gclient_scm.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Gclient-specific SCM-specific operations."""
  5. import collections
  6. import contextlib
  7. import errno
  8. import glob
  9. import json
  10. import logging
  11. import os
  12. import platform
  13. import posixpath
  14. import re
  15. import shutil
  16. import sys
  17. import tempfile
  18. import threading
  19. import traceback
  20. import gclient_utils
  21. import gerrit_util
  22. import git_auth
  23. import git_cache
  24. import git_common
  25. import newauth
  26. import scm
  27. import subprocess2
  28. # TODO: Should fix these warnings.
  29. # pylint: disable=line-too-long
  30. class NoUsableRevError(gclient_utils.Error):
  31. """Raised if requested revision isn't found in checkout."""
  32. class DiffFiltererWrapper(object):
  33. """Simple base class which tracks which file is being diffed and
  34. replaces instances of its file name in the original and
  35. working copy lines of the git diff output."""
  36. index_string = None
  37. original_prefix = "--- "
  38. working_prefix = "+++ "
  39. def __init__(self, relpath, print_func):
  40. # Note that we always use '/' as the path separator to be
  41. # consistent with cygwin-style output on Windows
  42. self._relpath = relpath.replace("\\", "/")
  43. self._current_file = None
  44. self._print_func = print_func
  45. def SetCurrentFile(self, current_file):
  46. self._current_file = current_file
  47. @property
  48. def _replacement_file(self):
  49. return posixpath.join(self._relpath, self._current_file)
  50. def _Replace(self, line):
  51. return line.replace(self._current_file, self._replacement_file)
  52. def Filter(self, line):
  53. if (line.startswith(self.index_string)):
  54. self.SetCurrentFile(line[len(self.index_string):])
  55. line = self._Replace(line)
  56. else:
  57. if (line.startswith(self.original_prefix)
  58. or line.startswith(self.working_prefix)):
  59. line = self._Replace(line)
  60. self._print_func(line)
  61. class GitDiffFilterer(DiffFiltererWrapper):
  62. index_string = "diff --git "
  63. def SetCurrentFile(self, current_file):
  64. # Get filename by parsing "a/<filename> b/<filename>"
  65. self._current_file = current_file[:(len(current_file) / 2)][2:]
  66. def _Replace(self, line):
  67. return re.sub("[a|b]/" + self._current_file, self._replacement_file,
  68. line)
  69. # SCMWrapper base class
  70. class SCMWrapper(object):
  71. """Add necessary glue between all the supported SCM.
  72. This is the abstraction layer to bind to different SCM.
  73. """
  74. def __init__(self,
  75. url=None,
  76. root_dir=None,
  77. relpath=None,
  78. out_fh=None,
  79. out_cb=None,
  80. print_outbuf=False):
  81. self.url = url
  82. self._root_dir = root_dir
  83. if self._root_dir:
  84. self._root_dir = self._root_dir.replace('/', os.sep)
  85. self.relpath = relpath
  86. if self.relpath:
  87. self.relpath = self.relpath.replace('/', os.sep)
  88. if self.relpath and self._root_dir:
  89. self.checkout_path = os.path.join(self._root_dir, self.relpath)
  90. if out_fh is None:
  91. out_fh = sys.stdout
  92. self.out_fh = out_fh
  93. self.out_cb = out_cb
  94. self.print_outbuf = print_outbuf
  95. def Print(self, *args, **kwargs):
  96. kwargs.setdefault('file', self.out_fh)
  97. if kwargs.pop('timestamp', True):
  98. self.out_fh.write('[%s] ' % gclient_utils.Elapsed())
  99. print(*args, **kwargs)
  100. def RunCommand(self, command, options, args, file_list=None):
  101. commands = [
  102. 'update', 'updatesingle', 'revert', 'revinfo', 'status', 'diff',
  103. 'pack', 'runhooks'
  104. ]
  105. if not command in commands:
  106. raise gclient_utils.Error('Unknown command %s' % command)
  107. if not command in dir(self):
  108. raise gclient_utils.Error(
  109. 'Command %s not implemented in %s wrapper' %
  110. (command, self.__class__.__name__))
  111. return getattr(self, command)(options, args, file_list)
  112. @staticmethod
  113. def _get_first_remote_url(checkout_path):
  114. log = scm.GIT.YieldConfigRegexp(checkout_path, r'remote.*.url')
  115. return next(log)[1]
  116. def GetCacheMirror(self):
  117. if getattr(self, 'cache_dir', None):
  118. url, _ = gclient_utils.SplitUrlRevision(self.url)
  119. return git_cache.Mirror(url)
  120. return None
  121. def GetActualRemoteURL(self, options):
  122. """Attempt to determine the remote URL for this SCMWrapper."""
  123. # Git
  124. if os.path.exists(os.path.join(self.checkout_path, '.git')):
  125. actual_remote_url = self._get_first_remote_url(self.checkout_path)
  126. mirror = self.GetCacheMirror()
  127. # If the cache is used, obtain the actual remote URL from there.
  128. if (mirror and mirror.exists() and mirror.mirror_path.replace(
  129. '\\', '/') == actual_remote_url.replace('\\', '/')):
  130. actual_remote_url = self._get_first_remote_url(
  131. mirror.mirror_path)
  132. return actual_remote_url
  133. return None
  134. def DoesRemoteURLMatch(self, options):
  135. """Determine whether the remote URL of this checkout is the expected URL."""
  136. if not os.path.exists(self.checkout_path):
  137. # A checkout which doesn't exist can't be broken.
  138. return True
  139. actual_remote_url = self.GetActualRemoteURL(options)
  140. if actual_remote_url:
  141. return (gclient_utils.SplitUrlRevision(actual_remote_url)[0].rstrip(
  142. '/') == gclient_utils.SplitUrlRevision(self.url)[0].rstrip('/'))
  143. # This may occur if the self.checkout_path exists but does not contain a
  144. # valid git checkout.
  145. return False
  146. def _DeleteOrMove(self, force):
  147. """Delete the checkout directory or move it out of the way.
  148. Args:
  149. force: bool; if True, delete the directory. Otherwise, just move it.
  150. """
  151. if force and os.environ.get('CHROME_HEADLESS') == '1':
  152. self.Print('_____ Conflicting directory found in %s. Removing.' %
  153. self.checkout_path)
  154. gclient_utils.AddWarning('Conflicting directory %s deleted.' %
  155. self.checkout_path)
  156. gclient_utils.rmtree(self.checkout_path)
  157. else:
  158. bad_scm_dir = os.path.join(self._root_dir, '_bad_scm',
  159. os.path.dirname(self.relpath))
  160. try:
  161. os.makedirs(bad_scm_dir)
  162. except OSError as e:
  163. if e.errno != errno.EEXIST:
  164. raise
  165. dest_path = tempfile.mkdtemp(prefix=os.path.basename(self.relpath),
  166. dir=bad_scm_dir)
  167. self.Print(
  168. '_____ Conflicting directory found in %s. Moving to %s.' %
  169. (self.checkout_path, dest_path))
  170. gclient_utils.AddWarning('Conflicting directory %s moved to %s.' %
  171. (self.checkout_path, dest_path))
  172. shutil.move(self.checkout_path, dest_path)
  173. class GitWrapper(SCMWrapper):
  174. """Wrapper for Git"""
  175. name = 'git'
  176. remote = 'origin'
  177. @property
  178. def cache_dir(self):
  179. try:
  180. return git_cache.Mirror.GetCachePath()
  181. except RuntimeError:
  182. return None
  183. def __init__(self, url=None, *args, **kwargs):
  184. """Removes 'git+' fake prefix from git URL."""
  185. if url and (url.startswith('git+http://')
  186. or url.startswith('git+https://')):
  187. url = url[4:]
  188. SCMWrapper.__init__(self, url, *args, **kwargs)
  189. filter_kwargs = {'time_throttle': 1, 'out_fh': self.out_fh}
  190. if self.out_cb:
  191. filter_kwargs['predicate'] = self.out_cb
  192. self.filter = gclient_utils.GitFilter(**filter_kwargs)
  193. self._running_under_rosetta = None
  194. self.current_revision = None
  195. def GetCheckoutRoot(self):
  196. return scm.GIT.GetCheckoutRoot(self.checkout_path)
  197. def GetRevisionDate(self, _revision):
  198. """Returns the given revision's date in ISO-8601 format (which contains the
  199. time zone)."""
  200. # TODO(floitsch): get the time-stamp of the given revision and not just
  201. # the time-stamp of the currently checked out revision.
  202. return self._Capture(['log', '-n', '1', '--format=%ai'])
  203. def _GetDiffFilenames(self, base):
  204. """Returns the names of files modified since base."""
  205. return self._Capture(
  206. # Filter to remove base if it is None.
  207. list(
  208. filter(
  209. bool,
  210. ['-c', 'core.quotePath=false', 'diff', '--name-only', base])
  211. )).split()
  212. def GetSubmoduleStateFromIndex(self):
  213. """Returns a map where keys are submodule names and values are commit
  214. hashes. It reads data from the Git index, so only committed values are
  215. present."""
  216. out = self._Capture(['ls-files', '-s'])
  217. result = {}
  218. for l in out.split('\n'):
  219. if not l.startswith('160000'):
  220. # Not a submodule
  221. continue
  222. (_, commit, _, filepath) = l.split(maxsplit=3)
  223. result[filepath] = commit
  224. return result
  225. def GetSubmoduleDiff(self):
  226. """Returns a map where keys are submodule names and values are tuples of
  227. (old_commit_hash, new_commit_hash). old_commit_hash matches the Git
  228. index, whereas new_commit_hash matches currently checked out commit
  229. hash."""
  230. out = self._Capture([
  231. 'diff',
  232. '--no-prefix',
  233. '--no-ext-diff',
  234. '--no-color',
  235. '--ignore-submodules=dirty',
  236. '--submodule=short',
  237. '-G',
  238. 'Subproject commit',
  239. ])
  240. NO_COMMIT = 40 * '0'
  241. committed_submodule = None
  242. checked_submodule = None
  243. filepath = None
  244. state = 0
  245. diff = {}
  246. # Parsing git diff uses simple state machine. States:
  247. # 0 - start state
  248. # 1 - diff file/line detected, ready to process content
  249. # 2 - gitlink detected, ready to process gitlink past and current
  250. # content.
  251. # 3 - past gitlink content detected. It contains a commit hash that's in
  252. # git index.
  253. # 4 - new gitlink content detected. It contains currently checked
  254. # commit. At this point, we have all information needed, and we can
  255. # reset state to 0.
  256. for l in out.split('\n'):
  257. if l.startswith('diff --git'):
  258. # New file detected, reset state.
  259. state = 1
  260. elif state == 1 and l.startswith('index') and l.endswith('160000'):
  261. # We detected gitlink
  262. state = 2
  263. elif state == 2 and l.startswith('+++ '):
  264. # This line contains filename
  265. filepath = l[4:]
  266. state = 3
  267. elif state == 3 and l.startswith('-Subproject commit '):
  268. # This line contains what commit hash Git index expects
  269. # (ls-files).
  270. committed_submodule = l.split(' ')[-1]
  271. state = 4
  272. elif state == 4 and l.startswith('+Subproject commit '):
  273. # This line contains currently checked out commit for this submodule.
  274. checked_submodule = l.split(' ')[-1]
  275. if NO_COMMIT not in (committed_submodule, checked_submodule):
  276. diff[filepath] = (committed_submodule, checked_submodule)
  277. state = 0
  278. return diff
  279. def diff(self, options, _args, _file_list):
  280. _, revision = gclient_utils.SplitUrlRevision(self.url)
  281. if not revision:
  282. revision = 'refs/remotes/%s/main' % self.remote
  283. self._Run(['-c', 'core.quotePath=false', 'diff', revision], options)
  284. def pack(self, _options, _args, _file_list):
  285. """Generates a patch file which can be applied to the root of the
  286. repository.
  287. The patch file is generated from a diff of the merge base of HEAD and
  288. its upstream branch.
  289. """
  290. try:
  291. merge_base = [self._Capture(['merge-base', 'HEAD', self.remote])]
  292. except subprocess2.CalledProcessError:
  293. merge_base = []
  294. gclient_utils.CheckCallAndFilter(['git', 'diff'] + merge_base,
  295. cwd=self.checkout_path,
  296. filter_fn=GitDiffFilterer(
  297. self.relpath,
  298. print_func=self.Print).Filter)
  299. def _Scrub(self, target, options):
  300. """Scrubs out all changes in the local repo, back to the state of target."""
  301. quiet = []
  302. if not options.verbose:
  303. quiet = ['--quiet']
  304. self._Run(['reset', '--hard', target] + quiet, options)
  305. if options.force and options.delete_unversioned_trees:
  306. # where `target` is a commit that contains both upper and lower case
  307. # versions of the same file on a case insensitive filesystem, we are
  308. # actually in a broken state here. The index will have both 'a' and
  309. # 'A', but only one of them will exist on the disk. To progress, we
  310. # delete everything that status thinks is modified.
  311. output = self._Capture(
  312. ['-c', 'core.quotePath=false', 'status', '--porcelain'],
  313. strip=False)
  314. for line in output.splitlines():
  315. # --porcelain (v1) looks like:
  316. # XY filename
  317. try:
  318. filename = line[3:]
  319. self.Print('_____ Deleting residual after reset: %r.' %
  320. filename)
  321. gclient_utils.rm_file_or_tree(
  322. os.path.join(self.checkout_path, filename))
  323. except OSError:
  324. pass
  325. def _FetchAndReset(self, revision, file_list, options):
  326. """Equivalent to git fetch; git reset."""
  327. self._SetFetchConfig(options)
  328. self._Fetch(options, prune=True, quiet=options.verbose)
  329. revision = self._AutoFetchRef(options, revision)
  330. self._Scrub(revision, options)
  331. if file_list is not None:
  332. files = self._Capture(['-c', 'core.quotePath=false',
  333. 'ls-files']).splitlines()
  334. file_list.extend(
  335. [os.path.join(self.checkout_path, f) for f in files])
  336. def _DisableHooks(self):
  337. hook_dir = os.path.join(self.checkout_path, '.git', 'hooks')
  338. if not os.path.isdir(hook_dir):
  339. return
  340. for f in os.listdir(hook_dir):
  341. if not f.endswith('.sample') and not f.endswith('.disabled'):
  342. disabled_hook_path = os.path.join(hook_dir, f + '.disabled')
  343. if os.path.exists(disabled_hook_path):
  344. os.remove(disabled_hook_path)
  345. os.rename(os.path.join(hook_dir, f), disabled_hook_path)
  346. def _maybe_break_locks(self, options):
  347. """This removes all .lock files from this repo's .git directory, if the
  348. user passed the --break_repo_locks command line flag.
  349. In particular, this will cleanup index.lock files, as well as ref lock
  350. files.
  351. """
  352. if options.break_repo_locks:
  353. git_dir = os.path.join(self.checkout_path, '.git')
  354. for path, _, filenames in os.walk(git_dir):
  355. for filename in filenames:
  356. if filename.endswith('.lock'):
  357. to_break = os.path.join(path, filename)
  358. self.Print('breaking lock: %s' % (to_break, ))
  359. try:
  360. os.remove(to_break)
  361. except OSError as ex:
  362. self.Print('FAILED to break lock: %s: %s' %
  363. (to_break, ex))
  364. raise
  365. def _download_topics(self, patch_rev, googlesource_url):
  366. """This method returns new patch_revs to process that have the same topic.
  367. It does the following:
  368. 1. Finds the topic of the Gerrit change specified in the patch_rev.
  369. 2. Find all changes with that topic.
  370. 3. Append patch_rev of the changes with the same topic to the patch_revs
  371. to process.
  372. 4. Returns the new patch_revs to process.
  373. """
  374. patch_revs_to_process = []
  375. # Parse the patch_rev to extract the CL and patchset.
  376. patch_rev_tokens = patch_rev.split('/')
  377. change = patch_rev_tokens[-2]
  378. # Parse the googlesource_url.
  379. tokens = re.search('//(.+).googlesource.com/(.+?)(?:\.git)?$',
  380. googlesource_url)
  381. if not tokens or len(tokens.groups()) != 2:
  382. # googlesource_url is not in the expected format.
  383. return patch_revs_to_process
  384. # parse the gerrit host and repo out of googlesource_url.
  385. host, repo = tokens.groups()[:2]
  386. gerrit_host_url = '%s-review.googlesource.com' % host
  387. # 1. Find the topic of the Gerrit change specified in the patch_rev.
  388. change_object = gerrit_util.GetChange(gerrit_host_url, change)
  389. topic = change_object.get('topic')
  390. if not topic:
  391. # This change has no topic set.
  392. return patch_revs_to_process
  393. # 2. Find all changes with that topic.
  394. changes_with_same_topic = gerrit_util.QueryChanges(
  395. gerrit_host_url, [('topic', topic), ('status', 'open'),
  396. ('repo', repo)],
  397. o_params=['ALL_REVISIONS'])
  398. for c in changes_with_same_topic:
  399. if str(c['_number']) == change:
  400. # This change is already in the patch_rev.
  401. continue
  402. self.Print('Found CL %d with the topic name %s' %
  403. (c['_number'], topic))
  404. # 3. Append patch_rev of the changes with the same topic to the
  405. # patch_revs to process.
  406. curr_rev = c['current_revision']
  407. new_patch_rev = c['revisions'][curr_rev]['ref']
  408. patch_revs_to_process.append(new_patch_rev)
  409. # 4. Return the new patch_revs to process.
  410. return patch_revs_to_process
  411. def _ref_to_remote_ref(self, target_rev):
  412. """Helper function for scm.GIT.RefToRemoteRef with error checking.
  413. Joins the results of scm.GIT.RefToRemoteRef into a string, but raises a
  414. comprehensible error if RefToRemoteRef fails.
  415. Args:
  416. target_rev: a ref somewhere under refs/.
  417. """
  418. tmp_ref = scm.GIT.RefToRemoteRef(target_rev, self.remote)
  419. if not tmp_ref:
  420. raise gclient_utils.Error(
  421. 'Failed to turn target revision %r in repo %r into remote ref' %
  422. (target_rev, self.checkout_path))
  423. return ''.join(tmp_ref)
  424. def apply_patch_ref(self, patch_repo, patch_rev, target_rev, options,
  425. file_list):
  426. # type: (str, str, str, optparse.Values, Collection[str]) -> str
  427. """Apply a patch on top of the revision we're synced at.
  428. The patch ref is given by |patch_repo|@|patch_rev|.
  429. |target_rev| is usually the branch that the |patch_rev| was uploaded against
  430. (e.g. 'refs/heads/main'), but this is not required.
  431. We cherry-pick all commits reachable from |patch_rev| on top of the curret
  432. HEAD, excluding those reachable from |target_rev|
  433. (i.e. git cherry-pick target_rev..patch_rev).
  434. Graphically, it looks like this:
  435. ... -> o -> [possibly already landed commits] -> target_rev
  436. \
  437. -> [possibly not yet landed dependent CLs] -> patch_rev
  438. The final checkout state is then:
  439. ... -> HEAD -> [possibly not yet landed dependent CLs] -> patch_rev
  440. After application, if |options.reset_patch_ref| is specified, we soft reset
  441. the cherry-picked changes, keeping them in git index only.
  442. Args:
  443. patch_repo: The patch origin.
  444. e.g. 'https://foo.googlesource.com/bar'
  445. patch_rev: The revision to patch.
  446. e.g. 'refs/changes/1234/34/1'.
  447. target_rev: The revision to use when finding the merge base.
  448. Typically, the branch that the patch was uploaded against.
  449. e.g. 'refs/heads/main' or 'refs/heads/infra/config'.
  450. options: The options passed to gclient.
  451. file_list: A list where modified files will be appended.
  452. """
  453. # Abort any cherry-picks in progress.
  454. try:
  455. self._Capture(['cherry-pick', '--abort'])
  456. except subprocess2.CalledProcessError:
  457. pass
  458. base_rev = self.revinfo(None, None, None)
  459. if not target_rev:
  460. raise gclient_utils.Error(
  461. 'A target revision for the patch must be given')
  462. if target_rev.startswith(('refs/heads/', 'refs/branch-heads')):
  463. # If |target_rev| is in refs/heads/** or refs/branch-heads/**, try
  464. # first to find the corresponding remote ref for it, since
  465. # |target_rev| might point to a local ref which is not up to date
  466. # with the corresponding remote ref.
  467. remote_ref = self._ref_to_remote_ref(target_rev)
  468. self.Print('Trying the corresponding remote ref for %r: %r\n' %
  469. (target_rev, remote_ref))
  470. if scm.GIT.IsValidRevision(self.checkout_path, remote_ref):
  471. # refs/remotes may need to be updated to cleanly cherry-pick
  472. # changes. See https://crbug.com/1255178.
  473. self._Capture(['fetch', '--no-tags', self.remote, target_rev])
  474. target_rev = remote_ref
  475. elif not scm.GIT.IsValidRevision(self.checkout_path, target_rev):
  476. # Fetch |target_rev| if it's not already available.
  477. url, _ = gclient_utils.SplitUrlRevision(self.url)
  478. mirror = self._GetMirror(url, options, target_rev, target_rev)
  479. if mirror:
  480. rev_type = 'branch' if target_rev.startswith(
  481. 'refs/') else 'hash'
  482. self._UpdateMirrorIfNotContains(mirror, options, rev_type,
  483. target_rev)
  484. self._Fetch(options, refspec=target_rev)
  485. patch_revs_to_process = [patch_rev]
  486. if hasattr(options, 'download_topics') and options.download_topics:
  487. patch_revs_to_process_from_topics = self._download_topics(
  488. patch_rev, self.url)
  489. patch_revs_to_process.extend(patch_revs_to_process_from_topics)
  490. self._Capture(['reset', '--hard'])
  491. for pr in patch_revs_to_process:
  492. self.Print('===Applying patch===')
  493. self.Print('Revision to patch is %r @ %r.' % (patch_repo, pr))
  494. self.Print('Current dir is %r' % self.checkout_path)
  495. self._Capture(['fetch', '--no-tags', patch_repo, pr])
  496. pr = self._Capture(['rev-parse', 'FETCH_HEAD'])
  497. if not options.rebase_patch_ref:
  498. self._Capture(['checkout', pr])
  499. # Adjust base_rev to be the first parent of our checked out
  500. # patch ref; This will allow us to correctly extend `file_list`,
  501. # and will show the correct file-list to programs which do `git
  502. # diff --cached` expecting to see the patch diff.
  503. base_rev = self._Capture(['rev-parse', pr + '~'])
  504. else:
  505. self.Print('Will cherrypick %r .. %r on top of %r.' %
  506. (target_rev, pr, base_rev))
  507. try:
  508. if scm.GIT.IsAncestor(pr,
  509. target_rev,
  510. cwd=self.checkout_path):
  511. if len(patch_revs_to_process) > 1:
  512. # If there are multiple patch_revs_to_process then
  513. # we do not want want to invalidate a previous patch
  514. # so throw an error.
  515. raise gclient_utils.Error(
  516. 'patch_rev %s is an ancestor of target_rev %s. This '
  517. 'situation is unsupported when we need to apply multiple '
  518. 'patch_revs: %s' %
  519. (pr, target_rev, patch_revs_to_process))
  520. # If |patch_rev| is an ancestor of |target_rev|, check
  521. # it out.
  522. self._Capture(['checkout', pr])
  523. else:
  524. # If a change was uploaded on top of another change,
  525. # which has already landed, one of the commits in the
  526. # cherry-pick range will be redundant, since it has
  527. # already landed and its changes incorporated in the
  528. # tree. We pass '--keep-redundant-commits' to ignore
  529. # those changes.
  530. self._Capture([
  531. 'cherry-pick', target_rev + '..' + pr,
  532. '--keep-redundant-commits'
  533. ])
  534. except subprocess2.CalledProcessError as e:
  535. self.Print('Failed to apply patch.')
  536. self.Print('Revision to patch was %r @ %r.' %
  537. (patch_repo, pr))
  538. self.Print('Tried to cherrypick %r .. %r on top of %r.' %
  539. (target_rev, pr, base_rev))
  540. self.Print('Current dir is %r' % self.checkout_path)
  541. self.Print('git returned non-zero exit status %s:\n%s' %
  542. (e.returncode, e.stderr.decode('utf-8')))
  543. # Print the current status so that developers know what
  544. # changes caused the patch failure, since git cherry-pick
  545. # doesn't show that information.
  546. self.Print(self._Capture(['status']))
  547. try:
  548. self._Capture(['cherry-pick', '--abort'])
  549. except subprocess2.CalledProcessError:
  550. pass
  551. raise
  552. if file_list is not None:
  553. file_list.extend(self._GetDiffFilenames(base_rev))
  554. latest_commit = self.revinfo(None, None, None)
  555. if options.reset_patch_ref:
  556. self._Capture(['reset', '--soft', base_rev])
  557. return latest_commit
  558. def check_diff(self, previous_commit, files=None):
  559. # type: (str, Optional[List[str]]) -> bool
  560. """Check if a diff exists between the current commit and `previous_commit`.
  561. Returns True if there were diffs or if an error was encountered.
  562. """
  563. cmd = ['diff', previous_commit, '--quiet']
  564. if files:
  565. cmd += ['--'] + files
  566. try:
  567. self._Capture(cmd)
  568. return False
  569. except subprocess2.CalledProcessError as e:
  570. # git diff --quiet exits with 1 if there were diffs.
  571. if e.returncode != 1:
  572. self.Print('git returned non-zero exit status %s:\n%s' %
  573. (e.returncode, e.stderr.decode('utf-8')))
  574. return True
  575. def set_config(f):
  576. def wrapper(*args):
  577. return_val = f(*args)
  578. if os.path.exists(os.path.join(args[0].checkout_path, '.git')):
  579. # The config updates to the project are stored in this list
  580. # and updated consecutively after the reads. The updates
  581. # are done this way because `scm.GIT.GetConfig` caches
  582. # the config file and `scm.GIT.SetConfig` evicts the cache.
  583. # This ensures we don't interleave reads and writes causing
  584. # the cache to set and unset consecutively.
  585. config_updates = []
  586. if scm.GIT.GetConfig(
  587. args[0].checkout_path,
  588. 'blame.ignorerevsfile') != '.git-blame-ignore-revs':
  589. config_updates.append(
  590. ('blame.ignoreRevsFile', '.git-blame-ignore-revs'))
  591. ignore_submodules = scm.GIT.GetConfig(args[0].checkout_path,
  592. 'diff.ignoresubmodules',
  593. None, 'local')
  594. if not ignore_submodules:
  595. config_updates.append(('diff.ignoreSubmodules', 'dirty'))
  596. elif ignore_submodules != 'dirty':
  597. warning_message = (
  598. "diff.ignoreSubmodules is not set to 'dirty' "
  599. "for this repository.\n"
  600. "This may cause unexpected behavior with submodules; "
  601. "see //docs/git_submodules.md\n"
  602. "Consider setting the config:\n"
  603. "\tgit config diff.ignoreSubmodule dirty\n"
  604. "or disable this warning by setting the "
  605. "GCLIENT_SUPPRESS_SUBMODULE_WARNING environment "
  606. "variable to 1.")
  607. if os.environ.get(
  608. 'GCLIENT_SUPPRESS_SUBMODULE_WARNING') != '1':
  609. gclient_utils.AddWarning(warning_message)
  610. if scm.GIT.GetConfig(args[0].checkout_path,
  611. 'fetch.recursesubmodules') != 'off':
  612. config_updates.append(('fetch.recurseSubmodules', 'off'))
  613. if scm.GIT.GetConfig(args[0].checkout_path,
  614. 'push.recursesubmodules') != 'off':
  615. # The default is off, but if user sets submodules.recurse to
  616. # on, this becomes on too. We never want to push submodules
  617. # for gclient managed repositories. Push, even if a no-op,
  618. # will increase `git cl upload` latency.
  619. config_updates.append(('push.recurseSubmodules', 'off'))
  620. for update in config_updates:
  621. scm.GIT.SetConfig(args[0].checkout_path,
  622. update[0],
  623. update[1],
  624. modify_all=True)
  625. return return_val
  626. return wrapper
  627. @set_config
  628. def update(self, options, args, file_list):
  629. """Runs git to update or transparently checkout the working copy.
  630. All updated files will be appended to file_list.
  631. Raises:
  632. Error: if can't get URL for relative path.
  633. """
  634. if args:
  635. raise gclient_utils.Error("Unsupported argument(s): %s" %
  636. ",".join(args))
  637. url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
  638. revision = deps_revision
  639. managed = True
  640. if options.revision:
  641. # Override the revision number.
  642. revision = str(options.revision)
  643. if revision == 'unmanaged':
  644. # Check again for a revision in case an initial ref was specified
  645. # in the url, for example bla.git@refs/heads/custombranch
  646. revision = deps_revision
  647. managed = False
  648. if not revision:
  649. # If a dependency is not pinned, track the default remote branch.
  650. revision = scm.GIT.GetRemoteHeadRef(self.checkout_path, self.url,
  651. self.remote)
  652. if revision.startswith('origin/'):
  653. revision = 'refs/remotes/' + revision
  654. if managed and platform.system() == 'Windows':
  655. self._DisableHooks()
  656. printed_path = False
  657. verbose = []
  658. if options.verbose:
  659. self.Print('_____ %s at %s' % (self.relpath, revision),
  660. timestamp=False)
  661. verbose = ['--verbose']
  662. printed_path = True
  663. revision_ref = revision
  664. if ':' in revision:
  665. revision_ref, _, revision = revision.partition(':')
  666. if revision_ref.startswith('refs/branch-heads'):
  667. options.with_branch_heads = True
  668. mirror = self._GetMirror(url, options, revision, revision_ref)
  669. if mirror:
  670. url = mirror.mirror_path
  671. remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
  672. if remote_ref:
  673. # Rewrite remote refs to their local equivalents.
  674. revision = ''.join(remote_ref)
  675. rev_type = "branch"
  676. elif revision.startswith('refs/heads/'):
  677. # Local branch? We probably don't want to support, since DEPS should
  678. # always specify branches as they are in the upstream repo.
  679. rev_type = "branch"
  680. else:
  681. # hash is also a tag, only make a distinction at checkout.
  682. # Any ref (e.g. /refs/changes/*) not a branch has no difference from
  683. # a hash.
  684. rev_type = "hash"
  685. # If we are going to introduce a new project, there is a possibility
  686. # that we are syncing back to a state where the project was originally a
  687. # sub-project rolled by DEPS (realistic case: crossing the Blink merge
  688. # point syncing backwards, when Blink was a DEPS entry and not part of
  689. # src.git). In such case, we might have a backup of the former .git
  690. # folder, which can be used to avoid re-fetching the entire repo again
  691. # (useful for bisects).
  692. backup_dir = self.GetGitBackupDirPath()
  693. target_dir = os.path.join(self.checkout_path, '.git')
  694. if os.path.exists(backup_dir) and not os.path.exists(target_dir):
  695. gclient_utils.safe_makedirs(self.checkout_path)
  696. os.rename(backup_dir, target_dir)
  697. # Reset to a clean state
  698. self._Scrub('HEAD', options)
  699. if (not os.path.exists(self.checkout_path) or
  700. (os.path.isdir(self.checkout_path)
  701. and not os.path.exists(os.path.join(self.checkout_path, '.git')))):
  702. if mirror:
  703. self._UpdateMirrorIfNotContains(mirror, options, rev_type,
  704. revision)
  705. try:
  706. self.current_revision = self._Clone(revision, url, options)
  707. except subprocess2.CalledProcessError as e:
  708. logging.warning('Clone failed due to: %s', e)
  709. self._DeleteOrMove(options.force)
  710. self.current_revision = self._Clone(revision, url, options)
  711. if file_list is not None:
  712. files = self._Capture(
  713. ['-c', 'core.quotePath=false', 'ls-files']).splitlines()
  714. file_list.extend(
  715. [os.path.join(self.checkout_path, f) for f in files])
  716. if mirror:
  717. self._Capture(
  718. ['remote', 'set-url', '--push', 'origin', mirror.url])
  719. if not verbose:
  720. # Make the output a little prettier. It's nice to have some
  721. # whitespace between projects when cloning.
  722. self.Print('')
  723. return self._Capture(['rev-parse', '--verify', 'HEAD'])
  724. if mirror:
  725. self._Capture(['remote', 'set-url', '--push', 'origin', mirror.url])
  726. if not managed:
  727. self._SetFetchConfig(options)
  728. self.Print('________ unmanaged solution; skipping %s' %
  729. self.relpath)
  730. return self._Capture(['rev-parse', '--verify', 'HEAD'])
  731. # Special case for rev_type = hash. If we use submodules, we can check
  732. # information already.
  733. if rev_type == 'hash':
  734. if self.current_revision == revision:
  735. if verbose:
  736. self.Print('Using submodule information to skip check')
  737. if options.reset or options.force:
  738. self._Scrub('HEAD', options)
  739. return revision
  740. self._maybe_break_locks(options)
  741. if mirror:
  742. self._UpdateMirrorIfNotContains(mirror, options, rev_type, revision)
  743. # See if the url has changed (the unittests use git://foo for the url,
  744. # let that through).
  745. current_url = scm.GIT.GetConfig(self.checkout_path,
  746. f'remote.{self.remote}.url')
  747. return_early = False
  748. # TODO(maruel): Delete url != 'git://foo' since it's just to make the
  749. # unit test pass. (and update the comment above)
  750. strp_url = url[:-4] if url.endswith('.git') else url
  751. strp_current_url = current_url[:-4] if current_url.endswith(
  752. '.git') else current_url
  753. if (strp_current_url.rstrip('/') != strp_url.rstrip('/')
  754. and url != 'git://foo'):
  755. self.Print('_____ switching %s from %s to new upstream %s' %
  756. (self.relpath, current_url, url))
  757. if not (options.force or options.reset):
  758. # Make sure it's clean
  759. self._CheckClean(revision)
  760. # Switch over to the new upstream
  761. self._Run(['remote', 'set-url', self.remote, url], options)
  762. if mirror:
  763. if git_cache.Mirror.CacheDirToUrl(current_url.rstrip(
  764. '/')) == git_cache.Mirror.CacheDirToUrl(
  765. url.rstrip('/')):
  766. # Reset alternates when the cache dir is updated.
  767. with open(
  768. os.path.join(self.checkout_path, '.git', 'objects',
  769. 'info', 'alternates'), 'w') as fh:
  770. fh.write(os.path.join(url, 'objects'))
  771. else:
  772. # Because we use Git alternatives, our existing repository
  773. # is not self-contained. It's possible that new git
  774. # alternative doesn't have all necessary objects that the
  775. # current repository needs. Instead of blindly hoping that
  776. # new alternative contains all necessary objects, keep the
  777. # old alternative and just append a new one on top of it.
  778. with open(
  779. os.path.join(self.checkout_path, '.git', 'objects',
  780. 'info', 'alternates'), 'a') as fh:
  781. fh.write("\n" + os.path.join(url, 'objects'))
  782. current_revision = self._EnsureValidHeadObjectOrCheckout(
  783. revision, options, url)
  784. self._FetchAndReset(revision, file_list, options)
  785. return_early = True
  786. else:
  787. current_revision = self._EnsureValidHeadObjectOrCheckout(
  788. revision, options, url)
  789. if return_early:
  790. return current_revision or self._Capture(
  791. ['rev-parse', '--verify', 'HEAD'])
  792. cur_branch = self._GetCurrentBranch()
  793. # Cases:
  794. # 0) HEAD is detached. Probably from our initial clone.
  795. # - make sure HEAD is contained by a named ref, then update.
  796. # Cases 1-4. HEAD is a branch.
  797. # 1) current branch is not tracking a remote branch
  798. # - try to rebase onto the new hash or branch
  799. # 2) current branch is tracking a remote branch with local committed
  800. # changes, but the DEPS file switched to point to a hash
  801. # - rebase those changes on top of the hash
  802. # 3) current branch is tracking a remote branch w/or w/out changes, and
  803. # no DEPS switch
  804. # - see if we can FF, if not, prompt the user for rebase, merge, or stop
  805. # 4) current branch is tracking a remote branch, but DEPS switches to a
  806. # different remote branch, and a) current branch has no local changes,
  807. # and --force: - checkout new branch b) current branch has local
  808. # changes, and --force and --reset: - checkout new branch c) otherwise
  809. # exit
  810. # GetUpstreamBranch returns something like 'refs/remotes/origin/main'
  811. # for a tracking branch or 'main' if not a tracking branch (it's based
  812. # on a specific rev/hash) or it returns None if it couldn't find an
  813. # upstream
  814. if cur_branch is None:
  815. upstream_branch = None
  816. current_type = "detached"
  817. logging.debug("Detached HEAD")
  818. else:
  819. upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
  820. if not upstream_branch or not upstream_branch.startswith(
  821. 'refs/remotes'):
  822. current_type = "hash"
  823. logging.debug(
  824. "Current branch is not tracking an upstream (remote)"
  825. " branch.")
  826. elif upstream_branch.startswith('refs/remotes'):
  827. current_type = "branch"
  828. else:
  829. raise gclient_utils.Error('Invalid Upstream: %s' %
  830. upstream_branch)
  831. self._SetFetchConfig(options)
  832. # Fetch upstream if we don't already have |revision|.
  833. if not scm.GIT.IsValidRevision(
  834. self.checkout_path, revision, sha_only=True):
  835. self._Fetch(options, prune=options.force)
  836. if not scm.GIT.IsValidRevision(
  837. self.checkout_path, revision, sha_only=True):
  838. # Update the remotes first so we have all the refs.
  839. remote_output = scm.GIT.Capture(['remote'] + verbose +
  840. ['update'],
  841. cwd=self.checkout_path)
  842. if verbose:
  843. self.Print(remote_output)
  844. revision = self._AutoFetchRef(options, revision)
  845. # This is a big hammer, debatable if it should even be here...
  846. if options.force or options.reset:
  847. target = 'HEAD'
  848. if options.upstream and upstream_branch:
  849. target = upstream_branch
  850. self._Scrub(target, options)
  851. if current_type == 'detached':
  852. # case 0
  853. # We just did a Scrub, this is as clean as it's going to get. In
  854. # particular if HEAD is a commit that contains two versions of the
  855. # same file on a case-insensitive filesystem (e.g. 'a' and 'A'),
  856. # there's no way to actually "Clean" the checkout; that commit is
  857. # uncheckoutable on this system. The best we can do is carry forward
  858. # to the checkout step.
  859. if not (options.force or options.reset):
  860. self._CheckClean(revision)
  861. self._CheckDetachedHead(revision, options)
  862. if not current_revision:
  863. current_revision = self._Capture(
  864. ['rev-list', '-n', '1', 'HEAD'])
  865. if current_revision == revision:
  866. self.Print('Up-to-date; skipping checkout.')
  867. else:
  868. # 'git checkout' may need to overwrite existing untracked files.
  869. # Allow it only when nuclear options are enabled.
  870. self._Checkout(
  871. options,
  872. revision,
  873. force=(options.force and options.delete_unversioned_trees),
  874. quiet=True,
  875. )
  876. if not printed_path:
  877. self.Print('_____ %s at %s' % (self.relpath, revision),
  878. timestamp=False)
  879. elif current_type == 'hash':
  880. # case 1
  881. # Can't find a merge-base since we don't know our upstream. That
  882. # makes this command VERY likely to produce a rebase failure. For
  883. # now we assume origin is our upstream since that's what the old
  884. # behavior was.
  885. upstream_branch = self.remote
  886. if options.revision or deps_revision:
  887. upstream_branch = revision
  888. self._AttemptRebase(upstream_branch,
  889. file_list,
  890. options,
  891. printed_path=printed_path,
  892. merge=options.merge)
  893. printed_path = True
  894. elif rev_type == 'hash':
  895. # case 2
  896. self._AttemptRebase(upstream_branch,
  897. file_list,
  898. options,
  899. newbase=revision,
  900. printed_path=printed_path,
  901. merge=options.merge)
  902. printed_path = True
  903. elif remote_ref and ''.join(remote_ref) != upstream_branch:
  904. # case 4
  905. new_base = ''.join(remote_ref)
  906. if not printed_path:
  907. self.Print('_____ %s at %s' % (self.relpath, revision),
  908. timestamp=False)
  909. switch_error = (
  910. "Could not switch upstream branch from %s to %s\n" %
  911. (upstream_branch, new_base) +
  912. "Please use --force or merge or rebase manually:\n" +
  913. "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
  914. "OR git checkout -b <some new branch> %s" % new_base)
  915. force_switch = False
  916. if options.force:
  917. try:
  918. self._CheckClean(revision)
  919. # case 4a
  920. force_switch = True
  921. except gclient_utils.Error as e:
  922. if options.reset:
  923. # case 4b
  924. force_switch = True
  925. else:
  926. switch_error = '%s\n%s' % (str(e), switch_error)
  927. if force_switch:
  928. self.Print("Switching upstream branch from %s to %s" %
  929. (upstream_branch, new_base))
  930. switch_branch = 'gclient_' + remote_ref[1]
  931. self._Capture(['branch', '-f', switch_branch, new_base])
  932. self._Checkout(options, switch_branch, force=True, quiet=True)
  933. else:
  934. # case 4c
  935. raise gclient_utils.Error(switch_error)
  936. else:
  937. # case 3 - the default case
  938. rebase_files = self._GetDiffFilenames(upstream_branch)
  939. if verbose:
  940. self.Print('Trying fast-forward merge to branch : %s' %
  941. upstream_branch)
  942. try:
  943. merge_args = ['merge']
  944. if options.merge:
  945. merge_args.append('--ff')
  946. else:
  947. merge_args.append('--ff-only')
  948. merge_args.append(upstream_branch)
  949. merge_output = self._Capture(merge_args)
  950. except subprocess2.CalledProcessError as e:
  951. rebase_files = []
  952. if re.search(b'fatal: Not possible to fast-forward, aborting.',
  953. e.stderr):
  954. if not printed_path:
  955. self.Print('_____ %s at %s' % (self.relpath, revision),
  956. timestamp=False)
  957. printed_path = True
  958. while True:
  959. if not options.auto_rebase:
  960. try:
  961. action = self._AskForData(
  962. 'Cannot %s, attempt to rebase? '
  963. '(y)es / (q)uit / (s)kip : ' %
  964. ('merge' if options.merge else
  965. 'fast-forward merge'), options)
  966. except ValueError:
  967. raise gclient_utils.Error('Invalid Character')
  968. if options.auto_rebase or re.match(
  969. r'yes|y', action, re.I):
  970. self._AttemptRebase(upstream_branch,
  971. rebase_files,
  972. options,
  973. printed_path=printed_path,
  974. merge=False)
  975. printed_path = True
  976. break
  977. if re.match(r'quit|q', action, re.I):
  978. raise gclient_utils.Error(
  979. "Can't fast-forward, please merge or "
  980. "rebase manually.\n"
  981. "cd %s && git " % self.checkout_path +
  982. "rebase %s" % upstream_branch)
  983. if re.match(r'skip|s', action, re.I):
  984. self.Print('Skipping %s' % self.relpath)
  985. return
  986. self.Print('Input not recognized')
  987. elif re.match(
  988. b"error: Your local changes to '.*' would be "
  989. b"overwritten by merge. Aborting.\nPlease, commit your "
  990. b"changes or stash them before you can merge.\n",
  991. e.stderr):
  992. if not printed_path:
  993. self.Print('_____ %s at %s' % (self.relpath, revision),
  994. timestamp=False)
  995. printed_path = True
  996. raise gclient_utils.Error(e.stderr.decode('utf-8'))
  997. else:
  998. # Some other problem happened with the merge
  999. logging.error("Error during fast-forward merge in %s!" %
  1000. self.relpath)
  1001. self.Print(e.stderr.decode('utf-8'))
  1002. raise
  1003. else:
  1004. # Fast-forward merge was successful
  1005. if not re.match('Already up-to-date.', merge_output) or verbose:
  1006. if not printed_path:
  1007. self.Print('_____ %s at %s' % (self.relpath, revision),
  1008. timestamp=False)
  1009. printed_path = True
  1010. self.Print(merge_output.strip())
  1011. if not verbose:
  1012. # Make the output a little prettier. It's nice to have
  1013. # some whitespace between projects when syncing.
  1014. self.Print('')
  1015. if file_list is not None:
  1016. file_list.extend(
  1017. [os.path.join(self.checkout_path, f) for f in rebase_files])
  1018. # If the rebase generated a conflict, abort and ask user to fix
  1019. if self._IsRebasing():
  1020. raise gclient_utils.Error(
  1021. '\n____ %s at %s\n'
  1022. '\nConflict while rebasing this branch.\n'
  1023. 'Fix the conflict and run gclient again.\n'
  1024. 'See man git-rebase for details.\n' % (self.relpath, revision))
  1025. # If --reset and --delete_unversioned_trees are specified, remove any
  1026. # untracked directories.
  1027. if options.reset and options.delete_unversioned_trees:
  1028. # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1
  1029. # (the merge-base by default), so doesn't include untracked files.
  1030. # So we use 'git ls-files --directory --others --exclude-standard'
  1031. # here directly.
  1032. paths = scm.GIT.Capture([
  1033. '-c', 'core.quotePath=false', 'ls-files', '--directory',
  1034. '--others', '--exclude-standard'
  1035. ], self.checkout_path)
  1036. for path in (p for p in paths.splitlines() if p.endswith('/')):
  1037. full_path = os.path.join(self.checkout_path, path)
  1038. if not os.path.islink(full_path):
  1039. self.Print('_____ removing unversioned directory %s' % path)
  1040. gclient_utils.rmtree(full_path)
  1041. if not current_revision:
  1042. current_revision = self._Capture(['rev-parse', '--verify', 'HEAD'])
  1043. if verbose:
  1044. self.Print(f'Checked out revision {current_revision}',
  1045. timestamp=False)
  1046. return current_revision
  1047. def revert(self, options, _args, file_list):
  1048. """Reverts local modifications.
  1049. All reverted files will be appended to file_list.
  1050. """
  1051. if not os.path.isdir(self.checkout_path):
  1052. # revert won't work if the directory doesn't exist. It needs to
  1053. # checkout instead.
  1054. self.Print('_____ %s is missing, syncing instead' % self.relpath)
  1055. # Don't reuse the args.
  1056. return self.update(options, [], file_list)
  1057. default_rev = "refs/heads/main"
  1058. if options.upstream:
  1059. if self._GetCurrentBranch():
  1060. upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
  1061. default_rev = upstream_branch or default_rev
  1062. _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
  1063. if not deps_revision:
  1064. deps_revision = default_rev
  1065. if deps_revision.startswith('refs/heads/'):
  1066. deps_revision = deps_revision.replace('refs/heads/',
  1067. self.remote + '/')
  1068. try:
  1069. deps_revision = self.GetUsableRev(deps_revision, options)
  1070. except NoUsableRevError as e:
  1071. # If the DEPS entry's url and hash changed, try to update the
  1072. # origin. See also http://crbug.com/520067.
  1073. logging.warning(
  1074. "Couldn't find usable revision, will retrying to update instead: %s",
  1075. str(e))
  1076. return self.update(options, [], file_list)
  1077. if file_list is not None:
  1078. files = self._GetDiffFilenames(deps_revision)
  1079. self._Scrub(deps_revision, options)
  1080. self._Run(['clean', '-f', '-d'], options)
  1081. if file_list is not None:
  1082. file_list.extend(
  1083. [os.path.join(self.checkout_path, f) for f in files])
  1084. def revinfo(self, _options, _args, _file_list):
  1085. """Returns revision"""
  1086. return self._Capture(['rev-parse', 'HEAD'])
  1087. def runhooks(self, options, args, file_list):
  1088. self.status(options, args, file_list)
  1089. def status(self, options, _args, file_list):
  1090. """Display status information."""
  1091. if not os.path.isdir(self.checkout_path):
  1092. self.Print('________ couldn\'t run status in %s:\n'
  1093. 'The directory does not exist.' % self.checkout_path)
  1094. else:
  1095. merge_base = []
  1096. if self.url:
  1097. _, base_rev = gclient_utils.SplitUrlRevision(self.url)
  1098. if base_rev:
  1099. if base_rev.startswith('refs/'):
  1100. base_rev = self._ref_to_remote_ref(base_rev)
  1101. merge_base = [base_rev]
  1102. self._Run(['-c', 'core.quotePath=false', 'diff', '--name-status'] +
  1103. merge_base,
  1104. options,
  1105. always_show_header=options.verbose)
  1106. if file_list is not None:
  1107. files = self._GetDiffFilenames(
  1108. merge_base[0] if merge_base else None)
  1109. file_list.extend(
  1110. [os.path.join(self.checkout_path, f) for f in files])
  1111. def GetUsableRev(self, rev, options):
  1112. """Finds a useful revision for this repository."""
  1113. sha1 = None
  1114. if not os.path.isdir(self.checkout_path):
  1115. raise NoUsableRevError(
  1116. 'This is not a git repo, so we cannot get a usable rev.')
  1117. if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
  1118. sha1 = rev
  1119. else:
  1120. # May exist in origin, but we don't have it yet, so fetch and look
  1121. # again.
  1122. self._Fetch(options)
  1123. if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
  1124. sha1 = rev
  1125. if not sha1:
  1126. raise NoUsableRevError(
  1127. 'Hash %s does not appear to be a valid hash in this repo.' %
  1128. rev)
  1129. return sha1
  1130. def GetGitBackupDirPath(self):
  1131. """Returns the path where the .git folder for the current project can be
  1132. staged/restored. Use case: subproject moved from DEPS <-> outer project."""
  1133. return os.path.join(self._root_dir,
  1134. 'old_' + self.relpath.replace(os.sep, '_')) + '.git'
  1135. def _GetMirror(self, url, options, revision=None, revision_ref=None):
  1136. """Get a git_cache.Mirror object for the argument url."""
  1137. if not self.cache_dir:
  1138. return None
  1139. mirror_kwargs = {
  1140. 'print_func': self.filter,
  1141. 'refs': [],
  1142. 'commits': [],
  1143. }
  1144. if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
  1145. mirror_kwargs['refs'].append('refs/branch-heads/*')
  1146. elif revision_ref and revision_ref.startswith('refs/branch-heads/'):
  1147. mirror_kwargs['refs'].append(revision_ref)
  1148. if hasattr(options, 'with_tags') and options.with_tags:
  1149. mirror_kwargs['refs'].append('refs/tags/*')
  1150. elif revision_ref and revision_ref.startswith('refs/tags/'):
  1151. mirror_kwargs['refs'].append(revision_ref)
  1152. if revision and not revision.startswith('refs/'):
  1153. mirror_kwargs['commits'].append(revision)
  1154. return git_cache.Mirror(url, **mirror_kwargs)
  1155. def _UpdateMirrorIfNotContains(self, mirror, options, rev_type, revision):
  1156. """Update a git mirror by fetching the latest commits from the remote,
  1157. unless mirror already contains revision whose type is sha1 hash.
  1158. """
  1159. if rev_type == 'hash' and mirror.contains_revision(revision):
  1160. if options.verbose:
  1161. self.Print('skipping mirror update, it has rev=%s already' %
  1162. revision,
  1163. timestamp=False)
  1164. return
  1165. if getattr(options, 'shallow', False):
  1166. depth = 10000
  1167. else:
  1168. depth = None
  1169. mirror.populate(verbose=options.verbose,
  1170. bootstrap=not getattr(options, 'no_bootstrap', False),
  1171. depth=depth,
  1172. lock_timeout=getattr(options, 'lock_timeout', 0))
  1173. def _Clone(self, revision, url, options):
  1174. """Clone a git repository from the given URL.
  1175. Once we've cloned the repo, we checkout a working branch if the
  1176. specified revision is a branch head. If it is a tag or a specific
  1177. commit, then we leave HEAD detached as it makes future updates simpler
  1178. -- in this case the user should first create a new branch or switch to
  1179. an existing branch before making changes in the repo."""
  1180. if self.print_outbuf:
  1181. print_stdout = True
  1182. filter_fn = None
  1183. else:
  1184. print_stdout = False
  1185. filter_fn = self.filter
  1186. if not options.verbose:
  1187. # git clone doesn't seem to insert a newline properly before
  1188. # printing to stdout
  1189. self.Print('')
  1190. # If the parent directory does not exist, Git clone on Windows will not
  1191. # create it, so we need to do it manually.
  1192. parent_dir = os.path.dirname(self.checkout_path)
  1193. gclient_utils.safe_makedirs(parent_dir)
  1194. # Set up Git authentication configuration that is needed to clone/fetch the repo.
  1195. if newauth.Enabled():
  1196. git_auth.ConfigureGlobal('/', url)
  1197. if hasattr(options, 'no_history') and options.no_history:
  1198. self._Run(['init', self.checkout_path], options, cwd=self._root_dir)
  1199. self._Run(['remote', 'add', 'origin', url], options)
  1200. revision = self._AutoFetchRef(options, revision, depth=1)
  1201. remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
  1202. self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
  1203. else:
  1204. cfg = gclient_utils.DefaultIndexPackConfig(url)
  1205. clone_cmd = cfg + ['clone', '--no-checkout', '--progress']
  1206. if self.cache_dir:
  1207. clone_cmd.append('--shared')
  1208. if options.verbose:
  1209. clone_cmd.append('--verbose')
  1210. clone_cmd.append(url)
  1211. tmp_dir = tempfile.mkdtemp(prefix='_gclient_%s_' %
  1212. os.path.basename(self.checkout_path),
  1213. dir=parent_dir)
  1214. clone_cmd.append(tmp_dir)
  1215. try:
  1216. self._Run(clone_cmd,
  1217. options,
  1218. cwd=self._root_dir,
  1219. retry=True,
  1220. print_stdout=print_stdout,
  1221. filter_fn=filter_fn)
  1222. logging.debug(
  1223. 'Cloned into temporary dir, moving to checkout_path')
  1224. gclient_utils.safe_makedirs(self.checkout_path)
  1225. gclient_utils.safe_rename(
  1226. os.path.join(tmp_dir, '.git'),
  1227. os.path.join(self.checkout_path, '.git'))
  1228. except:
  1229. traceback.print_exc(file=self.out_fh)
  1230. raise
  1231. finally:
  1232. if os.listdir(tmp_dir):
  1233. self.Print('_____ removing non-empty tmp dir %s' % tmp_dir)
  1234. gclient_utils.rmtree(tmp_dir)
  1235. self._SetFetchConfig(options)
  1236. self._Fetch(options, prune=options.force)
  1237. revision = self._AutoFetchRef(options, revision)
  1238. remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
  1239. self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
  1240. if self._GetCurrentBranch() is None:
  1241. # Squelch git's very verbose detached HEAD warning and use our own
  1242. self.Print((
  1243. 'Checked out %s to a detached HEAD. Before making any commits\n'
  1244. 'in this repo, you should use \'git checkout <branch>\' to switch \n'
  1245. 'to an existing branch or use \'git checkout %s -b <branch>\' to\n'
  1246. 'create a new branch for your work.') % (revision, self.remote))
  1247. return revision
  1248. def _AskForData(self, prompt, options):
  1249. if options.jobs > 1:
  1250. self.Print(prompt)
  1251. raise gclient_utils.Error("Background task requires input. Rerun "
  1252. "gclient with --jobs=1 so that\n"
  1253. "interaction is possible.")
  1254. return gclient_utils.AskForData(prompt)
  1255. def _AttemptRebase(self,
  1256. upstream,
  1257. files,
  1258. options,
  1259. newbase=None,
  1260. branch=None,
  1261. printed_path=False,
  1262. merge=False):
  1263. """Attempt to rebase onto either upstream or, if specified, newbase."""
  1264. if files is not None:
  1265. files.extend(self._GetDiffFilenames(upstream))
  1266. revision = upstream
  1267. if newbase:
  1268. revision = newbase
  1269. action = 'merge' if merge else 'rebase'
  1270. if not printed_path:
  1271. self.Print('_____ %s : Attempting %s onto %s...' %
  1272. (self.relpath, action, revision))
  1273. printed_path = True
  1274. else:
  1275. self.Print('Attempting %s onto %s...' % (action, revision))
  1276. if merge:
  1277. merge_output = self._Capture(['merge', revision])
  1278. if options.verbose:
  1279. self.Print(merge_output)
  1280. return
  1281. # Build the rebase command here using the args
  1282. # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
  1283. rebase_cmd = ['rebase']
  1284. if options.verbose:
  1285. rebase_cmd.append('--verbose')
  1286. if newbase:
  1287. rebase_cmd.extend(['--onto', newbase])
  1288. rebase_cmd.append(upstream)
  1289. if branch:
  1290. rebase_cmd.append(branch)
  1291. try:
  1292. rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
  1293. except subprocess2.CalledProcessError as e:
  1294. if (re.match(
  1295. br'cannot rebase: you have unstaged changes', e.stderr
  1296. ) or re.match(
  1297. br'cannot rebase: your index contains uncommitted changes',
  1298. e.stderr)):
  1299. while True:
  1300. rebase_action = self._AskForData(
  1301. 'Cannot rebase because of unstaged changes.\n'
  1302. '\'git reset --hard HEAD\' ?\n'
  1303. 'WARNING: destroys any uncommitted work in your current branch!'
  1304. ' (y)es / (q)uit / (s)how : ', options)
  1305. if re.match(r'yes|y', rebase_action, re.I):
  1306. self._Scrub('HEAD', options)
  1307. # Should this be recursive?
  1308. rebase_output = scm.GIT.Capture(rebase_cmd,
  1309. cwd=self.checkout_path)
  1310. break
  1311. if re.match(r'quit|q', rebase_action, re.I):
  1312. raise gclient_utils.Error(
  1313. "Please merge or rebase manually\n"
  1314. "cd %s && git " % self.checkout_path +
  1315. "%s" % ' '.join(rebase_cmd))
  1316. if re.match(r'show|s', rebase_action, re.I):
  1317. self.Print('%s' % e.stderr.decode('utf-8').strip())
  1318. continue
  1319. gclient_utils.Error("Input not recognized")
  1320. continue
  1321. elif re.search(br'^CONFLICT', e.stdout, re.M):
  1322. raise gclient_utils.Error(
  1323. "Conflict while rebasing this branch.\n"
  1324. "Fix the conflict and run gclient again.\n"
  1325. "See 'man git-rebase' for details.\n")
  1326. else:
  1327. self.Print(e.stdout.decode('utf-8').strip())
  1328. self.Print('Rebase produced error output:\n%s' %
  1329. e.stderr.decode('utf-8').strip())
  1330. raise gclient_utils.Error(
  1331. "Unrecognized error, please merge or rebase "
  1332. "manually.\ncd %s && git " % self.checkout_path +
  1333. "%s" % ' '.join(rebase_cmd))
  1334. self.Print(rebase_output.strip())
  1335. if not options.verbose:
  1336. # Make the output a little prettier. It's nice to have some
  1337. # whitespace between projects when syncing.
  1338. self.Print('')
  1339. def _EnsureValidHeadObjectOrCheckout(self, revision, options, url):
  1340. # Special case handling if all 3 conditions are met:
  1341. # * the mirros have recently changed, but deps destination remains same,
  1342. # * the git histories of mirrors are conflicting. * git cache is used
  1343. # This manifests itself in current checkout having invalid HEAD commit
  1344. # on most git operations. Since git cache is used, just deleted the .git
  1345. # folder, and re-create it by cloning.
  1346. try:
  1347. return self._Capture(['rev-list', '-n', '1', 'HEAD'])
  1348. except subprocess2.CalledProcessError as e:
  1349. if (b'fatal: bad object HEAD' in e.stderr and self.cache_dir
  1350. and self.cache_dir in url):
  1351. self.Print(
  1352. ('Likely due to DEPS change with git cache_dir, '
  1353. 'the current commit points to no longer existing object.\n'
  1354. '%s' % e))
  1355. self._DeleteOrMove(options.force)
  1356. return self._Clone(revision, url, options)
  1357. raise
  1358. def _IsRebasing(self):
  1359. # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git
  1360. # doesn't have a plumbing command to determine whether a rebase is in
  1361. # progress, so for now emualate (more-or-less) git-rebase.sh /
  1362. # git-completion.bash
  1363. g = os.path.join(self.checkout_path, '.git')
  1364. return (os.path.isdir(os.path.join(g, "rebase-merge"))
  1365. or os.path.isdir(os.path.join(g, "rebase-apply")))
  1366. def _CheckClean(self, revision):
  1367. lockfile = os.path.join(self.checkout_path, ".git", "index.lock")
  1368. if os.path.exists(lockfile):
  1369. raise gclient_utils.Error(
  1370. '\n____ %s at %s\n'
  1371. '\tYour repo is locked, possibly due to a concurrent git process.\n'
  1372. '\tIf no git executable is running, then clean up %r and try again.\n'
  1373. % (self.relpath, revision, lockfile))
  1374. # Ensure that the tree is clean.
  1375. if scm.GIT.Capture([
  1376. 'status', '--porcelain', '--untracked-files=no',
  1377. '--ignore-submodules'
  1378. ],
  1379. cwd=self.checkout_path):
  1380. raise gclient_utils.Error(
  1381. '\n____ %s at %s\n'
  1382. '\tYou have uncommitted changes.\n'
  1383. '\tcd into %s, run git status to see changes,\n'
  1384. '\tand commit, stash, or reset.\n' %
  1385. (self.relpath, revision, self.relpath))
  1386. def _CheckDetachedHead(self, revision, _options):
  1387. # HEAD is detached. Make sure it is safe to move away from (i.e., it is
  1388. # reference by a commit). If not, error out -- most likely a rebase is
  1389. # in progress, try to detect so we can give a better error.
  1390. try:
  1391. scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
  1392. cwd=self.checkout_path)
  1393. except subprocess2.CalledProcessError:
  1394. # Commit is not contained by any rev. See if the user is rebasing:
  1395. if self._IsRebasing():
  1396. # Punt to the user
  1397. raise gclient_utils.Error(
  1398. '\n____ %s at %s\n'
  1399. '\tAlready in a conflict, i.e. (no branch).\n'
  1400. '\tFix the conflict and run gclient again.\n'
  1401. '\tOr to abort run:\n\t\tgit-rebase --abort\n'
  1402. '\tSee man git-rebase for details.\n' %
  1403. (self.relpath, revision))
  1404. # Let's just save off the commit so we can proceed.
  1405. name = ('saved-by-gclient-' +
  1406. self._Capture(['rev-parse', '--short', 'HEAD']))
  1407. self._Capture(['branch', '-f', name])
  1408. self.Print(
  1409. '_____ found an unreferenced commit and saved it as \'%s\'' %
  1410. name)
  1411. def _GetCurrentBranch(self):
  1412. # Returns name of current branch or None for detached HEAD
  1413. branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
  1414. if branch == 'HEAD':
  1415. return None
  1416. return branch
  1417. def _Capture(self, args, **kwargs):
  1418. set_git_dir = 'cwd' not in kwargs
  1419. kwargs.setdefault('cwd', self.checkout_path)
  1420. kwargs.setdefault('stderr', subprocess2.PIPE)
  1421. strip = kwargs.pop('strip', True)
  1422. env = scm.GIT.ApplyEnvVars(kwargs)
  1423. # If an explicit cwd isn't set, then default to the .git/ subdir so we
  1424. # get stricter behavior. This can be useful in cases of slight
  1425. # corruption -- we don't accidentally go corrupting parent git checks
  1426. # too. See https://crbug.com/1000825 for an example.
  1427. if set_git_dir:
  1428. env.setdefault(
  1429. 'GIT_DIR',
  1430. os.path.abspath(os.path.join(self.checkout_path, '.git')))
  1431. kwargs.setdefault('env', env)
  1432. ret = git_common.run(*args, **kwargs)
  1433. if strip:
  1434. ret = ret.strip()
  1435. self.Print('Finished running: %s %s' % ('git', ' '.join(args)))
  1436. return ret
  1437. def _Checkout(self, options, ref, force=False, quiet=None):
  1438. """Performs a 'git-checkout' operation.
  1439. Args:
  1440. options: The configured option set
  1441. ref: (str) The branch/commit to checkout
  1442. quiet: (bool/None) Whether or not the checkout should pass '--quiet'; if
  1443. 'None', the behavior is inferred from 'options.verbose'.
  1444. Returns: (str) The output of the checkout operation
  1445. """
  1446. if quiet is None:
  1447. quiet = (not options.verbose)
  1448. checkout_args = ['checkout']
  1449. if force:
  1450. checkout_args.append('--force')
  1451. if quiet:
  1452. checkout_args.append('--quiet')
  1453. checkout_args.append(ref)
  1454. return self._Capture(checkout_args)
  1455. def _Fetch(self,
  1456. options,
  1457. remote=None,
  1458. prune=False,
  1459. quiet=False,
  1460. refspec=None,
  1461. depth=None):
  1462. cfg = gclient_utils.DefaultIndexPackConfig(self.url)
  1463. # When updating, the ref is modified to be a remote ref .
  1464. # (e.g. refs/heads/NAME becomes refs/remotes/REMOTE/NAME).
  1465. # Try to reverse that mapping.
  1466. original_ref = scm.GIT.RemoteRefToRef(refspec, self.remote)
  1467. if original_ref:
  1468. refspec = original_ref + ':' + refspec
  1469. # When a mirror is configured, it only fetches
  1470. # refs/{heads,branch-heads,tags}/*.
  1471. # If asked to fetch other refs, we must fetch those directly from
  1472. # the repository, and not from the mirror.
  1473. if not original_ref.startswith(
  1474. ('refs/heads/', 'refs/branch-heads/', 'refs/tags/')):
  1475. remote, _ = gclient_utils.SplitUrlRevision(self.url)
  1476. fetch_cmd = cfg + [
  1477. 'fetch',
  1478. remote or self.remote,
  1479. ]
  1480. if refspec:
  1481. fetch_cmd.append(refspec)
  1482. if prune:
  1483. fetch_cmd.append('--prune')
  1484. if options.verbose:
  1485. fetch_cmd.append('--verbose')
  1486. if not hasattr(options, 'with_tags') or not options.with_tags:
  1487. fetch_cmd.append('--no-tags')
  1488. elif quiet:
  1489. fetch_cmd.append('--quiet')
  1490. if depth:
  1491. fetch_cmd.append('--depth=' + str(depth))
  1492. self._Run(fetch_cmd, options, show_header=options.verbose, retry=True)
  1493. def _SetFetchConfig(self, options):
  1494. """Adds, and optionally fetches, "branch-heads" and "tags" refspecs
  1495. if requested."""
  1496. if options.force or options.reset:
  1497. try:
  1498. scm.GIT.SetConfig(self.checkout_path,
  1499. f'remote.{self.remote}.fetch',
  1500. modify_all=True)
  1501. scm.GIT.SetConfig(
  1502. self.checkout_path, f'remote.{self.remote}.fetch',
  1503. f'+refs/heads/*:refs/remotes/{self.remote}/*')
  1504. except subprocess2.CalledProcessError as e:
  1505. # If exit code was 5, it means we attempted to unset a config
  1506. # that didn't exist. Ignore it.
  1507. if e.returncode != 5:
  1508. raise
  1509. if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
  1510. scm.GIT.SetConfig(
  1511. self.checkout_path,
  1512. f'remote.{self.remote}.fetch',
  1513. '+refs/branch-heads/*:refs/remotes/branch-heads/*',
  1514. value_pattern='^\\+refs/branch-heads/\\*:.*$',
  1515. modify_all=True)
  1516. if hasattr(options, 'with_tags') and options.with_tags:
  1517. scm.GIT.SetConfig(self.checkout_path,
  1518. f'remote.{self.remote}.fetch',
  1519. '+refs/tags/*:refs/tags/*',
  1520. value_pattern='^\\+refs/tags/\\*:.*$',
  1521. modify_all=True)
  1522. def _AutoFetchRef(self, options, revision, depth=None):
  1523. """Attempts to fetch |revision| if not available in local repo.
  1524. Returns possibly updated revision."""
  1525. if not scm.GIT.IsValidRevision(self.checkout_path, revision):
  1526. self._Fetch(options, refspec=revision, depth=depth)
  1527. revision = self._Capture(['rev-parse', 'FETCH_HEAD'])
  1528. return revision
  1529. def _Run(self, args, options, **kwargs):
  1530. # Disable 'unused options' warning | pylint: disable=unused-argument
  1531. kwargs.setdefault('cwd', self.checkout_path)
  1532. kwargs.setdefault('filter_fn', self.filter)
  1533. kwargs.setdefault('show_header', True)
  1534. env = scm.GIT.ApplyEnvVars(kwargs)
  1535. cmd = ['git'] + args
  1536. gclient_utils.CheckCallAndFilter(cmd, env=env, **kwargs)
  1537. class CipdPackage(object):
  1538. """A representation of a single CIPD package."""
  1539. def __init__(self, name, version, authority_for_subdir):
  1540. self._authority_for_subdir = authority_for_subdir
  1541. self._name = name
  1542. self._version = version
  1543. @property
  1544. def authority_for_subdir(self):
  1545. """Whether this package has authority to act on behalf of its subdir.
  1546. Some operations should only be performed once per subdirectory. A package
  1547. that has authority for its subdirectory is the only package that should
  1548. perform such operations.
  1549. Returns:
  1550. bool; whether this package has subdir authority.
  1551. """
  1552. return self._authority_for_subdir
  1553. @property
  1554. def name(self):
  1555. return self._name
  1556. @property
  1557. def version(self):
  1558. return self._version
  1559. class CipdRoot(object):
  1560. """A representation of a single CIPD root."""
  1561. def __init__(self, root_dir, service_url, log_level=None):
  1562. self._all_packages = set()
  1563. self._mutator_lock = threading.Lock()
  1564. self._packages_by_subdir = collections.defaultdict(list)
  1565. self._root_dir = root_dir
  1566. self._service_url = service_url
  1567. self._resolved_packages = None
  1568. self._log_level = log_level or 'error'
  1569. def add_package(self, subdir, package, version):
  1570. """Adds a package to this CIPD root.
  1571. As far as clients are concerned, this grants both root and subdir authority
  1572. to packages arbitrarily. (The implementation grants root authority to the
  1573. first package added and subdir authority to the first package added for that
  1574. subdir, but clients should not depend on or expect that behavior.)
  1575. Args:
  1576. subdir: str; relative path to where the package should be installed from
  1577. the cipd root directory.
  1578. package: str; the cipd package name.
  1579. version: str; the cipd package version.
  1580. Returns:
  1581. CipdPackage; the package that was created and added to this root.
  1582. """
  1583. with self._mutator_lock:
  1584. cipd_package = CipdPackage(package, version,
  1585. not self._packages_by_subdir[subdir])
  1586. self._all_packages.add(cipd_package)
  1587. self._packages_by_subdir[subdir].append(cipd_package)
  1588. return cipd_package
  1589. def packages(self, subdir):
  1590. """Get the list of configured packages for the given subdir."""
  1591. return list(self._packages_by_subdir[subdir])
  1592. def resolved_packages(self):
  1593. if not self._resolved_packages:
  1594. self._resolved_packages = self.ensure_file_resolve()
  1595. return self._resolved_packages
  1596. def clobber(self):
  1597. """Remove the .cipd directory.
  1598. This is useful for forcing ensure to redownload and reinitialize all
  1599. packages.
  1600. """
  1601. with self._mutator_lock:
  1602. cipd_cache_dir = os.path.join(self.root_dir, '.cipd')
  1603. try:
  1604. gclient_utils.rmtree(os.path.join(cipd_cache_dir))
  1605. except OSError:
  1606. if os.path.exists(cipd_cache_dir):
  1607. raise
  1608. def expand_package_name(self, package_name_string, **kwargs):
  1609. """Run `cipd expand-package-name`.
  1610. CIPD package names can be declared with placeholder variables
  1611. such as '${platform}', this cmd will return the package name
  1612. with the variables resolved. The resolution is based on the host
  1613. the command is executing on.
  1614. """
  1615. kwargs.setdefault('stderr', subprocess2.PIPE)
  1616. cmd = ['cipd', 'expand-package-name', package_name_string]
  1617. ret = subprocess2.check_output(cmd, **kwargs).decode('utf-8')
  1618. return ret.strip()
  1619. @contextlib.contextmanager
  1620. def _create_ensure_file(self):
  1621. try:
  1622. contents = '$ParanoidMode CheckPresence\n'
  1623. # TODO(crbug/1329641): Remove once cipd packages have been updated
  1624. # to always be created in copy mode.
  1625. contents += '$OverrideInstallMode copy\n\n'
  1626. for subdir, packages in sorted(self._packages_by_subdir.items()):
  1627. contents += '@Subdir %s\n' % subdir
  1628. for package in sorted(packages, key=lambda p: p.name):
  1629. contents += '%s %s\n' % (package.name, package.version)
  1630. contents += '\n'
  1631. ensure_file = None
  1632. with tempfile.NamedTemporaryFile(suffix='.ensure',
  1633. delete=False,
  1634. mode='wb') as ensure_file:
  1635. ensure_file.write(contents.encode('utf-8', 'replace'))
  1636. yield ensure_file.name
  1637. finally:
  1638. if ensure_file is not None and os.path.exists(ensure_file.name):
  1639. os.remove(ensure_file.name)
  1640. def ensure(self):
  1641. """Run `cipd ensure`."""
  1642. with self._mutator_lock:
  1643. with self._create_ensure_file() as ensure_file:
  1644. cmd = [
  1645. 'cipd',
  1646. 'ensure',
  1647. '-log-level',
  1648. self._log_level,
  1649. '-root',
  1650. self.root_dir,
  1651. '-ensure-file',
  1652. ensure_file,
  1653. ]
  1654. gclient_utils.CheckCallAndFilter(cmd,
  1655. print_stdout=True,
  1656. show_header=True)
  1657. @contextlib.contextmanager
  1658. def _create_ensure_file_for_resolve(self):
  1659. try:
  1660. contents = '$ResolvedVersions %s\n' % os.devnull
  1661. for subdir, packages in sorted(self._packages_by_subdir.items()):
  1662. contents += '@Subdir %s\n' % subdir
  1663. for package in sorted(packages, key=lambda p: p.name):
  1664. contents += '%s %s\n' % (package.name, package.version)
  1665. contents += '\n'
  1666. ensure_file = None
  1667. with tempfile.NamedTemporaryFile(suffix='.ensure',
  1668. delete=False,
  1669. mode='wb') as ensure_file:
  1670. ensure_file.write(contents.encode('utf-8', 'replace'))
  1671. yield ensure_file.name
  1672. finally:
  1673. if ensure_file is not None and os.path.exists(ensure_file.name):
  1674. os.remove(ensure_file.name)
  1675. def _create_resolved_file(self):
  1676. return tempfile.NamedTemporaryFile(suffix='.resolved',
  1677. delete=False,
  1678. mode='wb')
  1679. def ensure_file_resolve(self):
  1680. """Run `cipd ensure-file-resolve`."""
  1681. with self._mutator_lock:
  1682. with self._create_resolved_file() as output_file:
  1683. with self._create_ensure_file_for_resolve() as ensure_file:
  1684. cmd = [
  1685. 'cipd',
  1686. 'ensure-file-resolve',
  1687. '-log-level',
  1688. self._log_level,
  1689. '-ensure-file',
  1690. ensure_file,
  1691. '-json-output',
  1692. output_file.name,
  1693. ]
  1694. gclient_utils.CheckCallAndFilter(cmd,
  1695. print_stdout=False,
  1696. show_header=False)
  1697. with open(output_file.name) as f:
  1698. output_json = json.load(f)
  1699. return output_json.get('result', {})
  1700. def run(self, command):
  1701. if command == 'update':
  1702. self.ensure()
  1703. elif command == 'revert':
  1704. self.clobber()
  1705. self.ensure()
  1706. def created_package(self, package):
  1707. """Checks whether this root created the given package.
  1708. Args:
  1709. package: CipdPackage; the package to check.
  1710. Returns:
  1711. bool; whether this root created the given package.
  1712. """
  1713. return package in self._all_packages
  1714. @property
  1715. def root_dir(self):
  1716. return self._root_dir
  1717. @property
  1718. def service_url(self):
  1719. return self._service_url
  1720. class CipdWrapper(SCMWrapper):
  1721. """Wrapper for CIPD.
  1722. Currently only supports chrome-infra-packages.appspot.com.
  1723. """
  1724. name = 'cipd'
  1725. def __init__(self,
  1726. url=None,
  1727. root_dir=None,
  1728. relpath=None,
  1729. out_fh=None,
  1730. out_cb=None,
  1731. root=None,
  1732. package=None):
  1733. super(CipdWrapper, self).__init__(url=url,
  1734. root_dir=root_dir,
  1735. relpath=relpath,
  1736. out_fh=out_fh,
  1737. out_cb=out_cb)
  1738. assert root.created_package(package)
  1739. self._package = package
  1740. self._root = root
  1741. #override
  1742. def GetCacheMirror(self):
  1743. return None
  1744. #override
  1745. def GetActualRemoteURL(self, options):
  1746. return self._root.service_url
  1747. #override
  1748. def DoesRemoteURLMatch(self, options):
  1749. del options
  1750. return True
  1751. def revert(self, options, args, file_list):
  1752. """Does nothing.
  1753. CIPD packages should be reverted at the root by running
  1754. `CipdRoot.run('revert')`.
  1755. """
  1756. def diff(self, options, args, file_list):
  1757. """CIPD has no notion of diffing."""
  1758. def pack(self, options, args, file_list):
  1759. """CIPD has no notion of diffing."""
  1760. def revinfo(self, options, args, file_list):
  1761. """Grab the instance ID."""
  1762. try:
  1763. tmpdir = tempfile.mkdtemp()
  1764. # Attempt to get instance_id from the root resolved cache.
  1765. # Resolved cache will not match on any CIPD packages with
  1766. # variables such as ${platform}, they will fall back to
  1767. # the slower method below.
  1768. resolved = self._root.resolved_packages()
  1769. if resolved:
  1770. # CIPD uses POSIX separators across all platforms, so
  1771. # replace any Windows separators.
  1772. path_split = self.relpath.replace(os.sep, "/").split(":")
  1773. if len(path_split) > 1:
  1774. src_path, package = path_split
  1775. if src_path in resolved:
  1776. for resolved_package in resolved[src_path]:
  1777. if package == resolved_package.get(
  1778. 'pin', {}).get('package'):
  1779. return resolved_package.get(
  1780. 'pin', {}).get('instance_id')
  1781. describe_json_path = os.path.join(tmpdir, 'describe.json')
  1782. cmd = [
  1783. 'cipd', 'describe', self._package.name, '-log-level', 'error',
  1784. '-version', self._package.version, '-json-output',
  1785. describe_json_path
  1786. ]
  1787. gclient_utils.CheckCallAndFilter(cmd)
  1788. with open(describe_json_path) as f:
  1789. describe_json = json.load(f)
  1790. return describe_json.get('result', {}).get('pin',
  1791. {}).get('instance_id')
  1792. finally:
  1793. gclient_utils.rmtree(tmpdir)
  1794. def status(self, options, args, file_list):
  1795. pass
  1796. def update(self, options, args, file_list):
  1797. """Does nothing.
  1798. CIPD packages should be updated at the root by running
  1799. `CipdRoot.run('update')`.
  1800. """
  1801. class GcsRoot(object):
  1802. """Root to keep track of all GCS objects, per checkout"""
  1803. def __init__(self, root_dir):
  1804. self._mutator_lock = threading.Lock()
  1805. self._root_dir = root_dir
  1806. # Populated when the DEPS file is parsed
  1807. # The objects here have not yet been downloaded and written into
  1808. # the .gcs_entries file
  1809. self._parsed_objects = {}
  1810. # .gcs_entries keeps track of which GCS deps have already been installed
  1811. # Maps checkout_name -> {GCS dep path -> [object_name]}
  1812. # This file is in the same directory as .gclient
  1813. self._gcs_entries_file = os.path.join(self._root_dir, '.gcs_entries')
  1814. # Contents of the .gcs_entries file
  1815. self._gcs_entries = self.read_gcs_entries()
  1816. @property
  1817. def root_dir(self):
  1818. return self._root_dir
  1819. def add_object(self, checkout_name, dep_path, object_name):
  1820. """Records the object in the _parsed_objects variable
  1821. This does not actually download the object"""
  1822. with self._mutator_lock:
  1823. if checkout_name not in self._parsed_objects:
  1824. self._parsed_objects[checkout_name] = {}
  1825. if dep_path not in self._parsed_objects[checkout_name]:
  1826. self._parsed_objects[checkout_name][dep_path] = [object_name]
  1827. else:
  1828. self._parsed_objects[checkout_name][dep_path].append(
  1829. object_name)
  1830. def read_gcs_entries(self):
  1831. """Reads .gcs_entries file and loads the content into _gcs_entries"""
  1832. if not os.path.exists(self._gcs_entries_file):
  1833. return {}
  1834. with open(self._gcs_entries_file, 'r') as f:
  1835. content = f.read().rstrip()
  1836. if content:
  1837. return json.loads(content)
  1838. return {}
  1839. def resolve_objects(self, checkout_name):
  1840. """Updates .gcs_entries with objects in _parsed_objects
  1841. This should only be called after the objects have been downloaded
  1842. and extracted."""
  1843. with self._mutator_lock:
  1844. object_dict = self._parsed_objects.get(checkout_name)
  1845. if not object_dict:
  1846. return
  1847. self._gcs_entries[checkout_name] = object_dict
  1848. with open(self._gcs_entries_file, 'w') as f:
  1849. f.write(json.dumps(self._gcs_entries, indent=2))
  1850. self._parsed_objects[checkout_name] = {}
  1851. def clobber_deps_with_updated_objects(self, checkout_name):
  1852. """Clobber the path if an object or GCS dependency is removed/added
  1853. This must be called before the GCS dependencies are
  1854. downloaded and extracted."""
  1855. with self._mutator_lock:
  1856. parsed_object_dict = self._parsed_objects.get(checkout_name, {})
  1857. parsed_paths = set(parsed_object_dict.keys())
  1858. resolved_object_dict = self._gcs_entries.get(checkout_name, {})
  1859. resolved_paths = set(resolved_object_dict.keys())
  1860. # If any GCS deps are added or removed entirely, clobber that path
  1861. intersected_paths = parsed_paths.intersection(resolved_paths)
  1862. # If any objects within a GCS dep are added/removed, clobber its
  1863. # extracted contents and relevant gcs dotfiles
  1864. for path in intersected_paths:
  1865. resolved_objects = resolved_object_dict[path]
  1866. parsed_objects = parsed_object_dict[path]
  1867. full_path = os.path.join(self.root_dir, path)
  1868. if (len(resolved_objects) != len(parsed_objects)
  1869. and os.path.exists(full_path)):
  1870. self.clobber_tar_content_names(full_path)
  1871. self.clobber_hash_files(full_path)
  1872. self.clobber_migration_files(full_path)
  1873. def clobber_tar_content_names(self, entry_directory):
  1874. """Delete paths written in .*_content_names files"""
  1875. content_names_files = glob.glob(
  1876. os.path.join(entry_directory, '.*_content_names'))
  1877. for file in content_names_files:
  1878. with open(file, 'r') as f:
  1879. names = json.loads(f.read().strip())
  1880. for name in names:
  1881. name_path = os.path.join(entry_directory, name)
  1882. if os.path.isdir(
  1883. name_path) or not os.path.exists(name_path):
  1884. continue
  1885. os.remove(os.path.join(entry_directory, name))
  1886. os.remove(file)
  1887. def clobber_hash_files(self, entry_directory):
  1888. files = glob.glob(os.path.join(entry_directory, '.*_hash'))
  1889. for f in files:
  1890. os.remove(f)
  1891. def clobber_migration_files(self, entry_directory):
  1892. files = glob.glob(os.path.join(entry_directory,
  1893. '.*_is_first_class_gcs'))
  1894. for f in files:
  1895. os.remove(f)
  1896. def clobber(self):
  1897. """Remove all dep path gcs items and clear .gcs_entries"""
  1898. for _, objects_dict in self._gcs_entries.items():
  1899. for dep_path, _ in objects_dict.items():
  1900. full_path = os.path.join(self.root_dir, dep_path)
  1901. self.clobber_tar_content_names(full_path)
  1902. self.clobber_hash_files(full_path)
  1903. self.clobber_migration_files(full_path)
  1904. if os.path.exists(self._gcs_entries_file):
  1905. os.remove(self._gcs_entries_file)
  1906. with self._mutator_lock:
  1907. self._gcs_entries = {}
  1908. class GcsWrapper(SCMWrapper):
  1909. """Wrapper for GCS.
  1910. Currently only supports content from Google Cloud Storage.
  1911. """
  1912. name = 'gcs'
  1913. def __init__(self,
  1914. url=None,
  1915. root_dir=None,
  1916. relpath=None,
  1917. out_fh=None,
  1918. out_cb=None):
  1919. super(GcsWrapper, self).__init__(url=url,
  1920. root_dir=root_dir,
  1921. relpath=relpath,
  1922. out_fh=out_fh,
  1923. out_cb=out_cb)
  1924. #override
  1925. def GetCacheMirror(self):
  1926. return None
  1927. #override
  1928. def GetActualRemoteURL(self, options):
  1929. return None
  1930. #override
  1931. def DoesRemoteURLMatch(self, options):
  1932. del options
  1933. return True
  1934. def revert(self, options, args, file_list):
  1935. """Does nothing."""
  1936. def diff(self, options, args, file_list):
  1937. """GCS has no notion of diffing."""
  1938. def pack(self, options, args, file_list):
  1939. """GCS has no notion of diffing."""
  1940. def revinfo(self, options, args, file_list):
  1941. """Does nothing"""
  1942. def status(self, options, args, file_list):
  1943. pass
  1944. def update(self, options, args, file_list):
  1945. """Does nothing."""
  1946. class CogWrapper(SCMWrapper):
  1947. """Wrapper for Cog, all no-op."""
  1948. name = 'cog'
  1949. def __init__(self):
  1950. super(CogWrapper, self).__init__()
  1951. #override
  1952. def GetCacheMirror(self):
  1953. return None
  1954. #override
  1955. def GetActualRemoteURL(self, options):
  1956. return None
  1957. #override
  1958. def GetSubmoduleDiff(self):
  1959. return None
  1960. #override
  1961. def GetSubmoduleStateFromIndex(self):
  1962. return None
  1963. #override
  1964. def DoesRemoteURLMatch(self, options):
  1965. del options
  1966. return True
  1967. def revert(self, options, args, file_list):
  1968. pass
  1969. def diff(self, options, args, file_list):
  1970. pass
  1971. def pack(self, options, args, file_list):
  1972. pass
  1973. def revinfo(self, options, args, file_list):
  1974. pass
  1975. def status(self, options, args, file_list):
  1976. pass
  1977. def update(self, options, args, file_list):
  1978. pass