project.py 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import errno
  18. import filecmp
  19. import glob
  20. import os
  21. import random
  22. import re
  23. import shutil
  24. import stat
  25. import subprocess
  26. import sys
  27. import tarfile
  28. import tempfile
  29. import time
  30. from color import Coloring
  31. from git_command import GitCommand, git_require
  32. from git_config import GitConfig, IsId, GetSchemeFromUrl, GetUrlCookieFile, \
  33. ID_RE
  34. from error import GitError, UploadError, DownloadError
  35. from error import ManifestInvalidRevisionError, ManifestInvalidPathError
  36. from error import NoManifestException
  37. import platform_utils
  38. import progress
  39. from repo_trace import IsTrace, Trace
  40. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M, R_WORKTREE_M
  41. from pyversion import is_python3
  42. if is_python3():
  43. import urllib.parse
  44. else:
  45. import imp
  46. import urlparse
  47. urllib = imp.new_module('urllib')
  48. urllib.parse = urlparse
  49. input = raw_input # noqa: F821
  50. # Maximum sleep time allowed during retries.
  51. MAXIMUM_RETRY_SLEEP_SEC = 3600.0
  52. # +-10% random jitter is added to each Fetches retry sleep duration.
  53. RETRY_JITTER_PERCENT = 0.1
  54. def _lwrite(path, content):
  55. lock = '%s.lock' % path
  56. with open(lock, 'w') as fd:
  57. fd.write(content)
  58. try:
  59. platform_utils.rename(lock, path)
  60. except OSError:
  61. platform_utils.remove(lock)
  62. raise
  63. def _error(fmt, *args):
  64. msg = fmt % args
  65. print('error: %s' % msg, file=sys.stderr)
  66. def _warn(fmt, *args):
  67. msg = fmt % args
  68. print('warn: %s' % msg, file=sys.stderr)
  69. def not_rev(r):
  70. return '^' + r
  71. def sq(r):
  72. return "'" + r.replace("'", "'\''") + "'"
  73. _project_hook_list = None
  74. def _ProjectHooks():
  75. """List the hooks present in the 'hooks' directory.
  76. These hooks are project hooks and are copied to the '.git/hooks' directory
  77. of all subprojects.
  78. This function caches the list of hooks (based on the contents of the
  79. 'repo/hooks' directory) on the first call.
  80. Returns:
  81. A list of absolute paths to all of the files in the hooks directory.
  82. """
  83. global _project_hook_list
  84. if _project_hook_list is None:
  85. d = platform_utils.realpath(os.path.abspath(os.path.dirname(__file__)))
  86. d = os.path.join(d, 'hooks')
  87. _project_hook_list = [os.path.join(d, x) for x in platform_utils.listdir(d)]
  88. return _project_hook_list
  89. class DownloadedChange(object):
  90. _commit_cache = None
  91. def __init__(self, project, base, change_id, ps_id, commit):
  92. self.project = project
  93. self.base = base
  94. self.change_id = change_id
  95. self.ps_id = ps_id
  96. self.commit = commit
  97. @property
  98. def commits(self):
  99. if self._commit_cache is None:
  100. self._commit_cache = self.project.bare_git.rev_list('--abbrev=8',
  101. '--abbrev-commit',
  102. '--pretty=oneline',
  103. '--reverse',
  104. '--date-order',
  105. not_rev(self.base),
  106. self.commit,
  107. '--')
  108. return self._commit_cache
  109. class ReviewableBranch(object):
  110. _commit_cache = None
  111. _base_exists = None
  112. def __init__(self, project, branch, base):
  113. self.project = project
  114. self.branch = branch
  115. self.base = base
  116. @property
  117. def name(self):
  118. return self.branch.name
  119. @property
  120. def commits(self):
  121. if self._commit_cache is None:
  122. args = ('--abbrev=8', '--abbrev-commit', '--pretty=oneline', '--reverse',
  123. '--date-order', not_rev(self.base), R_HEADS + self.name, '--')
  124. try:
  125. self._commit_cache = self.project.bare_git.rev_list(*args)
  126. except GitError:
  127. # We weren't able to probe the commits for this branch. Was it tracking
  128. # a branch that no longer exists? If so, return no commits. Otherwise,
  129. # rethrow the error as we don't know what's going on.
  130. if self.base_exists:
  131. raise
  132. self._commit_cache = []
  133. return self._commit_cache
  134. @property
  135. def unabbrev_commits(self):
  136. r = dict()
  137. for commit in self.project.bare_git.rev_list(not_rev(self.base),
  138. R_HEADS + self.name,
  139. '--'):
  140. r[commit[0:8]] = commit
  141. return r
  142. @property
  143. def date(self):
  144. return self.project.bare_git.log('--pretty=format:%cd',
  145. '-n', '1',
  146. R_HEADS + self.name,
  147. '--')
  148. @property
  149. def base_exists(self):
  150. """Whether the branch we're tracking exists.
  151. Normally it should, but sometimes branches we track can get deleted.
  152. """
  153. if self._base_exists is None:
  154. try:
  155. self.project.bare_git.rev_parse('--verify', not_rev(self.base))
  156. # If we're still here, the base branch exists.
  157. self._base_exists = True
  158. except GitError:
  159. # If we failed to verify, the base branch doesn't exist.
  160. self._base_exists = False
  161. return self._base_exists
  162. def UploadForReview(self, people,
  163. dryrun=False,
  164. auto_topic=False,
  165. hashtags=(),
  166. labels=(),
  167. private=False,
  168. notify=None,
  169. wip=False,
  170. dest_branch=None,
  171. validate_certs=True,
  172. push_options=None):
  173. self.project.UploadForReview(branch=self.name,
  174. people=people,
  175. dryrun=dryrun,
  176. auto_topic=auto_topic,
  177. hashtags=hashtags,
  178. labels=labels,
  179. private=private,
  180. notify=notify,
  181. wip=wip,
  182. dest_branch=dest_branch,
  183. validate_certs=validate_certs,
  184. push_options=push_options)
  185. def GetPublishedRefs(self):
  186. refs = {}
  187. output = self.project.bare_git.ls_remote(
  188. self.branch.remote.SshReviewUrl(self.project.UserEmail),
  189. 'refs/changes/*')
  190. for line in output.split('\n'):
  191. try:
  192. (sha, ref) = line.split()
  193. refs[sha] = ref
  194. except ValueError:
  195. pass
  196. return refs
  197. class StatusColoring(Coloring):
  198. def __init__(self, config):
  199. Coloring.__init__(self, config, 'status')
  200. self.project = self.printer('header', attr='bold')
  201. self.branch = self.printer('header', attr='bold')
  202. self.nobranch = self.printer('nobranch', fg='red')
  203. self.important = self.printer('important', fg='red')
  204. self.added = self.printer('added', fg='green')
  205. self.changed = self.printer('changed', fg='red')
  206. self.untracked = self.printer('untracked', fg='red')
  207. class DiffColoring(Coloring):
  208. def __init__(self, config):
  209. Coloring.__init__(self, config, 'diff')
  210. self.project = self.printer('header', attr='bold')
  211. self.fail = self.printer('fail', fg='red')
  212. class _Annotation(object):
  213. def __init__(self, name, value, keep):
  214. self.name = name
  215. self.value = value
  216. self.keep = keep
  217. def _SafeExpandPath(base, subpath, skipfinal=False):
  218. """Make sure |subpath| is completely safe under |base|.
  219. We make sure no intermediate symlinks are traversed, and that the final path
  220. is not a special file (e.g. not a socket or fifo).
  221. NB: We rely on a number of paths already being filtered out while parsing the
  222. manifest. See the validation logic in manifest_xml.py for more details.
  223. """
  224. # Split up the path by its components. We can't use os.path.sep exclusively
  225. # as some platforms (like Windows) will convert / to \ and that bypasses all
  226. # our constructed logic here. Especially since manifest authors only use
  227. # / in their paths.
  228. resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
  229. components = resep.split(subpath)
  230. if skipfinal:
  231. # Whether the caller handles the final component itself.
  232. finalpart = components.pop()
  233. path = base
  234. for part in components:
  235. if part in {'.', '..'}:
  236. raise ManifestInvalidPathError(
  237. '%s: "%s" not allowed in paths' % (subpath, part))
  238. path = os.path.join(path, part)
  239. if platform_utils.islink(path):
  240. raise ManifestInvalidPathError(
  241. '%s: traversing symlinks not allow' % (path,))
  242. if os.path.exists(path):
  243. if not os.path.isfile(path) and not platform_utils.isdir(path):
  244. raise ManifestInvalidPathError(
  245. '%s: only regular files & directories allowed' % (path,))
  246. if skipfinal:
  247. path = os.path.join(path, finalpart)
  248. return path
  249. class _CopyFile(object):
  250. """Container for <copyfile> manifest element."""
  251. def __init__(self, git_worktree, src, topdir, dest):
  252. """Register a <copyfile> request.
  253. Args:
  254. git_worktree: Absolute path to the git project checkout.
  255. src: Relative path under |git_worktree| of file to read.
  256. topdir: Absolute path to the top of the repo client checkout.
  257. dest: Relative path under |topdir| of file to write.
  258. """
  259. self.git_worktree = git_worktree
  260. self.topdir = topdir
  261. self.src = src
  262. self.dest = dest
  263. def _Copy(self):
  264. src = _SafeExpandPath(self.git_worktree, self.src)
  265. dest = _SafeExpandPath(self.topdir, self.dest)
  266. if platform_utils.isdir(src):
  267. raise ManifestInvalidPathError(
  268. '%s: copying from directory not supported' % (self.src,))
  269. if platform_utils.isdir(dest):
  270. raise ManifestInvalidPathError(
  271. '%s: copying to directory not allowed' % (self.dest,))
  272. # copy file if it does not exist or is out of date
  273. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  274. try:
  275. # remove existing file first, since it might be read-only
  276. if os.path.exists(dest):
  277. platform_utils.remove(dest)
  278. else:
  279. dest_dir = os.path.dirname(dest)
  280. if not platform_utils.isdir(dest_dir):
  281. os.makedirs(dest_dir)
  282. shutil.copy(src, dest)
  283. # make the file read-only
  284. mode = os.stat(dest)[stat.ST_MODE]
  285. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  286. os.chmod(dest, mode)
  287. except IOError:
  288. _error('Cannot copy file %s to %s', src, dest)
  289. class _LinkFile(object):
  290. """Container for <linkfile> manifest element."""
  291. def __init__(self, git_worktree, src, topdir, dest):
  292. """Register a <linkfile> request.
  293. Args:
  294. git_worktree: Absolute path to the git project checkout.
  295. src: Target of symlink relative to path under |git_worktree|.
  296. topdir: Absolute path to the top of the repo client checkout.
  297. dest: Relative path under |topdir| of symlink to create.
  298. """
  299. self.git_worktree = git_worktree
  300. self.topdir = topdir
  301. self.src = src
  302. self.dest = dest
  303. def __linkIt(self, relSrc, absDest):
  304. # link file if it does not exist or is out of date
  305. if not platform_utils.islink(absDest) or (platform_utils.readlink(absDest) != relSrc):
  306. try:
  307. # remove existing file first, since it might be read-only
  308. if os.path.lexists(absDest):
  309. platform_utils.remove(absDest)
  310. else:
  311. dest_dir = os.path.dirname(absDest)
  312. if not platform_utils.isdir(dest_dir):
  313. os.makedirs(dest_dir)
  314. platform_utils.symlink(relSrc, absDest)
  315. except IOError:
  316. _error('Cannot link file %s to %s', relSrc, absDest)
  317. def _Link(self):
  318. """Link the self.src & self.dest paths.
  319. Handles wild cards on the src linking all of the files in the source in to
  320. the destination directory.
  321. """
  322. # Some people use src="." to create stable links to projects. Lets allow
  323. # that but reject all other uses of "." to keep things simple.
  324. if self.src == '.':
  325. src = self.git_worktree
  326. else:
  327. src = _SafeExpandPath(self.git_worktree, self.src)
  328. if not glob.has_magic(src):
  329. # Entity does not contain a wild card so just a simple one to one link operation.
  330. dest = _SafeExpandPath(self.topdir, self.dest, skipfinal=True)
  331. # dest & src are absolute paths at this point. Make sure the target of
  332. # the symlink is relative in the context of the repo client checkout.
  333. relpath = os.path.relpath(src, os.path.dirname(dest))
  334. self.__linkIt(relpath, dest)
  335. else:
  336. dest = _SafeExpandPath(self.topdir, self.dest)
  337. # Entity contains a wild card.
  338. if os.path.exists(dest) and not platform_utils.isdir(dest):
  339. _error('Link error: src with wildcard, %s must be a directory', dest)
  340. else:
  341. for absSrcFile in glob.glob(src):
  342. # Create a releative path from source dir to destination dir
  343. absSrcDir = os.path.dirname(absSrcFile)
  344. relSrcDir = os.path.relpath(absSrcDir, dest)
  345. # Get the source file name
  346. srcFile = os.path.basename(absSrcFile)
  347. # Now form the final full paths to srcFile. They will be
  348. # absolute for the desintaiton and relative for the srouce.
  349. absDest = os.path.join(dest, srcFile)
  350. relSrc = os.path.join(relSrcDir, srcFile)
  351. self.__linkIt(relSrc, absDest)
  352. class RemoteSpec(object):
  353. def __init__(self,
  354. name,
  355. url=None,
  356. pushUrl=None,
  357. review=None,
  358. revision=None,
  359. orig_name=None,
  360. fetchUrl=None):
  361. self.name = name
  362. self.url = url
  363. self.pushUrl = pushUrl
  364. self.review = review
  365. self.revision = revision
  366. self.orig_name = orig_name
  367. self.fetchUrl = fetchUrl
  368. class Project(object):
  369. # These objects can be shared between several working trees.
  370. shareable_files = ['description', 'info']
  371. shareable_dirs = ['hooks', 'objects', 'rr-cache', 'svn']
  372. # These objects can only be used by a single working tree.
  373. working_tree_files = ['config', 'packed-refs', 'shallow']
  374. working_tree_dirs = ['logs', 'refs']
  375. def __init__(self,
  376. manifest,
  377. name,
  378. remote,
  379. gitdir,
  380. objdir,
  381. worktree,
  382. relpath,
  383. revisionExpr,
  384. revisionId,
  385. rebase=True,
  386. groups=None,
  387. sync_c=False,
  388. sync_s=False,
  389. sync_tags=True,
  390. clone_depth=None,
  391. upstream=None,
  392. parent=None,
  393. use_git_worktrees=False,
  394. is_derived=False,
  395. dest_branch=None,
  396. optimized_fetch=False,
  397. retry_fetches=0,
  398. old_revision=None):
  399. """Init a Project object.
  400. Args:
  401. manifest: The XmlManifest object.
  402. name: The `name` attribute of manifest.xml's project element.
  403. remote: RemoteSpec object specifying its remote's properties.
  404. gitdir: Absolute path of git directory.
  405. objdir: Absolute path of directory to store git objects.
  406. worktree: Absolute path of git working tree.
  407. relpath: Relative path of git working tree to repo's top directory.
  408. revisionExpr: The `revision` attribute of manifest.xml's project element.
  409. revisionId: git commit id for checking out.
  410. rebase: The `rebase` attribute of manifest.xml's project element.
  411. groups: The `groups` attribute of manifest.xml's project element.
  412. sync_c: The `sync-c` attribute of manifest.xml's project element.
  413. sync_s: The `sync-s` attribute of manifest.xml's project element.
  414. sync_tags: The `sync-tags` attribute of manifest.xml's project element.
  415. upstream: The `upstream` attribute of manifest.xml's project element.
  416. parent: The parent Project object.
  417. use_git_worktrees: Whether to use `git worktree` for this project.
  418. is_derived: False if the project was explicitly defined in the manifest;
  419. True if the project is a discovered submodule.
  420. dest_branch: The branch to which to push changes for review by default.
  421. optimized_fetch: If True, when a project is set to a sha1 revision, only
  422. fetch from the remote if the sha1 is not present locally.
  423. retry_fetches: Retry remote fetches n times upon receiving transient error
  424. with exponential backoff and jitter.
  425. old_revision: saved git commit id for open GITC projects.
  426. """
  427. self.client = self.manifest = manifest
  428. self.name = name
  429. self.remote = remote
  430. self.gitdir = gitdir.replace('\\', '/')
  431. self.objdir = objdir.replace('\\', '/')
  432. if worktree:
  433. self.worktree = os.path.normpath(worktree).replace('\\', '/')
  434. else:
  435. self.worktree = None
  436. self.relpath = relpath
  437. self.revisionExpr = revisionExpr
  438. if revisionId is None \
  439. and revisionExpr \
  440. and IsId(revisionExpr):
  441. self.revisionId = revisionExpr
  442. else:
  443. self.revisionId = revisionId
  444. self.rebase = rebase
  445. self.groups = groups
  446. self.sync_c = sync_c
  447. self.sync_s = sync_s
  448. self.sync_tags = sync_tags
  449. self.clone_depth = clone_depth
  450. self.upstream = upstream
  451. self.parent = parent
  452. # NB: Do not use this setting in __init__ to change behavior so that the
  453. # manifest.git checkout can inspect & change it after instantiating. See
  454. # the XmlManifest init code for more info.
  455. self.use_git_worktrees = use_git_worktrees
  456. self.is_derived = is_derived
  457. self.optimized_fetch = optimized_fetch
  458. self.retry_fetches = max(0, retry_fetches)
  459. self.subprojects = []
  460. self.snapshots = {}
  461. self.copyfiles = []
  462. self.linkfiles = []
  463. self.annotations = []
  464. self.config = GitConfig.ForRepository(gitdir=self.gitdir,
  465. defaults=self.client.globalConfig)
  466. if self.worktree:
  467. self.work_git = self._GitGetByExec(self, bare=False, gitdir=gitdir)
  468. else:
  469. self.work_git = None
  470. self.bare_git = self._GitGetByExec(self, bare=True, gitdir=gitdir)
  471. self.bare_ref = GitRefs(gitdir)
  472. self.bare_objdir = self._GitGetByExec(self, bare=True, gitdir=objdir)
  473. self.dest_branch = dest_branch
  474. self.old_revision = old_revision
  475. # This will be filled in if a project is later identified to be the
  476. # project containing repo hooks.
  477. self.enabled_repo_hooks = []
  478. @property
  479. def Derived(self):
  480. return self.is_derived
  481. @property
  482. def Exists(self):
  483. return platform_utils.isdir(self.gitdir) and platform_utils.isdir(self.objdir)
  484. @property
  485. def CurrentBranch(self):
  486. """Obtain the name of the currently checked out branch.
  487. The branch name omits the 'refs/heads/' prefix.
  488. None is returned if the project is on a detached HEAD, or if the work_git is
  489. otheriwse inaccessible (e.g. an incomplete sync).
  490. """
  491. try:
  492. b = self.work_git.GetHead()
  493. except NoManifestException:
  494. # If the local checkout is in a bad state, don't barf. Let the callers
  495. # process this like the head is unreadable.
  496. return None
  497. if b.startswith(R_HEADS):
  498. return b[len(R_HEADS):]
  499. return None
  500. def IsRebaseInProgress(self):
  501. return (os.path.exists(self.work_git.GetDotgitPath('rebase-apply')) or
  502. os.path.exists(self.work_git.GetDotgitPath('rebase-merge')) or
  503. os.path.exists(os.path.join(self.worktree, '.dotest')))
  504. def IsDirty(self, consider_untracked=True):
  505. """Is the working directory modified in some way?
  506. """
  507. self.work_git.update_index('-q',
  508. '--unmerged',
  509. '--ignore-missing',
  510. '--refresh')
  511. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  512. return True
  513. if self.work_git.DiffZ('diff-files'):
  514. return True
  515. if consider_untracked and self.work_git.LsOthers():
  516. return True
  517. return False
  518. _userident_name = None
  519. _userident_email = None
  520. @property
  521. def UserName(self):
  522. """Obtain the user's personal name.
  523. """
  524. if self._userident_name is None:
  525. self._LoadUserIdentity()
  526. return self._userident_name
  527. @property
  528. def UserEmail(self):
  529. """Obtain the user's email address. This is very likely
  530. to be their Gerrit login.
  531. """
  532. if self._userident_email is None:
  533. self._LoadUserIdentity()
  534. return self._userident_email
  535. def _LoadUserIdentity(self):
  536. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  537. m = re.compile("^(.*) <([^>]*)> ").match(u)
  538. if m:
  539. self._userident_name = m.group(1)
  540. self._userident_email = m.group(2)
  541. else:
  542. self._userident_name = ''
  543. self._userident_email = ''
  544. def GetRemote(self, name):
  545. """Get the configuration for a single remote.
  546. """
  547. return self.config.GetRemote(name)
  548. def GetBranch(self, name):
  549. """Get the configuration for a single branch.
  550. """
  551. return self.config.GetBranch(name)
  552. def GetBranches(self):
  553. """Get all existing local branches.
  554. """
  555. current = self.CurrentBranch
  556. all_refs = self._allrefs
  557. heads = {}
  558. for name, ref_id in all_refs.items():
  559. if name.startswith(R_HEADS):
  560. name = name[len(R_HEADS):]
  561. b = self.GetBranch(name)
  562. b.current = name == current
  563. b.published = None
  564. b.revision = ref_id
  565. heads[name] = b
  566. for name, ref_id in all_refs.items():
  567. if name.startswith(R_PUB):
  568. name = name[len(R_PUB):]
  569. b = heads.get(name)
  570. if b:
  571. b.published = ref_id
  572. return heads
  573. def MatchesGroups(self, manifest_groups):
  574. """Returns true if the manifest groups specified at init should cause
  575. this project to be synced.
  576. Prefixing a manifest group with "-" inverts the meaning of a group.
  577. All projects are implicitly labelled with "all".
  578. labels are resolved in order. In the example case of
  579. project_groups: "all,group1,group2"
  580. manifest_groups: "-group1,group2"
  581. the project will be matched.
  582. The special manifest group "default" will match any project that
  583. does not have the special project group "notdefault"
  584. """
  585. expanded_manifest_groups = manifest_groups or ['default']
  586. expanded_project_groups = ['all'] + (self.groups or [])
  587. if 'notdefault' not in expanded_project_groups:
  588. expanded_project_groups += ['default']
  589. matched = False
  590. for group in expanded_manifest_groups:
  591. if group.startswith('-') and group[1:] in expanded_project_groups:
  592. matched = False
  593. elif group in expanded_project_groups:
  594. matched = True
  595. return matched
  596. # Status Display ##
  597. def UncommitedFiles(self, get_all=True):
  598. """Returns a list of strings, uncommitted files in the git tree.
  599. Args:
  600. get_all: a boolean, if True - get information about all different
  601. uncommitted files. If False - return as soon as any kind of
  602. uncommitted files is detected.
  603. """
  604. details = []
  605. self.work_git.update_index('-q',
  606. '--unmerged',
  607. '--ignore-missing',
  608. '--refresh')
  609. if self.IsRebaseInProgress():
  610. details.append("rebase in progress")
  611. if not get_all:
  612. return details
  613. changes = self.work_git.DiffZ('diff-index', '--cached', HEAD).keys()
  614. if changes:
  615. details.extend(changes)
  616. if not get_all:
  617. return details
  618. changes = self.work_git.DiffZ('diff-files').keys()
  619. if changes:
  620. details.extend(changes)
  621. if not get_all:
  622. return details
  623. changes = self.work_git.LsOthers()
  624. if changes:
  625. details.extend(changes)
  626. return details
  627. def HasChanges(self):
  628. """Returns true if there are uncommitted changes.
  629. """
  630. if self.UncommitedFiles(get_all=False):
  631. return True
  632. else:
  633. return False
  634. def PrintWorkTreeStatus(self, output_redir=None, quiet=False):
  635. """Prints the status of the repository to stdout.
  636. Args:
  637. output_redir: If specified, redirect the output to this object.
  638. quiet: If True then only print the project name. Do not print
  639. the modified files, branch name, etc.
  640. """
  641. if not platform_utils.isdir(self.worktree):
  642. if output_redir is None:
  643. output_redir = sys.stdout
  644. print(file=output_redir)
  645. print('project %s/' % self.relpath, file=output_redir)
  646. print(' missing (run "repo sync")', file=output_redir)
  647. return
  648. self.work_git.update_index('-q',
  649. '--unmerged',
  650. '--ignore-missing',
  651. '--refresh')
  652. rb = self.IsRebaseInProgress()
  653. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  654. df = self.work_git.DiffZ('diff-files')
  655. do = self.work_git.LsOthers()
  656. if not rb and not di and not df and not do and not self.CurrentBranch:
  657. return 'CLEAN'
  658. out = StatusColoring(self.config)
  659. if output_redir is not None:
  660. out.redirect(output_redir)
  661. out.project('project %-40s', self.relpath + '/ ')
  662. if quiet:
  663. out.nl()
  664. return 'DIRTY'
  665. branch = self.CurrentBranch
  666. if branch is None:
  667. out.nobranch('(*** NO BRANCH ***)')
  668. else:
  669. out.branch('branch %s', branch)
  670. out.nl()
  671. if rb:
  672. out.important('prior sync failed; rebase still in progress')
  673. out.nl()
  674. paths = list()
  675. paths.extend(di.keys())
  676. paths.extend(df.keys())
  677. paths.extend(do)
  678. for p in sorted(set(paths)):
  679. try:
  680. i = di[p]
  681. except KeyError:
  682. i = None
  683. try:
  684. f = df[p]
  685. except KeyError:
  686. f = None
  687. if i:
  688. i_status = i.status.upper()
  689. else:
  690. i_status = '-'
  691. if f:
  692. f_status = f.status.lower()
  693. else:
  694. f_status = '-'
  695. if i and i.src_path:
  696. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  697. i.src_path, p, i.level)
  698. else:
  699. line = ' %s%s\t%s' % (i_status, f_status, p)
  700. if i and not f:
  701. out.added('%s', line)
  702. elif (i and f) or (not i and f):
  703. out.changed('%s', line)
  704. elif not i and not f:
  705. out.untracked('%s', line)
  706. else:
  707. out.write('%s', line)
  708. out.nl()
  709. return 'DIRTY'
  710. def PrintWorkTreeDiff(self, absolute_paths=False):
  711. """Prints the status of the repository to stdout.
  712. """
  713. out = DiffColoring(self.config)
  714. cmd = ['diff']
  715. if out.is_on:
  716. cmd.append('--color')
  717. cmd.append(HEAD)
  718. if absolute_paths:
  719. cmd.append('--src-prefix=a/%s/' % self.relpath)
  720. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  721. cmd.append('--')
  722. try:
  723. p = GitCommand(self,
  724. cmd,
  725. capture_stdout=True,
  726. capture_stderr=True)
  727. except GitError as e:
  728. out.nl()
  729. out.project('project %s/' % self.relpath)
  730. out.nl()
  731. out.fail('%s', str(e))
  732. out.nl()
  733. return False
  734. has_diff = False
  735. for line in p.process.stdout:
  736. if not hasattr(line, 'encode'):
  737. line = line.decode()
  738. if not has_diff:
  739. out.nl()
  740. out.project('project %s/' % self.relpath)
  741. out.nl()
  742. has_diff = True
  743. print(line[:-1])
  744. return p.Wait() == 0
  745. # Publish / Upload ##
  746. def WasPublished(self, branch, all_refs=None):
  747. """Was the branch published (uploaded) for code review?
  748. If so, returns the SHA-1 hash of the last published
  749. state for the branch.
  750. """
  751. key = R_PUB + branch
  752. if all_refs is None:
  753. try:
  754. return self.bare_git.rev_parse(key)
  755. except GitError:
  756. return None
  757. else:
  758. try:
  759. return all_refs[key]
  760. except KeyError:
  761. return None
  762. def CleanPublishedCache(self, all_refs=None):
  763. """Prunes any stale published refs.
  764. """
  765. if all_refs is None:
  766. all_refs = self._allrefs
  767. heads = set()
  768. canrm = {}
  769. for name, ref_id in all_refs.items():
  770. if name.startswith(R_HEADS):
  771. heads.add(name)
  772. elif name.startswith(R_PUB):
  773. canrm[name] = ref_id
  774. for name, ref_id in canrm.items():
  775. n = name[len(R_PUB):]
  776. if R_HEADS + n not in heads:
  777. self.bare_git.DeleteRef(name, ref_id)
  778. def GetUploadableBranches(self, selected_branch=None):
  779. """List any branches which can be uploaded for review.
  780. """
  781. heads = {}
  782. pubed = {}
  783. for name, ref_id in self._allrefs.items():
  784. if name.startswith(R_HEADS):
  785. heads[name[len(R_HEADS):]] = ref_id
  786. elif name.startswith(R_PUB):
  787. pubed[name[len(R_PUB):]] = ref_id
  788. ready = []
  789. for branch, ref_id in heads.items():
  790. if branch in pubed and pubed[branch] == ref_id:
  791. continue
  792. if selected_branch and branch != selected_branch:
  793. continue
  794. rb = self.GetUploadableBranch(branch)
  795. if rb:
  796. ready.append(rb)
  797. return ready
  798. def GetUploadableBranch(self, branch_name):
  799. """Get a single uploadable branch, or None.
  800. """
  801. branch = self.GetBranch(branch_name)
  802. base = branch.LocalMerge
  803. if branch.LocalMerge:
  804. rb = ReviewableBranch(self, branch, base)
  805. if rb.commits:
  806. return rb
  807. return None
  808. def UploadForReview(self, branch=None,
  809. people=([], []),
  810. dryrun=False,
  811. auto_topic=False,
  812. hashtags=(),
  813. labels=(),
  814. private=False,
  815. notify=None,
  816. wip=False,
  817. dest_branch=None,
  818. validate_certs=True,
  819. push_options=None):
  820. """Uploads the named branch for code review.
  821. """
  822. if branch is None:
  823. branch = self.CurrentBranch
  824. if branch is None:
  825. raise GitError('not currently on a branch')
  826. branch = self.GetBranch(branch)
  827. if not branch.LocalMerge:
  828. raise GitError('branch %s does not track a remote' % branch.name)
  829. if not branch.remote.review:
  830. raise GitError('remote %s has no review url' % branch.remote.name)
  831. if dest_branch is None:
  832. dest_branch = self.dest_branch
  833. if dest_branch is None:
  834. dest_branch = branch.merge
  835. if not dest_branch.startswith(R_HEADS):
  836. dest_branch = R_HEADS + dest_branch
  837. if not branch.remote.projectname:
  838. branch.remote.projectname = self.name
  839. branch.remote.Save()
  840. url = branch.remote.ReviewUrl(self.UserEmail, validate_certs)
  841. if url is None:
  842. raise UploadError('review not configured')
  843. cmd = ['push']
  844. if dryrun:
  845. cmd.append('-n')
  846. if url.startswith('ssh://'):
  847. cmd.append('--receive-pack=gerrit receive-pack')
  848. for push_option in (push_options or []):
  849. cmd.append('-o')
  850. cmd.append(push_option)
  851. cmd.append(url)
  852. if dest_branch.startswith(R_HEADS):
  853. dest_branch = dest_branch[len(R_HEADS):]
  854. ref_spec = '%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch)
  855. opts = []
  856. if auto_topic:
  857. opts += ['topic=' + branch.name]
  858. opts += ['t=%s' % p for p in hashtags]
  859. opts += ['l=%s' % p for p in labels]
  860. opts += ['r=%s' % p for p in people[0]]
  861. opts += ['cc=%s' % p for p in people[1]]
  862. if notify:
  863. opts += ['notify=' + notify]
  864. if private:
  865. opts += ['private']
  866. if wip:
  867. opts += ['wip']
  868. if opts:
  869. ref_spec = ref_spec + '%' + ','.join(opts)
  870. cmd.append(ref_spec)
  871. if GitCommand(self, cmd, bare=True).Wait() != 0:
  872. raise UploadError('Upload failed')
  873. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  874. self.bare_git.UpdateRef(R_PUB + branch.name,
  875. R_HEADS + branch.name,
  876. message=msg)
  877. # Sync ##
  878. def _ExtractArchive(self, tarpath, path=None):
  879. """Extract the given tar on its current location
  880. Args:
  881. - tarpath: The path to the actual tar file
  882. """
  883. try:
  884. with tarfile.open(tarpath, 'r') as tar:
  885. tar.extractall(path=path)
  886. return True
  887. except (IOError, tarfile.TarError) as e:
  888. _error("Cannot extract archive %s: %s", tarpath, str(e))
  889. return False
  890. def Sync_NetworkHalf(self,
  891. quiet=False,
  892. verbose=False,
  893. is_new=None,
  894. current_branch_only=False,
  895. force_sync=False,
  896. clone_bundle=True,
  897. tags=True,
  898. archive=False,
  899. optimized_fetch=False,
  900. retry_fetches=0,
  901. prune=False,
  902. submodules=False,
  903. clone_filter=None):
  904. """Perform only the network IO portion of the sync process.
  905. Local working directory/branch state is not affected.
  906. """
  907. if archive and not isinstance(self, MetaProject):
  908. if self.remote.url.startswith(('http://', 'https://')):
  909. _error("%s: Cannot fetch archives from http/https remotes.", self.name)
  910. return False
  911. name = self.relpath.replace('\\', '/')
  912. name = name.replace('/', '_')
  913. tarpath = '%s.tar' % name
  914. topdir = self.manifest.topdir
  915. try:
  916. self._FetchArchive(tarpath, cwd=topdir)
  917. except GitError as e:
  918. _error('%s', e)
  919. return False
  920. # From now on, we only need absolute tarpath
  921. tarpath = os.path.join(topdir, tarpath)
  922. if not self._ExtractArchive(tarpath, path=topdir):
  923. return False
  924. try:
  925. platform_utils.remove(tarpath)
  926. except OSError as e:
  927. _warn("Cannot remove archive %s: %s", tarpath, str(e))
  928. self._CopyAndLinkFiles()
  929. return True
  930. if is_new is None:
  931. is_new = not self.Exists
  932. if is_new:
  933. self._InitGitDir(force_sync=force_sync, quiet=quiet)
  934. else:
  935. self._UpdateHooks(quiet=quiet)
  936. self._InitRemote()
  937. if is_new:
  938. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  939. try:
  940. with open(alt) as fd:
  941. # This works for both absolute and relative alternate directories.
  942. alt_dir = os.path.join(self.objdir, 'objects', fd.readline().rstrip())
  943. except IOError:
  944. alt_dir = None
  945. else:
  946. alt_dir = None
  947. if (clone_bundle
  948. and alt_dir is None
  949. and self._ApplyCloneBundle(initial=is_new, quiet=quiet, verbose=verbose)):
  950. is_new = False
  951. if not current_branch_only:
  952. if self.sync_c:
  953. current_branch_only = True
  954. elif not self.manifest._loaded:
  955. # Manifest cannot check defaults until it syncs.
  956. current_branch_only = False
  957. elif self.manifest.default.sync_c:
  958. current_branch_only = True
  959. if not self.sync_tags:
  960. tags = False
  961. if self.clone_depth:
  962. depth = self.clone_depth
  963. else:
  964. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  965. # See if we can skip the network fetch entirely.
  966. if not (optimized_fetch and
  967. (ID_RE.match(self.revisionExpr) and
  968. self._CheckForImmutableRevision())):
  969. if not self._RemoteFetch(
  970. initial=is_new, quiet=quiet, verbose=verbose, alt_dir=alt_dir,
  971. current_branch_only=current_branch_only,
  972. tags=tags, prune=prune, depth=depth,
  973. submodules=submodules, force_sync=force_sync,
  974. clone_filter=clone_filter, retry_fetches=retry_fetches):
  975. return False
  976. mp = self.manifest.manifestProject
  977. dissociate = mp.config.GetBoolean('repo.dissociate')
  978. if dissociate:
  979. alternates_file = os.path.join(self.gitdir, 'objects/info/alternates')
  980. if os.path.exists(alternates_file):
  981. cmd = ['repack', '-a', '-d']
  982. if GitCommand(self, cmd, bare=True).Wait() != 0:
  983. return False
  984. platform_utils.remove(alternates_file)
  985. if self.worktree:
  986. self._InitMRef()
  987. else:
  988. self._InitMirrorHead()
  989. try:
  990. platform_utils.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  991. except OSError:
  992. pass
  993. return True
  994. def PostRepoUpgrade(self):
  995. self._InitHooks()
  996. def _CopyAndLinkFiles(self):
  997. if self.client.isGitcClient:
  998. return
  999. for copyfile in self.copyfiles:
  1000. copyfile._Copy()
  1001. for linkfile in self.linkfiles:
  1002. linkfile._Link()
  1003. def GetCommitRevisionId(self):
  1004. """Get revisionId of a commit.
  1005. Use this method instead of GetRevisionId to get the id of the commit rather
  1006. than the id of the current git object (for example, a tag)
  1007. """
  1008. if not self.revisionExpr.startswith(R_TAGS):
  1009. return self.GetRevisionId(self._allrefs)
  1010. try:
  1011. return self.bare_git.rev_list(self.revisionExpr, '-1')[0]
  1012. except GitError:
  1013. raise ManifestInvalidRevisionError('revision %s in %s not found' %
  1014. (self.revisionExpr, self.name))
  1015. def GetRevisionId(self, all_refs=None):
  1016. if self.revisionId:
  1017. return self.revisionId
  1018. rem = self.GetRemote(self.remote.name)
  1019. rev = rem.ToLocal(self.revisionExpr)
  1020. if all_refs is not None and rev in all_refs:
  1021. return all_refs[rev]
  1022. try:
  1023. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  1024. except GitError:
  1025. raise ManifestInvalidRevisionError('revision %s in %s not found' %
  1026. (self.revisionExpr, self.name))
  1027. def Sync_LocalHalf(self, syncbuf, force_sync=False, submodules=False):
  1028. """Perform only the local IO portion of the sync process.
  1029. Network access is not required.
  1030. """
  1031. if not os.path.exists(self.gitdir):
  1032. syncbuf.fail(self,
  1033. 'Cannot checkout %s due to missing network sync; Run '
  1034. '`repo sync -n %s` first.' %
  1035. (self.name, self.name))
  1036. return
  1037. self._InitWorkTree(force_sync=force_sync, submodules=submodules)
  1038. all_refs = self.bare_ref.all
  1039. self.CleanPublishedCache(all_refs)
  1040. revid = self.GetRevisionId(all_refs)
  1041. def _doff():
  1042. self._FastForward(revid)
  1043. self._CopyAndLinkFiles()
  1044. def _dosubmodules():
  1045. self._SyncSubmodules(quiet=True)
  1046. head = self.work_git.GetHead()
  1047. if head.startswith(R_HEADS):
  1048. branch = head[len(R_HEADS):]
  1049. try:
  1050. head = all_refs[head]
  1051. except KeyError:
  1052. head = None
  1053. else:
  1054. branch = None
  1055. if branch is None or syncbuf.detach_head:
  1056. # Currently on a detached HEAD. The user is assumed to
  1057. # not have any local modifications worth worrying about.
  1058. #
  1059. if self.IsRebaseInProgress():
  1060. syncbuf.fail(self, _PriorSyncFailedError())
  1061. return
  1062. if head == revid:
  1063. # No changes; don't do anything further.
  1064. # Except if the head needs to be detached
  1065. #
  1066. if not syncbuf.detach_head:
  1067. # The copy/linkfile config may have changed.
  1068. self._CopyAndLinkFiles()
  1069. return
  1070. else:
  1071. lost = self._revlist(not_rev(revid), HEAD)
  1072. if lost:
  1073. syncbuf.info(self, "discarding %d commits", len(lost))
  1074. try:
  1075. self._Checkout(revid, quiet=True)
  1076. if submodules:
  1077. self._SyncSubmodules(quiet=True)
  1078. except GitError as e:
  1079. syncbuf.fail(self, e)
  1080. return
  1081. self._CopyAndLinkFiles()
  1082. return
  1083. if head == revid:
  1084. # No changes; don't do anything further.
  1085. #
  1086. # The copy/linkfile config may have changed.
  1087. self._CopyAndLinkFiles()
  1088. return
  1089. branch = self.GetBranch(branch)
  1090. if not branch.LocalMerge:
  1091. # The current branch has no tracking configuration.
  1092. # Jump off it to a detached HEAD.
  1093. #
  1094. syncbuf.info(self,
  1095. "leaving %s; does not track upstream",
  1096. branch.name)
  1097. try:
  1098. self._Checkout(revid, quiet=True)
  1099. if submodules:
  1100. self._SyncSubmodules(quiet=True)
  1101. except GitError as e:
  1102. syncbuf.fail(self, e)
  1103. return
  1104. self._CopyAndLinkFiles()
  1105. return
  1106. upstream_gain = self._revlist(not_rev(HEAD), revid)
  1107. # See if we can perform a fast forward merge. This can happen if our
  1108. # branch isn't in the exact same state as we last published.
  1109. try:
  1110. self.work_git.merge_base('--is-ancestor', HEAD, revid)
  1111. # Skip the published logic.
  1112. pub = False
  1113. except GitError:
  1114. pub = self.WasPublished(branch.name, all_refs)
  1115. if pub:
  1116. not_merged = self._revlist(not_rev(revid), pub)
  1117. if not_merged:
  1118. if upstream_gain:
  1119. # The user has published this branch and some of those
  1120. # commits are not yet merged upstream. We do not want
  1121. # to rewrite the published commits so we punt.
  1122. #
  1123. syncbuf.fail(self,
  1124. "branch %s is published (but not merged) and is now "
  1125. "%d commits behind" % (branch.name, len(upstream_gain)))
  1126. return
  1127. elif pub == head:
  1128. # All published commits are merged, and thus we are a
  1129. # strict subset. We can fast-forward safely.
  1130. #
  1131. syncbuf.later1(self, _doff)
  1132. if submodules:
  1133. syncbuf.later1(self, _dosubmodules)
  1134. return
  1135. # Examine the local commits not in the remote. Find the
  1136. # last one attributed to this user, if any.
  1137. #
  1138. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  1139. last_mine = None
  1140. cnt_mine = 0
  1141. for commit in local_changes:
  1142. commit_id, committer_email = commit.split(' ', 1)
  1143. if committer_email == self.UserEmail:
  1144. last_mine = commit_id
  1145. cnt_mine += 1
  1146. if not upstream_gain and cnt_mine == len(local_changes):
  1147. return
  1148. if self.IsDirty(consider_untracked=False):
  1149. syncbuf.fail(self, _DirtyError())
  1150. return
  1151. # If the upstream switched on us, warn the user.
  1152. #
  1153. if branch.merge != self.revisionExpr:
  1154. if branch.merge and self.revisionExpr:
  1155. syncbuf.info(self,
  1156. 'manifest switched %s...%s',
  1157. branch.merge,
  1158. self.revisionExpr)
  1159. elif branch.merge:
  1160. syncbuf.info(self,
  1161. 'manifest no longer tracks %s',
  1162. branch.merge)
  1163. if cnt_mine < len(local_changes):
  1164. # Upstream rebased. Not everything in HEAD
  1165. # was created by this user.
  1166. #
  1167. syncbuf.info(self,
  1168. "discarding %d commits removed from upstream",
  1169. len(local_changes) - cnt_mine)
  1170. branch.remote = self.GetRemote(self.remote.name)
  1171. if not ID_RE.match(self.revisionExpr):
  1172. # in case of manifest sync the revisionExpr might be a SHA1
  1173. branch.merge = self.revisionExpr
  1174. if not branch.merge.startswith('refs/'):
  1175. branch.merge = R_HEADS + branch.merge
  1176. branch.Save()
  1177. if cnt_mine > 0 and self.rebase:
  1178. def _docopyandlink():
  1179. self._CopyAndLinkFiles()
  1180. def _dorebase():
  1181. self._Rebase(upstream='%s^1' % last_mine, onto=revid)
  1182. syncbuf.later2(self, _dorebase)
  1183. if submodules:
  1184. syncbuf.later2(self, _dosubmodules)
  1185. syncbuf.later2(self, _docopyandlink)
  1186. elif local_changes:
  1187. try:
  1188. self._ResetHard(revid)
  1189. if submodules:
  1190. self._SyncSubmodules(quiet=True)
  1191. self._CopyAndLinkFiles()
  1192. except GitError as e:
  1193. syncbuf.fail(self, e)
  1194. return
  1195. else:
  1196. syncbuf.later1(self, _doff)
  1197. if submodules:
  1198. syncbuf.later1(self, _dosubmodules)
  1199. def AddCopyFile(self, src, dest, topdir):
  1200. """Mark |src| for copying to |dest| (relative to |topdir|).
  1201. No filesystem changes occur here. Actual copying happens later on.
  1202. Paths should have basic validation run on them before being queued.
  1203. Further checking will be handled when the actual copy happens.
  1204. """
  1205. self.copyfiles.append(_CopyFile(self.worktree, src, topdir, dest))
  1206. def AddLinkFile(self, src, dest, topdir):
  1207. """Mark |dest| to create a symlink (relative to |topdir|) pointing to |src|.
  1208. No filesystem changes occur here. Actual linking happens later on.
  1209. Paths should have basic validation run on them before being queued.
  1210. Further checking will be handled when the actual link happens.
  1211. """
  1212. self.linkfiles.append(_LinkFile(self.worktree, src, topdir, dest))
  1213. def AddAnnotation(self, name, value, keep):
  1214. self.annotations.append(_Annotation(name, value, keep))
  1215. def DownloadPatchSet(self, change_id, patch_id):
  1216. """Download a single patch set of a single change to FETCH_HEAD.
  1217. """
  1218. remote = self.GetRemote(self.remote.name)
  1219. cmd = ['fetch', remote.name]
  1220. cmd.append('refs/changes/%2.2d/%d/%d'
  1221. % (change_id % 100, change_id, patch_id))
  1222. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1223. return None
  1224. return DownloadedChange(self,
  1225. self.GetRevisionId(),
  1226. change_id,
  1227. patch_id,
  1228. self.bare_git.rev_parse('FETCH_HEAD'))
  1229. def DeleteWorktree(self, quiet=False, force=False):
  1230. """Delete the source checkout and any other housekeeping tasks.
  1231. This currently leaves behind the internal .repo/ cache state. This helps
  1232. when switching branches or manifest changes get reverted as we don't have
  1233. to redownload all the git objects. But we should do some GC at some point.
  1234. Args:
  1235. quiet: Whether to hide normal messages.
  1236. force: Always delete tree even if dirty.
  1237. Returns:
  1238. True if the worktree was completely cleaned out.
  1239. """
  1240. if self.IsDirty():
  1241. if force:
  1242. print('warning: %s: Removing dirty project: uncommitted changes lost.' %
  1243. (self.relpath,), file=sys.stderr)
  1244. else:
  1245. print('error: %s: Cannot remove project: uncommitted changes are '
  1246. 'present.\n' % (self.relpath,), file=sys.stderr)
  1247. return False
  1248. if not quiet:
  1249. print('%s: Deleting obsolete checkout.' % (self.relpath,))
  1250. # Unlock and delink from the main worktree. We don't use git's worktree
  1251. # remove because it will recursively delete projects -- we handle that
  1252. # ourselves below. https://crbug.com/git/48
  1253. if self.use_git_worktrees:
  1254. needle = platform_utils.realpath(self.gitdir)
  1255. # Find the git worktree commondir under .repo/worktrees/.
  1256. output = self.bare_git.worktree('list', '--porcelain').splitlines()[0]
  1257. assert output.startswith('worktree '), output
  1258. commondir = output[9:]
  1259. # Walk each of the git worktrees to see where they point.
  1260. configs = os.path.join(commondir, 'worktrees')
  1261. for name in os.listdir(configs):
  1262. gitdir = os.path.join(configs, name, 'gitdir')
  1263. with open(gitdir) as fp:
  1264. relpath = fp.read().strip()
  1265. # Resolve the checkout path and see if it matches this project.
  1266. fullpath = platform_utils.realpath(os.path.join(configs, name, relpath))
  1267. if fullpath == needle:
  1268. platform_utils.rmtree(os.path.join(configs, name))
  1269. # Delete the .git directory first, so we're less likely to have a partially
  1270. # working git repository around. There shouldn't be any git projects here,
  1271. # so rmtree works.
  1272. # Try to remove plain files first in case of git worktrees. If this fails
  1273. # for any reason, we'll fall back to rmtree, and that'll display errors if
  1274. # it can't remove things either.
  1275. try:
  1276. platform_utils.remove(self.gitdir)
  1277. except OSError:
  1278. pass
  1279. try:
  1280. platform_utils.rmtree(self.gitdir)
  1281. except OSError as e:
  1282. if e.errno != errno.ENOENT:
  1283. print('error: %s: %s' % (self.gitdir, e), file=sys.stderr)
  1284. print('error: %s: Failed to delete obsolete checkout; remove manually, '
  1285. 'then run `repo sync -l`.' % (self.relpath,), file=sys.stderr)
  1286. return False
  1287. # Delete everything under the worktree, except for directories that contain
  1288. # another git project.
  1289. dirs_to_remove = []
  1290. failed = False
  1291. for root, dirs, files in platform_utils.walk(self.worktree):
  1292. for f in files:
  1293. path = os.path.join(root, f)
  1294. try:
  1295. platform_utils.remove(path)
  1296. except OSError as e:
  1297. if e.errno != errno.ENOENT:
  1298. print('error: %s: Failed to remove: %s' % (path, e), file=sys.stderr)
  1299. failed = True
  1300. dirs[:] = [d for d in dirs
  1301. if not os.path.lexists(os.path.join(root, d, '.git'))]
  1302. dirs_to_remove += [os.path.join(root, d) for d in dirs
  1303. if os.path.join(root, d) not in dirs_to_remove]
  1304. for d in reversed(dirs_to_remove):
  1305. if platform_utils.islink(d):
  1306. try:
  1307. platform_utils.remove(d)
  1308. except OSError as e:
  1309. if e.errno != errno.ENOENT:
  1310. print('error: %s: Failed to remove: %s' % (d, e), file=sys.stderr)
  1311. failed = True
  1312. elif not platform_utils.listdir(d):
  1313. try:
  1314. platform_utils.rmdir(d)
  1315. except OSError as e:
  1316. if e.errno != errno.ENOENT:
  1317. print('error: %s: Failed to remove: %s' % (d, e), file=sys.stderr)
  1318. failed = True
  1319. if failed:
  1320. print('error: %s: Failed to delete obsolete checkout.' % (self.relpath,),
  1321. file=sys.stderr)
  1322. print(' Remove manually, then run `repo sync -l`.', file=sys.stderr)
  1323. return False
  1324. # Try deleting parent dirs if they are empty.
  1325. path = self.worktree
  1326. while path != self.manifest.topdir:
  1327. try:
  1328. platform_utils.rmdir(path)
  1329. except OSError as e:
  1330. if e.errno != errno.ENOENT:
  1331. break
  1332. path = os.path.dirname(path)
  1333. return True
  1334. # Branch Management ##
  1335. def StartBranch(self, name, branch_merge='', revision=None):
  1336. """Create a new branch off the manifest's revision.
  1337. """
  1338. if not branch_merge:
  1339. branch_merge = self.revisionExpr
  1340. head = self.work_git.GetHead()
  1341. if head == (R_HEADS + name):
  1342. return True
  1343. all_refs = self.bare_ref.all
  1344. if R_HEADS + name in all_refs:
  1345. return GitCommand(self,
  1346. ['checkout', name, '--'],
  1347. capture_stdout=True,
  1348. capture_stderr=True).Wait() == 0
  1349. branch = self.GetBranch(name)
  1350. branch.remote = self.GetRemote(self.remote.name)
  1351. branch.merge = branch_merge
  1352. if not branch.merge.startswith('refs/') and not ID_RE.match(branch_merge):
  1353. branch.merge = R_HEADS + branch_merge
  1354. if revision is None:
  1355. revid = self.GetRevisionId(all_refs)
  1356. else:
  1357. revid = self.work_git.rev_parse(revision)
  1358. if head.startswith(R_HEADS):
  1359. try:
  1360. head = all_refs[head]
  1361. except KeyError:
  1362. head = None
  1363. if revid and head and revid == head:
  1364. ref = R_HEADS + name
  1365. self.work_git.update_ref(ref, revid)
  1366. self.work_git.symbolic_ref(HEAD, ref)
  1367. branch.Save()
  1368. return True
  1369. if GitCommand(self,
  1370. ['checkout', '-b', branch.name, revid],
  1371. capture_stdout=True,
  1372. capture_stderr=True).Wait() == 0:
  1373. branch.Save()
  1374. return True
  1375. return False
  1376. def CheckoutBranch(self, name):
  1377. """Checkout a local topic branch.
  1378. Args:
  1379. name: The name of the branch to checkout.
  1380. Returns:
  1381. True if the checkout succeeded; False if it didn't; None if the branch
  1382. didn't exist.
  1383. """
  1384. rev = R_HEADS + name
  1385. head = self.work_git.GetHead()
  1386. if head == rev:
  1387. # Already on the branch
  1388. #
  1389. return True
  1390. all_refs = self.bare_ref.all
  1391. try:
  1392. revid = all_refs[rev]
  1393. except KeyError:
  1394. # Branch does not exist in this project
  1395. #
  1396. return None
  1397. if head.startswith(R_HEADS):
  1398. try:
  1399. head = all_refs[head]
  1400. except KeyError:
  1401. head = None
  1402. if head == revid:
  1403. # Same revision; just update HEAD to point to the new
  1404. # target branch, but otherwise take no other action.
  1405. #
  1406. _lwrite(self.work_git.GetDotgitPath(subpath=HEAD),
  1407. 'ref: %s%s\n' % (R_HEADS, name))
  1408. return True
  1409. return GitCommand(self,
  1410. ['checkout', name, '--'],
  1411. capture_stdout=True,
  1412. capture_stderr=True).Wait() == 0
  1413. def AbandonBranch(self, name):
  1414. """Destroy a local topic branch.
  1415. Args:
  1416. name: The name of the branch to abandon.
  1417. Returns:
  1418. True if the abandon succeeded; False if it didn't; None if the branch
  1419. didn't exist.
  1420. """
  1421. rev = R_HEADS + name
  1422. all_refs = self.bare_ref.all
  1423. if rev not in all_refs:
  1424. # Doesn't exist
  1425. return None
  1426. head = self.work_git.GetHead()
  1427. if head == rev:
  1428. # We can't destroy the branch while we are sitting
  1429. # on it. Switch to a detached HEAD.
  1430. #
  1431. head = all_refs[head]
  1432. revid = self.GetRevisionId(all_refs)
  1433. if head == revid:
  1434. _lwrite(self.work_git.GetDotgitPath(subpath=HEAD), '%s\n' % revid)
  1435. else:
  1436. self._Checkout(revid, quiet=True)
  1437. return GitCommand(self,
  1438. ['branch', '-D', name],
  1439. capture_stdout=True,
  1440. capture_stderr=True).Wait() == 0
  1441. def PruneHeads(self):
  1442. """Prune any topic branches already merged into upstream.
  1443. """
  1444. cb = self.CurrentBranch
  1445. kill = []
  1446. left = self._allrefs
  1447. for name in left.keys():
  1448. if name.startswith(R_HEADS):
  1449. name = name[len(R_HEADS):]
  1450. if cb is None or name != cb:
  1451. kill.append(name)
  1452. rev = self.GetRevisionId(left)
  1453. if cb is not None \
  1454. and not self._revlist(HEAD + '...' + rev) \
  1455. and not self.IsDirty(consider_untracked=False):
  1456. self.work_git.DetachHead(HEAD)
  1457. kill.append(cb)
  1458. if kill:
  1459. old = self.bare_git.GetHead()
  1460. try:
  1461. self.bare_git.DetachHead(rev)
  1462. b = ['branch', '-d']
  1463. b.extend(kill)
  1464. b = GitCommand(self, b, bare=True,
  1465. capture_stdout=True,
  1466. capture_stderr=True)
  1467. b.Wait()
  1468. finally:
  1469. if ID_RE.match(old):
  1470. self.bare_git.DetachHead(old)
  1471. else:
  1472. self.bare_git.SetHead(old)
  1473. left = self._allrefs
  1474. for branch in kill:
  1475. if (R_HEADS + branch) not in left:
  1476. self.CleanPublishedCache()
  1477. break
  1478. if cb and cb not in kill:
  1479. kill.append(cb)
  1480. kill.sort()
  1481. kept = []
  1482. for branch in kill:
  1483. if R_HEADS + branch in left:
  1484. branch = self.GetBranch(branch)
  1485. base = branch.LocalMerge
  1486. if not base:
  1487. base = rev
  1488. kept.append(ReviewableBranch(self, branch, base))
  1489. return kept
  1490. # Submodule Management ##
  1491. def GetRegisteredSubprojects(self):
  1492. result = []
  1493. def rec(subprojects):
  1494. if not subprojects:
  1495. return
  1496. result.extend(subprojects)
  1497. for p in subprojects:
  1498. rec(p.subprojects)
  1499. rec(self.subprojects)
  1500. return result
  1501. def _GetSubmodules(self):
  1502. # Unfortunately we cannot call `git submodule status --recursive` here
  1503. # because the working tree might not exist yet, and it cannot be used
  1504. # without a working tree in its current implementation.
  1505. def get_submodules(gitdir, rev):
  1506. # Parse .gitmodules for submodule sub_paths and sub_urls
  1507. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1508. if not sub_paths:
  1509. return []
  1510. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1511. # revision of submodule repository
  1512. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1513. submodules = []
  1514. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1515. try:
  1516. sub_rev = sub_revs[sub_path]
  1517. except KeyError:
  1518. # Ignore non-exist submodules
  1519. continue
  1520. submodules.append((sub_rev, sub_path, sub_url))
  1521. return submodules
  1522. re_path = re.compile(r'^submodule\.(.+)\.path=(.*)$')
  1523. re_url = re.compile(r'^submodule\.(.+)\.url=(.*)$')
  1524. def parse_gitmodules(gitdir, rev):
  1525. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1526. try:
  1527. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1528. bare=True, gitdir=gitdir)
  1529. except GitError:
  1530. return [], []
  1531. if p.Wait() != 0:
  1532. return [], []
  1533. gitmodules_lines = []
  1534. fd, temp_gitmodules_path = tempfile.mkstemp()
  1535. try:
  1536. os.write(fd, p.stdout.encode('utf-8'))
  1537. os.close(fd)
  1538. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1539. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1540. bare=True, gitdir=gitdir)
  1541. if p.Wait() != 0:
  1542. return [], []
  1543. gitmodules_lines = p.stdout.split('\n')
  1544. except GitError:
  1545. return [], []
  1546. finally:
  1547. platform_utils.remove(temp_gitmodules_path)
  1548. names = set()
  1549. paths = {}
  1550. urls = {}
  1551. for line in gitmodules_lines:
  1552. if not line:
  1553. continue
  1554. m = re_path.match(line)
  1555. if m:
  1556. names.add(m.group(1))
  1557. paths[m.group(1)] = m.group(2)
  1558. continue
  1559. m = re_url.match(line)
  1560. if m:
  1561. names.add(m.group(1))
  1562. urls[m.group(1)] = m.group(2)
  1563. continue
  1564. names = sorted(names)
  1565. return ([paths.get(name, '') for name in names],
  1566. [urls.get(name, '') for name in names])
  1567. def git_ls_tree(gitdir, rev, paths):
  1568. cmd = ['ls-tree', rev, '--']
  1569. cmd.extend(paths)
  1570. try:
  1571. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1572. bare=True, gitdir=gitdir)
  1573. except GitError:
  1574. return []
  1575. if p.Wait() != 0:
  1576. return []
  1577. objects = {}
  1578. for line in p.stdout.split('\n'):
  1579. if not line.strip():
  1580. continue
  1581. object_rev, object_path = line.split()[2:4]
  1582. objects[object_path] = object_rev
  1583. return objects
  1584. try:
  1585. rev = self.GetRevisionId()
  1586. except GitError:
  1587. return []
  1588. return get_submodules(self.gitdir, rev)
  1589. def GetDerivedSubprojects(self):
  1590. result = []
  1591. if not self.Exists:
  1592. # If git repo does not exist yet, querying its submodules will
  1593. # mess up its states; so return here.
  1594. return result
  1595. for rev, path, url in self._GetSubmodules():
  1596. name = self.manifest.GetSubprojectName(self, path)
  1597. relpath, worktree, gitdir, objdir = \
  1598. self.manifest.GetSubprojectPaths(self, name, path)
  1599. project = self.manifest.paths.get(relpath)
  1600. if project:
  1601. result.extend(project.GetDerivedSubprojects())
  1602. continue
  1603. if url.startswith('..'):
  1604. url = urllib.parse.urljoin("%s/" % self.remote.url, url)
  1605. remote = RemoteSpec(self.remote.name,
  1606. url=url,
  1607. pushUrl=self.remote.pushUrl,
  1608. review=self.remote.review,
  1609. revision=self.remote.revision)
  1610. subproject = Project(manifest=self.manifest,
  1611. name=name,
  1612. remote=remote,
  1613. gitdir=gitdir,
  1614. objdir=objdir,
  1615. worktree=worktree,
  1616. relpath=relpath,
  1617. revisionExpr=rev,
  1618. revisionId=rev,
  1619. rebase=self.rebase,
  1620. groups=self.groups,
  1621. sync_c=self.sync_c,
  1622. sync_s=self.sync_s,
  1623. sync_tags=self.sync_tags,
  1624. parent=self,
  1625. is_derived=True)
  1626. result.append(subproject)
  1627. result.extend(subproject.GetDerivedSubprojects())
  1628. return result
  1629. # Direct Git Commands ##
  1630. def EnableRepositoryExtension(self, key, value='true', version=1):
  1631. """Enable git repository extension |key| with |value|.
  1632. Args:
  1633. key: The extension to enabled. Omit the "extensions." prefix.
  1634. value: The value to use for the extension.
  1635. version: The minimum git repository version needed.
  1636. """
  1637. # Make sure the git repo version is new enough already.
  1638. found_version = self.config.GetInt('core.repositoryFormatVersion')
  1639. if found_version is None:
  1640. found_version = 0
  1641. if found_version < version:
  1642. self.config.SetString('core.repositoryFormatVersion', str(version))
  1643. # Enable the extension!
  1644. self.config.SetString('extensions.%s' % (key,), value)
  1645. def ResolveRemoteHead(self, name=None):
  1646. """Find out what the default branch (HEAD) points to.
  1647. Normally this points to refs/heads/master, but projects are moving to main.
  1648. Support whatever the server uses rather than hardcoding "master" ourselves.
  1649. """
  1650. if name is None:
  1651. name = self.remote.name
  1652. # The output will look like (NB: tabs are separators):
  1653. # ref: refs/heads/master HEAD
  1654. # 5f6803b100bb3cd0f534e96e88c91373e8ed1c44 HEAD
  1655. output = self.bare_git.ls_remote('-q', '--symref', '--exit-code', name, 'HEAD')
  1656. for line in output.splitlines():
  1657. lhs, rhs = line.split('\t', 1)
  1658. if rhs == 'HEAD' and lhs.startswith('ref:'):
  1659. return lhs[4:].strip()
  1660. return None
  1661. def _CheckForImmutableRevision(self):
  1662. try:
  1663. # if revision (sha or tag) is not present then following function
  1664. # throws an error.
  1665. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1666. return True
  1667. except GitError:
  1668. # There is no such persistent revision. We have to fetch it.
  1669. return False
  1670. def _FetchArchive(self, tarpath, cwd=None):
  1671. cmd = ['archive', '-v', '-o', tarpath]
  1672. cmd.append('--remote=%s' % self.remote.url)
  1673. cmd.append('--prefix=%s/' % self.relpath)
  1674. cmd.append(self.revisionExpr)
  1675. command = GitCommand(self, cmd, cwd=cwd,
  1676. capture_stdout=True,
  1677. capture_stderr=True)
  1678. if command.Wait() != 0:
  1679. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1680. def _RemoteFetch(self, name=None,
  1681. current_branch_only=False,
  1682. initial=False,
  1683. quiet=False,
  1684. verbose=False,
  1685. alt_dir=None,
  1686. tags=True,
  1687. prune=False,
  1688. depth=None,
  1689. submodules=False,
  1690. force_sync=False,
  1691. clone_filter=None,
  1692. retry_fetches=2,
  1693. retry_sleep_initial_sec=4.0,
  1694. retry_exp_factor=2.0):
  1695. is_sha1 = False
  1696. tag_name = None
  1697. # The depth should not be used when fetching to a mirror because
  1698. # it will result in a shallow repository that cannot be cloned or
  1699. # fetched from.
  1700. # The repo project should also never be synced with partial depth.
  1701. if self.manifest.IsMirror or self.relpath == '.repo/repo':
  1702. depth = None
  1703. if depth:
  1704. current_branch_only = True
  1705. if ID_RE.match(self.revisionExpr) is not None:
  1706. is_sha1 = True
  1707. if current_branch_only:
  1708. if self.revisionExpr.startswith(R_TAGS):
  1709. # this is a tag and its sha1 value should never change
  1710. tag_name = self.revisionExpr[len(R_TAGS):]
  1711. if is_sha1 or tag_name is not None:
  1712. if self._CheckForImmutableRevision():
  1713. if verbose:
  1714. print('Skipped fetching project %s (already have persistent ref)'
  1715. % self.name)
  1716. return True
  1717. if is_sha1 and not depth:
  1718. # When syncing a specific commit and --depth is not set:
  1719. # * if upstream is explicitly specified and is not a sha1, fetch only
  1720. # upstream as users expect only upstream to be fetch.
  1721. # Note: The commit might not be in upstream in which case the sync
  1722. # will fail.
  1723. # * otherwise, fetch all branches to make sure we end up with the
  1724. # specific commit.
  1725. if self.upstream:
  1726. current_branch_only = not ID_RE.match(self.upstream)
  1727. else:
  1728. current_branch_only = False
  1729. if not name:
  1730. name = self.remote.name
  1731. ssh_proxy = False
  1732. remote = self.GetRemote(name)
  1733. if remote.PreConnectFetch():
  1734. ssh_proxy = True
  1735. if initial:
  1736. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1737. ref_dir = os.path.dirname(alt_dir)
  1738. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1739. remote = self.GetRemote(name)
  1740. all_refs = self.bare_ref.all
  1741. ids = set(all_refs.values())
  1742. tmp = set()
  1743. for r, ref_id in GitRefs(ref_dir).all.items():
  1744. if r not in all_refs:
  1745. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1746. all_refs[r] = ref_id
  1747. ids.add(ref_id)
  1748. continue
  1749. if ref_id in ids:
  1750. continue
  1751. r = 'refs/_alt/%s' % ref_id
  1752. all_refs[r] = ref_id
  1753. ids.add(ref_id)
  1754. tmp.add(r)
  1755. tmp_packed_lines = []
  1756. old_packed_lines = []
  1757. for r in sorted(all_refs):
  1758. line = '%s %s\n' % (all_refs[r], r)
  1759. tmp_packed_lines.append(line)
  1760. if r not in tmp:
  1761. old_packed_lines.append(line)
  1762. tmp_packed = ''.join(tmp_packed_lines)
  1763. old_packed = ''.join(old_packed_lines)
  1764. _lwrite(packed_refs, tmp_packed)
  1765. else:
  1766. alt_dir = None
  1767. cmd = ['fetch']
  1768. if clone_filter:
  1769. git_require((2, 19, 0), fail=True, msg='partial clones')
  1770. cmd.append('--filter=%s' % clone_filter)
  1771. self.EnableRepositoryExtension('partialclone', self.remote.name)
  1772. if depth:
  1773. cmd.append('--depth=%s' % depth)
  1774. else:
  1775. # If this repo has shallow objects, then we don't know which refs have
  1776. # shallow objects or not. Tell git to unshallow all fetched refs. Don't
  1777. # do this with projects that don't have shallow objects, since it is less
  1778. # efficient.
  1779. if os.path.exists(os.path.join(self.gitdir, 'shallow')):
  1780. cmd.append('--depth=2147483647')
  1781. if not verbose:
  1782. cmd.append('--quiet')
  1783. if not quiet and sys.stdout.isatty():
  1784. cmd.append('--progress')
  1785. if not self.worktree:
  1786. cmd.append('--update-head-ok')
  1787. cmd.append(name)
  1788. if force_sync:
  1789. cmd.append('--force')
  1790. if prune:
  1791. cmd.append('--prune')
  1792. if submodules:
  1793. cmd.append('--recurse-submodules=on-demand')
  1794. spec = []
  1795. if not current_branch_only:
  1796. # Fetch whole repo
  1797. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1798. elif tag_name is not None:
  1799. spec.append('tag')
  1800. spec.append(tag_name)
  1801. if self.manifest.IsMirror and not current_branch_only:
  1802. branch = None
  1803. else:
  1804. branch = self.revisionExpr
  1805. if (not self.manifest.IsMirror and is_sha1 and depth
  1806. and git_require((1, 8, 3))):
  1807. # Shallow checkout of a specific commit, fetch from that commit and not
  1808. # the heads only as the commit might be deeper in the history.
  1809. spec.append(branch)
  1810. else:
  1811. if is_sha1:
  1812. branch = self.upstream
  1813. if branch is not None and branch.strip():
  1814. if not branch.startswith('refs/'):
  1815. branch = R_HEADS + branch
  1816. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1817. # If mirroring repo and we cannot deduce the tag or branch to fetch, fetch
  1818. # whole repo.
  1819. if self.manifest.IsMirror and not spec:
  1820. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1821. # If using depth then we should not get all the tags since they may
  1822. # be outside of the depth.
  1823. if not tags or depth:
  1824. cmd.append('--no-tags')
  1825. else:
  1826. cmd.append('--tags')
  1827. spec.append(str((u'+refs/tags/*:') + remote.ToLocal('refs/tags/*')))
  1828. cmd.extend(spec)
  1829. # At least one retry minimum due to git remote prune.
  1830. retry_fetches = max(retry_fetches, 2)
  1831. retry_cur_sleep = retry_sleep_initial_sec
  1832. ok = prune_tried = False
  1833. for try_n in range(retry_fetches):
  1834. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy,
  1835. merge_output=True, capture_stdout=quiet)
  1836. ret = gitcmd.Wait()
  1837. if ret == 0:
  1838. ok = True
  1839. break
  1840. # Retry later due to HTTP 429 Too Many Requests.
  1841. elif ('error:' in gitcmd.stderr and
  1842. 'HTTP 429' in gitcmd.stderr):
  1843. if not quiet:
  1844. print('429 received, sleeping: %s sec' % retry_cur_sleep,
  1845. file=sys.stderr)
  1846. time.sleep(retry_cur_sleep)
  1847. retry_cur_sleep = min(retry_exp_factor * retry_cur_sleep,
  1848. MAXIMUM_RETRY_SLEEP_SEC)
  1849. retry_cur_sleep *= (1 - random.uniform(-RETRY_JITTER_PERCENT,
  1850. RETRY_JITTER_PERCENT))
  1851. continue
  1852. # If this is not last attempt, try 'git remote prune'.
  1853. elif (try_n < retry_fetches - 1 and
  1854. 'error:' in gitcmd.stderr and
  1855. 'git remote prune' in gitcmd.stderr and
  1856. not prune_tried):
  1857. prune_tried = True
  1858. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1859. ssh_proxy=ssh_proxy)
  1860. ret = prunecmd.Wait()
  1861. if ret:
  1862. break
  1863. continue
  1864. elif current_branch_only and is_sha1 and ret == 128:
  1865. # Exit code 128 means "couldn't find the ref you asked for"; if we're
  1866. # in sha1 mode, we just tried sync'ing from the upstream field; it
  1867. # doesn't exist, thus abort the optimization attempt and do a full sync.
  1868. break
  1869. elif ret < 0:
  1870. # Git died with a signal, exit immediately
  1871. break
  1872. if not verbose:
  1873. print('%s:\n%s' % (self.name, gitcmd.stdout), file=sys.stderr)
  1874. time.sleep(random.randint(30, 45))
  1875. if initial:
  1876. if alt_dir:
  1877. if old_packed != '':
  1878. _lwrite(packed_refs, old_packed)
  1879. else:
  1880. platform_utils.remove(packed_refs)
  1881. self.bare_git.pack_refs('--all', '--prune')
  1882. if is_sha1 and current_branch_only:
  1883. # We just synced the upstream given branch; verify we
  1884. # got what we wanted, else trigger a second run of all
  1885. # refs.
  1886. if not self._CheckForImmutableRevision():
  1887. # Sync the current branch only with depth set to None.
  1888. # We always pass depth=None down to avoid infinite recursion.
  1889. return self._RemoteFetch(
  1890. name=name, quiet=quiet, verbose=verbose,
  1891. current_branch_only=current_branch_only and depth,
  1892. initial=False, alt_dir=alt_dir,
  1893. depth=None, clone_filter=clone_filter)
  1894. return ok
  1895. def _ApplyCloneBundle(self, initial=False, quiet=False, verbose=False):
  1896. if initial and \
  1897. (self.manifest.manifestProject.config.GetString('repo.depth') or
  1898. self.clone_depth):
  1899. return False
  1900. remote = self.GetRemote(self.remote.name)
  1901. bundle_url = remote.url + '/clone.bundle'
  1902. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1903. if GetSchemeFromUrl(bundle_url) not in ('http', 'https',
  1904. 'persistent-http',
  1905. 'persistent-https'):
  1906. return False
  1907. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1908. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1909. exist_dst = os.path.exists(bundle_dst)
  1910. exist_tmp = os.path.exists(bundle_tmp)
  1911. if not initial and not exist_dst and not exist_tmp:
  1912. return False
  1913. if not exist_dst:
  1914. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet,
  1915. verbose)
  1916. if not exist_dst:
  1917. return False
  1918. cmd = ['fetch']
  1919. if not verbose:
  1920. cmd.append('--quiet')
  1921. if not quiet and sys.stdout.isatty():
  1922. cmd.append('--progress')
  1923. if not self.worktree:
  1924. cmd.append('--update-head-ok')
  1925. cmd.append(bundle_dst)
  1926. for f in remote.fetch:
  1927. cmd.append(str(f))
  1928. cmd.append('+refs/tags/*:refs/tags/*')
  1929. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1930. if os.path.exists(bundle_dst):
  1931. platform_utils.remove(bundle_dst)
  1932. if os.path.exists(bundle_tmp):
  1933. platform_utils.remove(bundle_tmp)
  1934. return ok
  1935. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet, verbose):
  1936. if os.path.exists(dstPath):
  1937. platform_utils.remove(dstPath)
  1938. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1939. if quiet:
  1940. cmd += ['--silent', '--show-error']
  1941. if os.path.exists(tmpPath):
  1942. size = os.stat(tmpPath).st_size
  1943. if size >= 1024:
  1944. cmd += ['--continue-at', '%d' % (size,)]
  1945. else:
  1946. platform_utils.remove(tmpPath)
  1947. with GetUrlCookieFile(srcUrl, quiet) as (cookiefile, proxy):
  1948. if cookiefile:
  1949. cmd += ['--cookie', cookiefile]
  1950. if proxy:
  1951. cmd += ['--proxy', proxy]
  1952. elif 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1953. cmd += ['--proxy', os.environ['http_proxy']]
  1954. if srcUrl.startswith('persistent-https'):
  1955. srcUrl = 'http' + srcUrl[len('persistent-https'):]
  1956. elif srcUrl.startswith('persistent-http'):
  1957. srcUrl = 'http' + srcUrl[len('persistent-http'):]
  1958. cmd += [srcUrl]
  1959. if IsTrace():
  1960. Trace('%s', ' '.join(cmd))
  1961. if verbose:
  1962. print('%s: Downloading bundle: %s' % (self.name, srcUrl))
  1963. stdout = None if verbose else subprocess.PIPE
  1964. stderr = None if verbose else subprocess.STDOUT
  1965. try:
  1966. proc = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)
  1967. except OSError:
  1968. return False
  1969. (output, _) = proc.communicate()
  1970. curlret = proc.returncode
  1971. if curlret == 22:
  1972. # From curl man page:
  1973. # 22: HTTP page not retrieved. The requested url was not found or
  1974. # returned another error with the HTTP error code being 400 or above.
  1975. # This return code only appears if -f, --fail is used.
  1976. if verbose:
  1977. print('%s: Unable to retrieve clone.bundle; ignoring.' % self.name)
  1978. if output:
  1979. print('Curl output:\n%s' % output)
  1980. return False
  1981. elif curlret and not verbose and output:
  1982. print('%s' % output, file=sys.stderr)
  1983. if os.path.exists(tmpPath):
  1984. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  1985. platform_utils.rename(tmpPath, dstPath)
  1986. return True
  1987. else:
  1988. platform_utils.remove(tmpPath)
  1989. return False
  1990. else:
  1991. return False
  1992. def _IsValidBundle(self, path, quiet):
  1993. try:
  1994. with open(path, 'rb') as f:
  1995. if f.read(16) == b'# v2 git bundle\n':
  1996. return True
  1997. else:
  1998. if not quiet:
  1999. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  2000. return False
  2001. except OSError:
  2002. return False
  2003. def _Checkout(self, rev, quiet=False):
  2004. cmd = ['checkout']
  2005. if quiet:
  2006. cmd.append('-q')
  2007. cmd.append(rev)
  2008. cmd.append('--')
  2009. if GitCommand(self, cmd).Wait() != 0:
  2010. if self._allrefs:
  2011. raise GitError('%s checkout %s ' % (self.name, rev))
  2012. def _CherryPick(self, rev, ffonly=False, record_origin=False):
  2013. cmd = ['cherry-pick']
  2014. if ffonly:
  2015. cmd.append('--ff')
  2016. if record_origin:
  2017. cmd.append('-x')
  2018. cmd.append(rev)
  2019. cmd.append('--')
  2020. if GitCommand(self, cmd).Wait() != 0:
  2021. if self._allrefs:
  2022. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  2023. def _LsRemote(self, refs):
  2024. cmd = ['ls-remote', self.remote.name, refs]
  2025. p = GitCommand(self, cmd, capture_stdout=True)
  2026. if p.Wait() == 0:
  2027. return p.stdout
  2028. return None
  2029. def _Revert(self, rev):
  2030. cmd = ['revert']
  2031. cmd.append('--no-edit')
  2032. cmd.append(rev)
  2033. cmd.append('--')
  2034. if GitCommand(self, cmd).Wait() != 0:
  2035. if self._allrefs:
  2036. raise GitError('%s revert %s ' % (self.name, rev))
  2037. def _ResetHard(self, rev, quiet=True):
  2038. cmd = ['reset', '--hard']
  2039. if quiet:
  2040. cmd.append('-q')
  2041. cmd.append(rev)
  2042. if GitCommand(self, cmd).Wait() != 0:
  2043. raise GitError('%s reset --hard %s ' % (self.name, rev))
  2044. def _SyncSubmodules(self, quiet=True):
  2045. cmd = ['submodule', 'update', '--init', '--recursive']
  2046. if quiet:
  2047. cmd.append('-q')
  2048. if GitCommand(self, cmd).Wait() != 0:
  2049. raise GitError('%s submodule update --init --recursive %s ' % self.name)
  2050. def _Rebase(self, upstream, onto=None):
  2051. cmd = ['rebase']
  2052. if onto is not None:
  2053. cmd.extend(['--onto', onto])
  2054. cmd.append(upstream)
  2055. if GitCommand(self, cmd).Wait() != 0:
  2056. raise GitError('%s rebase %s ' % (self.name, upstream))
  2057. def _FastForward(self, head, ffonly=False):
  2058. cmd = ['merge', '--no-stat', head]
  2059. if ffonly:
  2060. cmd.append("--ff-only")
  2061. if GitCommand(self, cmd).Wait() != 0:
  2062. raise GitError('%s merge %s ' % (self.name, head))
  2063. def _InitGitDir(self, mirror_git=None, force_sync=False, quiet=False):
  2064. init_git_dir = not os.path.exists(self.gitdir)
  2065. init_obj_dir = not os.path.exists(self.objdir)
  2066. try:
  2067. # Initialize the bare repository, which contains all of the objects.
  2068. if init_obj_dir:
  2069. os.makedirs(self.objdir)
  2070. self.bare_objdir.init()
  2071. if self.use_git_worktrees:
  2072. # Set up the m/ space to point to the worktree-specific ref space.
  2073. # We'll update the worktree-specific ref space on each checkout.
  2074. if self.manifest.branch:
  2075. self.bare_git.symbolic_ref(
  2076. '-m', 'redirecting to worktree scope',
  2077. R_M + self.manifest.branch,
  2078. R_WORKTREE_M + self.manifest.branch)
  2079. # Enable per-worktree config file support if possible. This is more a
  2080. # nice-to-have feature for users rather than a hard requirement.
  2081. if git_require((2, 20, 0)):
  2082. self.EnableRepositoryExtension('worktreeConfig')
  2083. # If we have a separate directory to hold refs, initialize it as well.
  2084. if self.objdir != self.gitdir:
  2085. if init_git_dir:
  2086. os.makedirs(self.gitdir)
  2087. if init_obj_dir or init_git_dir:
  2088. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  2089. copy_all=True)
  2090. try:
  2091. self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
  2092. except GitError as e:
  2093. if force_sync:
  2094. print("Retrying clone after deleting %s" %
  2095. self.gitdir, file=sys.stderr)
  2096. try:
  2097. platform_utils.rmtree(platform_utils.realpath(self.gitdir))
  2098. if self.worktree and os.path.exists(platform_utils.realpath
  2099. (self.worktree)):
  2100. platform_utils.rmtree(platform_utils.realpath(self.worktree))
  2101. return self._InitGitDir(mirror_git=mirror_git, force_sync=False,
  2102. quiet=quiet)
  2103. except Exception:
  2104. raise e
  2105. raise e
  2106. if init_git_dir:
  2107. mp = self.manifest.manifestProject
  2108. ref_dir = mp.config.GetString('repo.reference') or ''
  2109. if ref_dir or mirror_git:
  2110. if not mirror_git:
  2111. mirror_git = os.path.join(ref_dir, self.name + '.git')
  2112. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  2113. self.relpath + '.git')
  2114. worktrees_git = os.path.join(ref_dir, '.repo', 'worktrees',
  2115. self.name + '.git')
  2116. if os.path.exists(mirror_git):
  2117. ref_dir = mirror_git
  2118. elif os.path.exists(repo_git):
  2119. ref_dir = repo_git
  2120. elif os.path.exists(worktrees_git):
  2121. ref_dir = worktrees_git
  2122. else:
  2123. ref_dir = None
  2124. if ref_dir:
  2125. if not os.path.isabs(ref_dir):
  2126. # The alternate directory is relative to the object database.
  2127. ref_dir = os.path.relpath(ref_dir,
  2128. os.path.join(self.objdir, 'objects'))
  2129. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  2130. os.path.join(ref_dir, 'objects') + '\n')
  2131. self._UpdateHooks(quiet=quiet)
  2132. m = self.manifest.manifestProject.config
  2133. for key in ['user.name', 'user.email']:
  2134. if m.Has(key, include_defaults=False):
  2135. self.config.SetString(key, m.GetString(key))
  2136. self.config.SetString('filter.lfs.smudge', 'git-lfs smudge --skip -- %f')
  2137. self.config.SetString('filter.lfs.process', 'git-lfs filter-process --skip')
  2138. if self.manifest.IsMirror:
  2139. self.config.SetString('core.bare', 'true')
  2140. else:
  2141. self.config.SetString('core.bare', None)
  2142. except Exception:
  2143. if init_obj_dir and os.path.exists(self.objdir):
  2144. platform_utils.rmtree(self.objdir)
  2145. if init_git_dir and os.path.exists(self.gitdir):
  2146. platform_utils.rmtree(self.gitdir)
  2147. raise
  2148. def _UpdateHooks(self, quiet=False):
  2149. if os.path.exists(self.gitdir):
  2150. self._InitHooks(quiet=quiet)
  2151. def _InitHooks(self, quiet=False):
  2152. hooks = platform_utils.realpath(self._gitdir_path('hooks'))
  2153. if not os.path.exists(hooks):
  2154. os.makedirs(hooks)
  2155. for stock_hook in _ProjectHooks():
  2156. name = os.path.basename(stock_hook)
  2157. if name in ('commit-msg',) and not self.remote.review \
  2158. and self is not self.manifest.manifestProject:
  2159. # Don't install a Gerrit Code Review hook if this
  2160. # project does not appear to use it for reviews.
  2161. #
  2162. # Since the manifest project is one of those, but also
  2163. # managed through gerrit, it's excluded
  2164. continue
  2165. dst = os.path.join(hooks, name)
  2166. if platform_utils.islink(dst):
  2167. continue
  2168. if os.path.exists(dst):
  2169. # If the files are the same, we'll leave it alone. We create symlinks
  2170. # below by default but fallback to hardlinks if the OS blocks them.
  2171. # So if we're here, it's probably because we made a hardlink below.
  2172. if not filecmp.cmp(stock_hook, dst, shallow=False):
  2173. if not quiet:
  2174. _warn("%s: Not replacing locally modified %s hook",
  2175. self.relpath, name)
  2176. continue
  2177. try:
  2178. platform_utils.symlink(
  2179. os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  2180. except OSError as e:
  2181. if e.errno == errno.EPERM:
  2182. try:
  2183. os.link(stock_hook, dst)
  2184. except OSError:
  2185. raise GitError(self._get_symlink_error_message())
  2186. else:
  2187. raise
  2188. def _InitRemote(self):
  2189. if self.remote.url:
  2190. remote = self.GetRemote(self.remote.name)
  2191. remote.url = self.remote.url
  2192. remote.pushUrl = self.remote.pushUrl
  2193. remote.review = self.remote.review
  2194. remote.projectname = self.name
  2195. if self.worktree:
  2196. remote.ResetFetch(mirror=False)
  2197. else:
  2198. remote.ResetFetch(mirror=True)
  2199. remote.Save()
  2200. def _InitMRef(self):
  2201. if self.manifest.branch:
  2202. if self.use_git_worktrees:
  2203. # We can't update this ref with git worktrees until it exists.
  2204. # We'll wait until the initial checkout to set it.
  2205. if not os.path.exists(self.worktree):
  2206. return
  2207. base = R_WORKTREE_M
  2208. active_git = self.work_git
  2209. else:
  2210. base = R_M
  2211. active_git = self.bare_git
  2212. self._InitAnyMRef(base + self.manifest.branch, active_git)
  2213. def _InitMirrorHead(self):
  2214. self._InitAnyMRef(HEAD, self.bare_git)
  2215. def _InitAnyMRef(self, ref, active_git):
  2216. cur = self.bare_ref.symref(ref)
  2217. if self.revisionId:
  2218. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  2219. msg = 'manifest set to %s' % self.revisionId
  2220. dst = self.revisionId + '^0'
  2221. active_git.UpdateRef(ref, dst, message=msg, detach=True)
  2222. else:
  2223. remote = self.GetRemote(self.remote.name)
  2224. dst = remote.ToLocal(self.revisionExpr)
  2225. if cur != dst:
  2226. msg = 'manifest set to %s' % self.revisionExpr
  2227. active_git.symbolic_ref('-m', msg, ref, dst)
  2228. def _CheckDirReference(self, srcdir, destdir, share_refs):
  2229. # Git worktrees don't use symlinks to share at all.
  2230. if self.use_git_worktrees:
  2231. return
  2232. symlink_files = self.shareable_files[:]
  2233. symlink_dirs = self.shareable_dirs[:]
  2234. if share_refs:
  2235. symlink_files += self.working_tree_files
  2236. symlink_dirs += self.working_tree_dirs
  2237. to_symlink = symlink_files + symlink_dirs
  2238. for name in set(to_symlink):
  2239. # Try to self-heal a bit in simple cases.
  2240. dst_path = os.path.join(destdir, name)
  2241. src_path = os.path.join(srcdir, name)
  2242. if name in self.working_tree_dirs:
  2243. # If the dir is missing under .repo/projects/, create it.
  2244. if not os.path.exists(src_path):
  2245. os.makedirs(src_path)
  2246. elif name in self.working_tree_files:
  2247. # If it's a file under the checkout .git/ and the .repo/projects/ has
  2248. # nothing, move the file under the .repo/projects/ tree.
  2249. if not os.path.exists(src_path) and os.path.isfile(dst_path):
  2250. platform_utils.rename(dst_path, src_path)
  2251. # If the path exists under the .repo/projects/ and there's no symlink
  2252. # under the checkout .git/, recreate the symlink.
  2253. if name in self.working_tree_dirs or name in self.working_tree_files:
  2254. if os.path.exists(src_path) and not os.path.exists(dst_path):
  2255. platform_utils.symlink(
  2256. os.path.relpath(src_path, os.path.dirname(dst_path)), dst_path)
  2257. dst = platform_utils.realpath(dst_path)
  2258. if os.path.lexists(dst):
  2259. src = platform_utils.realpath(src_path)
  2260. # Fail if the links are pointing to the wrong place
  2261. if src != dst:
  2262. _error('%s is different in %s vs %s', name, destdir, srcdir)
  2263. raise GitError('--force-sync not enabled; cannot overwrite a local '
  2264. 'work tree. If you\'re comfortable with the '
  2265. 'possibility of losing the work tree\'s git metadata,'
  2266. ' use `repo sync --force-sync {0}` to '
  2267. 'proceed.'.format(self.relpath))
  2268. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  2269. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  2270. Args:
  2271. gitdir: The bare git repository. Must already be initialized.
  2272. dotgit: The repository you would like to initialize.
  2273. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  2274. Only one work tree can store refs under a given |gitdir|.
  2275. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  2276. This saves you the effort of initializing |dotgit| yourself.
  2277. """
  2278. symlink_files = self.shareable_files[:]
  2279. symlink_dirs = self.shareable_dirs[:]
  2280. if share_refs:
  2281. symlink_files += self.working_tree_files
  2282. symlink_dirs += self.working_tree_dirs
  2283. to_symlink = symlink_files + symlink_dirs
  2284. to_copy = []
  2285. if copy_all:
  2286. to_copy = platform_utils.listdir(gitdir)
  2287. dotgit = platform_utils.realpath(dotgit)
  2288. for name in set(to_copy).union(to_symlink):
  2289. try:
  2290. src = platform_utils.realpath(os.path.join(gitdir, name))
  2291. dst = os.path.join(dotgit, name)
  2292. if os.path.lexists(dst):
  2293. continue
  2294. # If the source dir doesn't exist, create an empty dir.
  2295. if name in symlink_dirs and not os.path.lexists(src):
  2296. os.makedirs(src)
  2297. if name in to_symlink:
  2298. platform_utils.symlink(
  2299. os.path.relpath(src, os.path.dirname(dst)), dst)
  2300. elif copy_all and not platform_utils.islink(dst):
  2301. if platform_utils.isdir(src):
  2302. shutil.copytree(src, dst)
  2303. elif os.path.isfile(src):
  2304. shutil.copy(src, dst)
  2305. # If the source file doesn't exist, ensure the destination
  2306. # file doesn't either.
  2307. if name in symlink_files and not os.path.lexists(src):
  2308. try:
  2309. platform_utils.remove(dst)
  2310. except OSError:
  2311. pass
  2312. except OSError as e:
  2313. if e.errno == errno.EPERM:
  2314. raise DownloadError(self._get_symlink_error_message())
  2315. else:
  2316. raise
  2317. def _InitGitWorktree(self):
  2318. """Init the project using git worktrees."""
  2319. self.bare_git.worktree('prune')
  2320. self.bare_git.worktree('add', '-ff', '--checkout', '--detach', '--lock',
  2321. self.worktree, self.GetRevisionId())
  2322. # Rewrite the internal state files to use relative paths between the
  2323. # checkouts & worktrees.
  2324. dotgit = os.path.join(self.worktree, '.git')
  2325. with open(dotgit, 'r') as fp:
  2326. # Figure out the checkout->worktree path.
  2327. setting = fp.read()
  2328. assert setting.startswith('gitdir:')
  2329. git_worktree_path = setting.split(':', 1)[1].strip()
  2330. # Some platforms (e.g. Windows) won't let us update dotgit in situ because
  2331. # of file permissions. Delete it and recreate it from scratch to avoid.
  2332. platform_utils.remove(dotgit)
  2333. # Use relative path from checkout->worktree.
  2334. with open(dotgit, 'w') as fp:
  2335. print('gitdir:', os.path.relpath(git_worktree_path, self.worktree),
  2336. file=fp)
  2337. # Use relative path from worktree->checkout.
  2338. with open(os.path.join(git_worktree_path, 'gitdir'), 'w') as fp:
  2339. print(os.path.relpath(dotgit, git_worktree_path), file=fp)
  2340. self._InitMRef()
  2341. def _InitWorkTree(self, force_sync=False, submodules=False):
  2342. realdotgit = os.path.join(self.worktree, '.git')
  2343. tmpdotgit = realdotgit + '.tmp'
  2344. init_dotgit = not os.path.exists(realdotgit)
  2345. if init_dotgit:
  2346. if self.use_git_worktrees:
  2347. self._InitGitWorktree()
  2348. self._CopyAndLinkFiles()
  2349. return
  2350. dotgit = tmpdotgit
  2351. platform_utils.rmtree(tmpdotgit, ignore_errors=True)
  2352. os.makedirs(tmpdotgit)
  2353. self._ReferenceGitDir(self.gitdir, tmpdotgit, share_refs=True,
  2354. copy_all=False)
  2355. else:
  2356. dotgit = realdotgit
  2357. try:
  2358. self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
  2359. except GitError as e:
  2360. if force_sync and not init_dotgit:
  2361. try:
  2362. platform_utils.rmtree(dotgit)
  2363. return self._InitWorkTree(force_sync=False, submodules=submodules)
  2364. except Exception:
  2365. raise e
  2366. raise e
  2367. if init_dotgit:
  2368. _lwrite(os.path.join(tmpdotgit, HEAD), '%s\n' % self.GetRevisionId())
  2369. # Now that the .git dir is fully set up, move it to its final home.
  2370. platform_utils.rename(tmpdotgit, realdotgit)
  2371. # Finish checking out the worktree.
  2372. cmd = ['read-tree', '--reset', '-u']
  2373. cmd.append('-v')
  2374. cmd.append(HEAD)
  2375. if GitCommand(self, cmd).Wait() != 0:
  2376. raise GitError('Cannot initialize work tree for ' + self.name)
  2377. if submodules:
  2378. self._SyncSubmodules(quiet=True)
  2379. self._CopyAndLinkFiles()
  2380. def _get_symlink_error_message(self):
  2381. if platform_utils.isWindows():
  2382. return ('Unable to create symbolic link. Please re-run the command as '
  2383. 'Administrator, or see '
  2384. 'https://github.com/git-for-windows/git/wiki/Symbolic-Links '
  2385. 'for other options.')
  2386. return 'filesystem must support symlinks'
  2387. def _gitdir_path(self, path):
  2388. return platform_utils.realpath(os.path.join(self.gitdir, path))
  2389. def _revlist(self, *args, **kw):
  2390. a = []
  2391. a.extend(args)
  2392. a.append('--')
  2393. return self.work_git.rev_list(*a, **kw)
  2394. @property
  2395. def _allrefs(self):
  2396. return self.bare_ref.all
  2397. def _getLogs(self, rev1, rev2, oneline=False, color=True, pretty_format=None):
  2398. """Get logs between two revisions of this project."""
  2399. comp = '..'
  2400. if rev1:
  2401. revs = [rev1]
  2402. if rev2:
  2403. revs.extend([comp, rev2])
  2404. cmd = ['log', ''.join(revs)]
  2405. out = DiffColoring(self.config)
  2406. if out.is_on and color:
  2407. cmd.append('--color')
  2408. if pretty_format is not None:
  2409. cmd.append('--pretty=format:%s' % pretty_format)
  2410. if oneline:
  2411. cmd.append('--oneline')
  2412. try:
  2413. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2414. if log.Wait() == 0:
  2415. return log.stdout
  2416. except GitError:
  2417. # worktree may not exist if groups changed for example. In that case,
  2418. # try in gitdir instead.
  2419. if not os.path.exists(self.worktree):
  2420. return self.bare_git.log(*cmd[1:])
  2421. else:
  2422. raise
  2423. return None
  2424. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True,
  2425. pretty_format=None):
  2426. """Get the list of logs from this revision to given revisionId"""
  2427. logs = {}
  2428. selfId = self.GetRevisionId(self._allrefs)
  2429. toId = toProject.GetRevisionId(toProject._allrefs)
  2430. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color,
  2431. pretty_format=pretty_format)
  2432. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color,
  2433. pretty_format=pretty_format)
  2434. return logs
  2435. class _GitGetByExec(object):
  2436. def __init__(self, project, bare, gitdir):
  2437. self._project = project
  2438. self._bare = bare
  2439. self._gitdir = gitdir
  2440. # __getstate__ and __setstate__ are required for pickling because __getattr__ exists.
  2441. def __getstate__(self):
  2442. return (self._project, self._bare, self._gitdir)
  2443. def __setstate__(self, state):
  2444. self._project, self._bare, self._gitdir = state
  2445. def LsOthers(self):
  2446. p = GitCommand(self._project,
  2447. ['ls-files',
  2448. '-z',
  2449. '--others',
  2450. '--exclude-standard'],
  2451. bare=False,
  2452. gitdir=self._gitdir,
  2453. capture_stdout=True,
  2454. capture_stderr=True)
  2455. if p.Wait() == 0:
  2456. out = p.stdout
  2457. if out:
  2458. # Backslash is not anomalous
  2459. return out[:-1].split('\0')
  2460. return []
  2461. def DiffZ(self, name, *args):
  2462. cmd = [name]
  2463. cmd.append('-z')
  2464. cmd.append('--ignore-submodules')
  2465. cmd.extend(args)
  2466. p = GitCommand(self._project,
  2467. cmd,
  2468. gitdir=self._gitdir,
  2469. bare=False,
  2470. capture_stdout=True,
  2471. capture_stderr=True)
  2472. try:
  2473. out = p.process.stdout.read()
  2474. if not hasattr(out, 'encode'):
  2475. out = out.decode()
  2476. r = {}
  2477. if out:
  2478. out = iter(out[:-1].split('\0'))
  2479. while out:
  2480. try:
  2481. info = next(out)
  2482. path = next(out)
  2483. except StopIteration:
  2484. break
  2485. class _Info(object):
  2486. def __init__(self, path, omode, nmode, oid, nid, state):
  2487. self.path = path
  2488. self.src_path = None
  2489. self.old_mode = omode
  2490. self.new_mode = nmode
  2491. self.old_id = oid
  2492. self.new_id = nid
  2493. if len(state) == 1:
  2494. self.status = state
  2495. self.level = None
  2496. else:
  2497. self.status = state[:1]
  2498. self.level = state[1:]
  2499. while self.level.startswith('0'):
  2500. self.level = self.level[1:]
  2501. info = info[1:].split(' ')
  2502. info = _Info(path, *info)
  2503. if info.status in ('R', 'C'):
  2504. info.src_path = info.path
  2505. info.path = next(out)
  2506. r[info.path] = info
  2507. return r
  2508. finally:
  2509. p.Wait()
  2510. def GetDotgitPath(self, subpath=None):
  2511. """Return the full path to the .git dir.
  2512. As a convenience, append |subpath| if provided.
  2513. """
  2514. if self._bare:
  2515. dotgit = self._gitdir
  2516. else:
  2517. dotgit = os.path.join(self._project.worktree, '.git')
  2518. if os.path.isfile(dotgit):
  2519. # Git worktrees use a "gitdir:" syntax to point to the scratch space.
  2520. with open(dotgit) as fp:
  2521. setting = fp.read()
  2522. assert setting.startswith('gitdir:')
  2523. gitdir = setting.split(':', 1)[1].strip()
  2524. dotgit = os.path.normpath(os.path.join(self._project.worktree, gitdir))
  2525. return dotgit if subpath is None else os.path.join(dotgit, subpath)
  2526. def GetHead(self):
  2527. """Return the ref that HEAD points to."""
  2528. path = self.GetDotgitPath(subpath=HEAD)
  2529. try:
  2530. with open(path) as fd:
  2531. line = fd.readline()
  2532. except IOError as e:
  2533. raise NoManifestException(path, str(e))
  2534. try:
  2535. line = line.decode()
  2536. except AttributeError:
  2537. pass
  2538. if line.startswith('ref: '):
  2539. return line[5:-1]
  2540. return line[:-1]
  2541. def SetHead(self, ref, message=None):
  2542. cmdv = []
  2543. if message is not None:
  2544. cmdv.extend(['-m', message])
  2545. cmdv.append(HEAD)
  2546. cmdv.append(ref)
  2547. self.symbolic_ref(*cmdv)
  2548. def DetachHead(self, new, message=None):
  2549. cmdv = ['--no-deref']
  2550. if message is not None:
  2551. cmdv.extend(['-m', message])
  2552. cmdv.append(HEAD)
  2553. cmdv.append(new)
  2554. self.update_ref(*cmdv)
  2555. def UpdateRef(self, name, new, old=None,
  2556. message=None,
  2557. detach=False):
  2558. cmdv = []
  2559. if message is not None:
  2560. cmdv.extend(['-m', message])
  2561. if detach:
  2562. cmdv.append('--no-deref')
  2563. cmdv.append(name)
  2564. cmdv.append(new)
  2565. if old is not None:
  2566. cmdv.append(old)
  2567. self.update_ref(*cmdv)
  2568. def DeleteRef(self, name, old=None):
  2569. if not old:
  2570. old = self.rev_parse(name)
  2571. self.update_ref('-d', name, old)
  2572. self._project.bare_ref.deleted(name)
  2573. def rev_list(self, *args, **kw):
  2574. if 'format' in kw:
  2575. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2576. else:
  2577. cmdv = ['rev-list']
  2578. cmdv.extend(args)
  2579. p = GitCommand(self._project,
  2580. cmdv,
  2581. bare=self._bare,
  2582. gitdir=self._gitdir,
  2583. capture_stdout=True,
  2584. capture_stderr=True)
  2585. if p.Wait() != 0:
  2586. raise GitError('%s rev-list %s: %s' %
  2587. (self._project.name, str(args), p.stderr))
  2588. return p.stdout.splitlines()
  2589. def __getattr__(self, name):
  2590. """Allow arbitrary git commands using pythonic syntax.
  2591. This allows you to do things like:
  2592. git_obj.rev_parse('HEAD')
  2593. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2594. run. We'll replace the '_' with a '-' and try to run a git command.
  2595. Any other positional arguments will be passed to the git command, and the
  2596. following keyword arguments are supported:
  2597. config: An optional dict of git config options to be passed with '-c'.
  2598. Args:
  2599. name: The name of the git command to call. Any '_' characters will
  2600. be replaced with '-'.
  2601. Returns:
  2602. A callable object that will try to call git with the named command.
  2603. """
  2604. name = name.replace('_', '-')
  2605. def runner(*args, **kwargs):
  2606. cmdv = []
  2607. config = kwargs.pop('config', None)
  2608. for k in kwargs:
  2609. raise TypeError('%s() got an unexpected keyword argument %r'
  2610. % (name, k))
  2611. if config is not None:
  2612. for k, v in config.items():
  2613. cmdv.append('-c')
  2614. cmdv.append('%s=%s' % (k, v))
  2615. cmdv.append(name)
  2616. cmdv.extend(args)
  2617. p = GitCommand(self._project,
  2618. cmdv,
  2619. bare=self._bare,
  2620. gitdir=self._gitdir,
  2621. capture_stdout=True,
  2622. capture_stderr=True)
  2623. if p.Wait() != 0:
  2624. raise GitError('%s %s: %s' %
  2625. (self._project.name, name, p.stderr))
  2626. r = p.stdout
  2627. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2628. return r[:-1]
  2629. return r
  2630. return runner
  2631. class _PriorSyncFailedError(Exception):
  2632. def __str__(self):
  2633. return 'prior sync failed; rebase still in progress'
  2634. class _DirtyError(Exception):
  2635. def __str__(self):
  2636. return 'contains uncommitted changes'
  2637. class _InfoMessage(object):
  2638. def __init__(self, project, text):
  2639. self.project = project
  2640. self.text = text
  2641. def Print(self, syncbuf):
  2642. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2643. syncbuf.out.nl()
  2644. class _Failure(object):
  2645. def __init__(self, project, why):
  2646. self.project = project
  2647. self.why = why
  2648. def Print(self, syncbuf):
  2649. syncbuf.out.fail('error: %s/: %s',
  2650. self.project.relpath,
  2651. str(self.why))
  2652. syncbuf.out.nl()
  2653. class _Later(object):
  2654. def __init__(self, project, action):
  2655. self.project = project
  2656. self.action = action
  2657. def Run(self, syncbuf):
  2658. out = syncbuf.out
  2659. out.project('project %s/', self.project.relpath)
  2660. out.nl()
  2661. try:
  2662. self.action()
  2663. out.nl()
  2664. return True
  2665. except GitError:
  2666. out.nl()
  2667. return False
  2668. class _SyncColoring(Coloring):
  2669. def __init__(self, config):
  2670. Coloring.__init__(self, config, 'reposync')
  2671. self.project = self.printer('header', attr='bold')
  2672. self.info = self.printer('info')
  2673. self.fail = self.printer('fail', fg='red')
  2674. class SyncBuffer(object):
  2675. def __init__(self, config, detach_head=False):
  2676. self._messages = []
  2677. self._failures = []
  2678. self._later_queue1 = []
  2679. self._later_queue2 = []
  2680. self.out = _SyncColoring(config)
  2681. self.out.redirect(sys.stderr)
  2682. self.detach_head = detach_head
  2683. self.clean = True
  2684. self.recent_clean = True
  2685. def info(self, project, fmt, *args):
  2686. self._messages.append(_InfoMessage(project, fmt % args))
  2687. def fail(self, project, err=None):
  2688. self._failures.append(_Failure(project, err))
  2689. self._MarkUnclean()
  2690. def later1(self, project, what):
  2691. self._later_queue1.append(_Later(project, what))
  2692. def later2(self, project, what):
  2693. self._later_queue2.append(_Later(project, what))
  2694. def Finish(self):
  2695. self._PrintMessages()
  2696. self._RunLater()
  2697. self._PrintMessages()
  2698. return self.clean
  2699. def Recently(self):
  2700. recent_clean = self.recent_clean
  2701. self.recent_clean = True
  2702. return recent_clean
  2703. def _MarkUnclean(self):
  2704. self.clean = False
  2705. self.recent_clean = False
  2706. def _RunLater(self):
  2707. for q in ['_later_queue1', '_later_queue2']:
  2708. if not self._RunQueue(q):
  2709. return
  2710. def _RunQueue(self, queue):
  2711. for m in getattr(self, queue):
  2712. if not m.Run(self):
  2713. self._MarkUnclean()
  2714. return False
  2715. setattr(self, queue, [])
  2716. return True
  2717. def _PrintMessages(self):
  2718. if self._messages or self._failures:
  2719. if os.isatty(2):
  2720. self.out.write(progress.CSI_ERASE_LINE)
  2721. self.out.write('\r')
  2722. for m in self._messages:
  2723. m.Print(self)
  2724. for m in self._failures:
  2725. m.Print(self)
  2726. self._messages = []
  2727. self._failures = []
  2728. class MetaProject(Project):
  2729. """A special project housed under .repo.
  2730. """
  2731. def __init__(self, manifest, name, gitdir, worktree):
  2732. Project.__init__(self,
  2733. manifest=manifest,
  2734. name=name,
  2735. gitdir=gitdir,
  2736. objdir=gitdir,
  2737. worktree=worktree,
  2738. remote=RemoteSpec('origin'),
  2739. relpath='.repo/%s' % name,
  2740. revisionExpr='refs/heads/master',
  2741. revisionId=None,
  2742. groups=None)
  2743. def PreSync(self):
  2744. if self.Exists:
  2745. cb = self.CurrentBranch
  2746. if cb:
  2747. base = self.GetBranch(cb).merge
  2748. if base:
  2749. self.revisionExpr = base
  2750. self.revisionId = None
  2751. def MetaBranchSwitch(self, submodules=False):
  2752. """ Prepare MetaProject for manifest branch switch
  2753. """
  2754. # detach and delete manifest branch, allowing a new
  2755. # branch to take over
  2756. syncbuf = SyncBuffer(self.config, detach_head=True)
  2757. self.Sync_LocalHalf(syncbuf, submodules=submodules)
  2758. syncbuf.Finish()
  2759. return GitCommand(self,
  2760. ['update-ref', '-d', 'refs/heads/default'],
  2761. capture_stdout=True,
  2762. capture_stderr=True).Wait() == 0
  2763. @property
  2764. def LastFetch(self):
  2765. try:
  2766. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2767. return os.path.getmtime(fh)
  2768. except OSError:
  2769. return 0
  2770. @property
  2771. def HasChanges(self):
  2772. """Has the remote received new commits not yet checked out?
  2773. """
  2774. if not self.remote or not self.revisionExpr:
  2775. return False
  2776. all_refs = self.bare_ref.all
  2777. revid = self.GetRevisionId(all_refs)
  2778. head = self.work_git.GetHead()
  2779. if head.startswith(R_HEADS):
  2780. try:
  2781. head = all_refs[head]
  2782. except KeyError:
  2783. head = None
  2784. if revid == head:
  2785. return False
  2786. elif self._revlist(not_rev(HEAD), revid):
  2787. return True
  2788. return False