project.py 104 KB

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