project.py 104 KB

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