project.py 104 KB

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