gclient_scm.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  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. if scm.GIT.GetConfig(args[0].checkout_path,
  592. 'diff.ignoresubmodules') != 'dirty':
  593. config_updates.append(('diff.ignoreSubmodules', 'dirty'))
  594. if scm.GIT.GetConfig(args[0].checkout_path,
  595. 'fetch.recursesubmodules') != 'off':
  596. config_updates.append(('fetch.recurseSubmodules', 'off'))
  597. if scm.GIT.GetConfig(args[0].checkout_path,
  598. 'push.recursesubmodules') != 'off':
  599. # The default is off, but if user sets submodules.recurse to
  600. # on, this becomes on too. We never want to push submodules
  601. # for gclient managed repositories. Push, even if a no-op,
  602. # will increase `git cl upload` latency.
  603. config_updates.append(('push.recurseSubmodules', 'off'))
  604. for update in config_updates:
  605. scm.GIT.SetConfig(args[0].checkout_path,
  606. update[0],
  607. update[1],
  608. modify_all=True)
  609. return return_val
  610. return wrapper
  611. @set_config
  612. def update(self, options, args, file_list):
  613. """Runs git to update or transparently checkout the working copy.
  614. All updated files will be appended to file_list.
  615. Raises:
  616. Error: if can't get URL for relative path.
  617. """
  618. if args:
  619. raise gclient_utils.Error("Unsupported argument(s): %s" %
  620. ",".join(args))
  621. url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
  622. revision = deps_revision
  623. managed = True
  624. if options.revision:
  625. # Override the revision number.
  626. revision = str(options.revision)
  627. if revision == 'unmanaged':
  628. # Check again for a revision in case an initial ref was specified
  629. # in the url, for example bla.git@refs/heads/custombranch
  630. revision = deps_revision
  631. managed = False
  632. if not revision:
  633. # If a dependency is not pinned, track the default remote branch.
  634. revision = scm.GIT.GetRemoteHeadRef(self.checkout_path, self.url,
  635. self.remote)
  636. if revision.startswith('origin/'):
  637. revision = 'refs/remotes/' + revision
  638. if managed and platform.system() == 'Windows':
  639. self._DisableHooks()
  640. printed_path = False
  641. verbose = []
  642. if options.verbose:
  643. self.Print('_____ %s at %s' % (self.relpath, revision),
  644. timestamp=False)
  645. verbose = ['--verbose']
  646. printed_path = True
  647. revision_ref = revision
  648. if ':' in revision:
  649. revision_ref, _, revision = revision.partition(':')
  650. if revision_ref.startswith('refs/branch-heads'):
  651. options.with_branch_heads = True
  652. mirror = self._GetMirror(url, options, revision, revision_ref)
  653. if mirror:
  654. url = mirror.mirror_path
  655. remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
  656. if remote_ref:
  657. # Rewrite remote refs to their local equivalents.
  658. revision = ''.join(remote_ref)
  659. rev_type = "branch"
  660. elif revision.startswith('refs/'):
  661. # Local branch? We probably don't want to support, since DEPS should
  662. # always specify branches as they are in the upstream repo.
  663. rev_type = "branch"
  664. else:
  665. # hash is also a tag, only make a distinction at checkout
  666. rev_type = "hash"
  667. # If we are going to introduce a new project, there is a possibility
  668. # that we are syncing back to a state where the project was originally a
  669. # sub-project rolled by DEPS (realistic case: crossing the Blink merge
  670. # point syncing backwards, when Blink was a DEPS entry and not part of
  671. # src.git). In such case, we might have a backup of the former .git
  672. # folder, which can be used to avoid re-fetching the entire repo again
  673. # (useful for bisects).
  674. backup_dir = self.GetGitBackupDirPath()
  675. target_dir = os.path.join(self.checkout_path, '.git')
  676. if os.path.exists(backup_dir) and not os.path.exists(target_dir):
  677. gclient_utils.safe_makedirs(self.checkout_path)
  678. os.rename(backup_dir, target_dir)
  679. # Reset to a clean state
  680. self._Scrub('HEAD', options)
  681. if (not os.path.exists(self.checkout_path) or
  682. (os.path.isdir(self.checkout_path)
  683. and not os.path.exists(os.path.join(self.checkout_path, '.git')))):
  684. if mirror:
  685. self._UpdateMirrorIfNotContains(mirror, options, rev_type,
  686. revision)
  687. try:
  688. self.current_revision = self._Clone(revision, url, options)
  689. except subprocess2.CalledProcessError as e:
  690. logging.warning('Clone failed due to: %s', e)
  691. self._DeleteOrMove(options.force)
  692. self.current_revision = self._Clone(revision, url, options)
  693. if file_list is not None:
  694. files = self._Capture(
  695. ['-c', 'core.quotePath=false', 'ls-files']).splitlines()
  696. file_list.extend(
  697. [os.path.join(self.checkout_path, f) for f in files])
  698. if mirror:
  699. self._Capture(
  700. ['remote', 'set-url', '--push', 'origin', mirror.url])
  701. if not verbose:
  702. # Make the output a little prettier. It's nice to have some
  703. # whitespace between projects when cloning.
  704. self.Print('')
  705. return self._Capture(['rev-parse', '--verify', 'HEAD'])
  706. if mirror:
  707. self._Capture(['remote', 'set-url', '--push', 'origin', mirror.url])
  708. if not managed:
  709. self._SetFetchConfig(options)
  710. self.Print('________ unmanaged solution; skipping %s' %
  711. self.relpath)
  712. return self._Capture(['rev-parse', '--verify', 'HEAD'])
  713. # Special case for rev_type = hash. If we use submodules, we can check
  714. # information already.
  715. if rev_type == 'hash':
  716. if self.current_revision == revision:
  717. if verbose:
  718. self.Print('Using submodule information to skip check')
  719. if options.reset or options.force:
  720. self._Scrub('HEAD', options)
  721. return revision
  722. self._maybe_break_locks(options)
  723. if mirror:
  724. self._UpdateMirrorIfNotContains(mirror, options, rev_type, revision)
  725. # See if the url has changed (the unittests use git://foo for the url,
  726. # let that through).
  727. current_url = scm.GIT.GetConfig(self.checkout_path,
  728. f'remote.{self.remote}.url')
  729. return_early = False
  730. # TODO(maruel): Delete url != 'git://foo' since it's just to make the
  731. # unit test pass. (and update the comment above)
  732. strp_url = url[:-4] if url.endswith('.git') else url
  733. strp_current_url = current_url[:-4] if current_url.endswith(
  734. '.git') else current_url
  735. if (strp_current_url.rstrip('/') != strp_url.rstrip('/')
  736. and url != 'git://foo'):
  737. self.Print('_____ switching %s from %s to new upstream %s' %
  738. (self.relpath, current_url, url))
  739. if not (options.force or options.reset):
  740. # Make sure it's clean
  741. self._CheckClean(revision)
  742. # Switch over to the new upstream
  743. self._Run(['remote', 'set-url', self.remote, url], options)
  744. if mirror:
  745. if git_cache.Mirror.CacheDirToUrl(current_url.rstrip(
  746. '/')) == git_cache.Mirror.CacheDirToUrl(
  747. url.rstrip('/')):
  748. # Reset alternates when the cache dir is updated.
  749. with open(
  750. os.path.join(self.checkout_path, '.git', 'objects',
  751. 'info', 'alternates'), 'w') as fh:
  752. fh.write(os.path.join(url, 'objects'))
  753. else:
  754. # Because we use Git alternatives, our existing repository
  755. # is not self-contained. It's possible that new git
  756. # alternative doesn't have all necessary objects that the
  757. # current repository needs. Instead of blindly hoping that
  758. # new alternative contains all necessary objects, keep the
  759. # old alternative and just append a new one on top of it.
  760. with open(
  761. os.path.join(self.checkout_path, '.git', 'objects',
  762. 'info', 'alternates'), 'a') as fh:
  763. fh.write("\n" + os.path.join(url, 'objects'))
  764. current_revision = self._EnsureValidHeadObjectOrCheckout(
  765. revision, options, url)
  766. self._FetchAndReset(revision, file_list, options)
  767. return_early = True
  768. else:
  769. current_revision = self._EnsureValidHeadObjectOrCheckout(
  770. revision, options, url)
  771. if return_early:
  772. return current_revision or self._Capture(
  773. ['rev-parse', '--verify', 'HEAD'])
  774. cur_branch = self._GetCurrentBranch()
  775. # Cases:
  776. # 0) HEAD is detached. Probably from our initial clone.
  777. # - make sure HEAD is contained by a named ref, then update.
  778. # Cases 1-4. HEAD is a branch.
  779. # 1) current branch is not tracking a remote branch
  780. # - try to rebase onto the new hash or branch
  781. # 2) current branch is tracking a remote branch with local committed
  782. # changes, but the DEPS file switched to point to a hash
  783. # - rebase those changes on top of the hash
  784. # 3) current branch is tracking a remote branch w/or w/out changes, and
  785. # no DEPS switch
  786. # - see if we can FF, if not, prompt the user for rebase, merge, or stop
  787. # 4) current branch is tracking a remote branch, but DEPS switches to a
  788. # different remote branch, and a) current branch has no local changes,
  789. # and --force: - checkout new branch b) current branch has local
  790. # changes, and --force and --reset: - checkout new branch c) otherwise
  791. # exit
  792. # GetUpstreamBranch returns something like 'refs/remotes/origin/main'
  793. # for a tracking branch or 'main' if not a tracking branch (it's based
  794. # on a specific rev/hash) or it returns None if it couldn't find an
  795. # upstream
  796. if cur_branch is None:
  797. upstream_branch = None
  798. current_type = "detached"
  799. logging.debug("Detached HEAD")
  800. else:
  801. upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
  802. if not upstream_branch or not upstream_branch.startswith(
  803. 'refs/remotes'):
  804. current_type = "hash"
  805. logging.debug(
  806. "Current branch is not tracking an upstream (remote)"
  807. " branch.")
  808. elif upstream_branch.startswith('refs/remotes'):
  809. current_type = "branch"
  810. else:
  811. raise gclient_utils.Error('Invalid Upstream: %s' %
  812. upstream_branch)
  813. self._SetFetchConfig(options)
  814. # Fetch upstream if we don't already have |revision|.
  815. if not scm.GIT.IsValidRevision(
  816. self.checkout_path, revision, sha_only=True):
  817. self._Fetch(options, prune=options.force)
  818. if not scm.GIT.IsValidRevision(
  819. self.checkout_path, revision, sha_only=True):
  820. # Update the remotes first so we have all the refs.
  821. remote_output = scm.GIT.Capture(['remote'] + verbose +
  822. ['update'],
  823. cwd=self.checkout_path)
  824. if verbose:
  825. self.Print(remote_output)
  826. revision = self._AutoFetchRef(options, revision)
  827. # This is a big hammer, debatable if it should even be here...
  828. if options.force or options.reset:
  829. target = 'HEAD'
  830. if options.upstream and upstream_branch:
  831. target = upstream_branch
  832. self._Scrub(target, options)
  833. if current_type == 'detached':
  834. # case 0
  835. # We just did a Scrub, this is as clean as it's going to get. In
  836. # particular if HEAD is a commit that contains two versions of the
  837. # same file on a case-insensitive filesystem (e.g. 'a' and 'A'),
  838. # there's no way to actually "Clean" the checkout; that commit is
  839. # uncheckoutable on this system. The best we can do is carry forward
  840. # to the checkout step.
  841. if not (options.force or options.reset):
  842. self._CheckClean(revision)
  843. self._CheckDetachedHead(revision, options)
  844. if not current_revision:
  845. current_revision = self._Capture(
  846. ['rev-list', '-n', '1', 'HEAD'])
  847. if current_revision == revision:
  848. self.Print('Up-to-date; skipping checkout.')
  849. else:
  850. # 'git checkout' may need to overwrite existing untracked files.
  851. # Allow it only when nuclear options are enabled.
  852. self._Checkout(
  853. options,
  854. revision,
  855. force=(options.force and options.delete_unversioned_trees),
  856. quiet=True,
  857. )
  858. if not printed_path:
  859. self.Print('_____ %s at %s' % (self.relpath, revision),
  860. timestamp=False)
  861. elif current_type == 'hash':
  862. # case 1
  863. # Can't find a merge-base since we don't know our upstream. That
  864. # makes this command VERY likely to produce a rebase failure. For
  865. # now we assume origin is our upstream since that's what the old
  866. # behavior was.
  867. upstream_branch = self.remote
  868. if options.revision or deps_revision:
  869. upstream_branch = revision
  870. self._AttemptRebase(upstream_branch,
  871. file_list,
  872. options,
  873. printed_path=printed_path,
  874. merge=options.merge)
  875. printed_path = True
  876. elif rev_type == 'hash':
  877. # case 2
  878. self._AttemptRebase(upstream_branch,
  879. file_list,
  880. options,
  881. newbase=revision,
  882. printed_path=printed_path,
  883. merge=options.merge)
  884. printed_path = True
  885. elif remote_ref and ''.join(remote_ref) != upstream_branch:
  886. # case 4
  887. new_base = ''.join(remote_ref)
  888. if not printed_path:
  889. self.Print('_____ %s at %s' % (self.relpath, revision),
  890. timestamp=False)
  891. switch_error = (
  892. "Could not switch upstream branch from %s to %s\n" %
  893. (upstream_branch, new_base) +
  894. "Please use --force or merge or rebase manually:\n" +
  895. "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
  896. "OR git checkout -b <some new branch> %s" % new_base)
  897. force_switch = False
  898. if options.force:
  899. try:
  900. self._CheckClean(revision)
  901. # case 4a
  902. force_switch = True
  903. except gclient_utils.Error as e:
  904. if options.reset:
  905. # case 4b
  906. force_switch = True
  907. else:
  908. switch_error = '%s\n%s' % (str(e), switch_error)
  909. if force_switch:
  910. self.Print("Switching upstream branch from %s to %s" %
  911. (upstream_branch, new_base))
  912. switch_branch = 'gclient_' + remote_ref[1]
  913. self._Capture(['branch', '-f', switch_branch, new_base])
  914. self._Checkout(options, switch_branch, force=True, quiet=True)
  915. else:
  916. # case 4c
  917. raise gclient_utils.Error(switch_error)
  918. else:
  919. # case 3 - the default case
  920. rebase_files = self._GetDiffFilenames(upstream_branch)
  921. if verbose:
  922. self.Print('Trying fast-forward merge to branch : %s' %
  923. upstream_branch)
  924. try:
  925. merge_args = ['merge']
  926. if options.merge:
  927. merge_args.append('--ff')
  928. else:
  929. merge_args.append('--ff-only')
  930. merge_args.append(upstream_branch)
  931. merge_output = self._Capture(merge_args)
  932. except subprocess2.CalledProcessError as e:
  933. rebase_files = []
  934. if re.search(b'fatal: Not possible to fast-forward, aborting.',
  935. e.stderr):
  936. if not printed_path:
  937. self.Print('_____ %s at %s' % (self.relpath, revision),
  938. timestamp=False)
  939. printed_path = True
  940. while True:
  941. if not options.auto_rebase:
  942. try:
  943. action = self._AskForData(
  944. 'Cannot %s, attempt to rebase? '
  945. '(y)es / (q)uit / (s)kip : ' %
  946. ('merge' if options.merge else
  947. 'fast-forward merge'), options)
  948. except ValueError:
  949. raise gclient_utils.Error('Invalid Character')
  950. if options.auto_rebase or re.match(
  951. r'yes|y', action, re.I):
  952. self._AttemptRebase(upstream_branch,
  953. rebase_files,
  954. options,
  955. printed_path=printed_path,
  956. merge=False)
  957. printed_path = True
  958. break
  959. if re.match(r'quit|q', action, re.I):
  960. raise gclient_utils.Error(
  961. "Can't fast-forward, please merge or "
  962. "rebase manually.\n"
  963. "cd %s && git " % self.checkout_path +
  964. "rebase %s" % upstream_branch)
  965. if re.match(r'skip|s', action, re.I):
  966. self.Print('Skipping %s' % self.relpath)
  967. return
  968. self.Print('Input not recognized')
  969. elif re.match(
  970. b"error: Your local changes to '.*' would be "
  971. b"overwritten by merge. Aborting.\nPlease, commit your "
  972. b"changes or stash them before you can merge.\n",
  973. e.stderr):
  974. if not printed_path:
  975. self.Print('_____ %s at %s' % (self.relpath, revision),
  976. timestamp=False)
  977. printed_path = True
  978. raise gclient_utils.Error(e.stderr.decode('utf-8'))
  979. else:
  980. # Some other problem happened with the merge
  981. logging.error("Error during fast-forward merge in %s!" %
  982. self.relpath)
  983. self.Print(e.stderr.decode('utf-8'))
  984. raise
  985. else:
  986. # Fast-forward merge was successful
  987. if not re.match('Already up-to-date.', merge_output) or verbose:
  988. if not printed_path:
  989. self.Print('_____ %s at %s' % (self.relpath, revision),
  990. timestamp=False)
  991. printed_path = True
  992. self.Print(merge_output.strip())
  993. if not verbose:
  994. # Make the output a little prettier. It's nice to have
  995. # some whitespace between projects when syncing.
  996. self.Print('')
  997. if file_list is not None:
  998. file_list.extend(
  999. [os.path.join(self.checkout_path, f) for f in rebase_files])
  1000. # If the rebase generated a conflict, abort and ask user to fix
  1001. if self._IsRebasing():
  1002. raise gclient_utils.Error(
  1003. '\n____ %s at %s\n'
  1004. '\nConflict while rebasing this branch.\n'
  1005. 'Fix the conflict and run gclient again.\n'
  1006. 'See man git-rebase for details.\n' % (self.relpath, revision))
  1007. # If --reset and --delete_unversioned_trees are specified, remove any
  1008. # untracked directories.
  1009. if options.reset and options.delete_unversioned_trees:
  1010. # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1
  1011. # (the merge-base by default), so doesn't include untracked files.
  1012. # So we use 'git ls-files --directory --others --exclude-standard'
  1013. # here directly.
  1014. paths = scm.GIT.Capture([
  1015. '-c', 'core.quotePath=false', 'ls-files', '--directory',
  1016. '--others', '--exclude-standard'
  1017. ], self.checkout_path)
  1018. for path in (p for p in paths.splitlines() if p.endswith('/')):
  1019. full_path = os.path.join(self.checkout_path, path)
  1020. if not os.path.islink(full_path):
  1021. self.Print('_____ removing unversioned directory %s' % path)
  1022. gclient_utils.rmtree(full_path)
  1023. if not current_revision:
  1024. current_revision = self._Capture(['rev-parse', '--verify', 'HEAD'])
  1025. if verbose:
  1026. self.Print(f'Checked out revision {current_revision}',
  1027. timestamp=False)
  1028. return current_revision
  1029. def revert(self, options, _args, file_list):
  1030. """Reverts local modifications.
  1031. All reverted files will be appended to file_list.
  1032. """
  1033. if not os.path.isdir(self.checkout_path):
  1034. # revert won't work if the directory doesn't exist. It needs to
  1035. # checkout instead.
  1036. self.Print('_____ %s is missing, syncing instead' % self.relpath)
  1037. # Don't reuse the args.
  1038. return self.update(options, [], file_list)
  1039. default_rev = "refs/heads/main"
  1040. if options.upstream:
  1041. if self._GetCurrentBranch():
  1042. upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
  1043. default_rev = upstream_branch or default_rev
  1044. _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
  1045. if not deps_revision:
  1046. deps_revision = default_rev
  1047. if deps_revision.startswith('refs/heads/'):
  1048. deps_revision = deps_revision.replace('refs/heads/',
  1049. self.remote + '/')
  1050. try:
  1051. deps_revision = self.GetUsableRev(deps_revision, options)
  1052. except NoUsableRevError as e:
  1053. # If the DEPS entry's url and hash changed, try to update the
  1054. # origin. See also http://crbug.com/520067.
  1055. logging.warning(
  1056. "Couldn't find usable revision, will retrying to update instead: %s",
  1057. str(e))
  1058. return self.update(options, [], file_list)
  1059. if file_list is not None:
  1060. files = self._GetDiffFilenames(deps_revision)
  1061. self._Scrub(deps_revision, options)
  1062. self._Run(['clean', '-f', '-d'], options)
  1063. if file_list is not None:
  1064. file_list.extend(
  1065. [os.path.join(self.checkout_path, f) for f in files])
  1066. def revinfo(self, _options, _args, _file_list):
  1067. """Returns revision"""
  1068. return self._Capture(['rev-parse', 'HEAD'])
  1069. def runhooks(self, options, args, file_list):
  1070. self.status(options, args, file_list)
  1071. def status(self, options, _args, file_list):
  1072. """Display status information."""
  1073. if not os.path.isdir(self.checkout_path):
  1074. self.Print('________ couldn\'t run status in %s:\n'
  1075. 'The directory does not exist.' % self.checkout_path)
  1076. else:
  1077. merge_base = []
  1078. if self.url:
  1079. _, base_rev = gclient_utils.SplitUrlRevision(self.url)
  1080. if base_rev:
  1081. if base_rev.startswith('refs/'):
  1082. base_rev = self._ref_to_remote_ref(base_rev)
  1083. merge_base = [base_rev]
  1084. self._Run(['-c', 'core.quotePath=false', 'diff', '--name-status'] +
  1085. merge_base,
  1086. options,
  1087. always_show_header=options.verbose)
  1088. if file_list is not None:
  1089. files = self._GetDiffFilenames(
  1090. merge_base[0] if merge_base else None)
  1091. file_list.extend(
  1092. [os.path.join(self.checkout_path, f) for f in files])
  1093. def GetUsableRev(self, rev, options):
  1094. """Finds a useful revision for this repository."""
  1095. sha1 = None
  1096. if not os.path.isdir(self.checkout_path):
  1097. raise NoUsableRevError(
  1098. 'This is not a git repo, so we cannot get a usable rev.')
  1099. if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
  1100. sha1 = rev
  1101. else:
  1102. # May exist in origin, but we don't have it yet, so fetch and look
  1103. # again.
  1104. self._Fetch(options)
  1105. if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
  1106. sha1 = rev
  1107. if not sha1:
  1108. raise NoUsableRevError(
  1109. 'Hash %s does not appear to be a valid hash in this repo.' %
  1110. rev)
  1111. return sha1
  1112. def GetGitBackupDirPath(self):
  1113. """Returns the path where the .git folder for the current project can be
  1114. staged/restored. Use case: subproject moved from DEPS <-> outer project."""
  1115. return os.path.join(self._root_dir,
  1116. 'old_' + self.relpath.replace(os.sep, '_')) + '.git'
  1117. def _GetMirror(self, url, options, revision=None, revision_ref=None):
  1118. """Get a git_cache.Mirror object for the argument url."""
  1119. if not self.cache_dir:
  1120. return None
  1121. mirror_kwargs = {
  1122. 'print_func': self.filter,
  1123. 'refs': [],
  1124. 'commits': [],
  1125. }
  1126. if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
  1127. mirror_kwargs['refs'].append('refs/branch-heads/*')
  1128. elif revision_ref and revision_ref.startswith('refs/branch-heads/'):
  1129. mirror_kwargs['refs'].append(revision_ref)
  1130. if hasattr(options, 'with_tags') and options.with_tags:
  1131. mirror_kwargs['refs'].append('refs/tags/*')
  1132. elif revision_ref and revision_ref.startswith('refs/tags/'):
  1133. mirror_kwargs['refs'].append(revision_ref)
  1134. if revision and not revision.startswith('refs/'):
  1135. mirror_kwargs['commits'].append(revision)
  1136. return git_cache.Mirror(url, **mirror_kwargs)
  1137. def _UpdateMirrorIfNotContains(self, mirror, options, rev_type, revision):
  1138. """Update a git mirror by fetching the latest commits from the remote,
  1139. unless mirror already contains revision whose type is sha1 hash.
  1140. """
  1141. if rev_type == 'hash' and mirror.contains_revision(revision):
  1142. if options.verbose:
  1143. self.Print('skipping mirror update, it has rev=%s already' %
  1144. revision,
  1145. timestamp=False)
  1146. return
  1147. if getattr(options, 'shallow', False):
  1148. depth = 10000
  1149. else:
  1150. depth = None
  1151. mirror.populate(verbose=options.verbose,
  1152. bootstrap=not getattr(options, 'no_bootstrap', False),
  1153. depth=depth,
  1154. lock_timeout=getattr(options, 'lock_timeout', 0))
  1155. def _Clone(self, revision, url, options):
  1156. """Clone a git repository from the given URL.
  1157. Once we've cloned the repo, we checkout a working branch if the
  1158. specified revision is a branch head. If it is a tag or a specific
  1159. commit, then we leave HEAD detached as it makes future updates simpler
  1160. -- in this case the user should first create a new branch or switch to
  1161. an existing branch before making changes in the repo."""
  1162. if self.print_outbuf:
  1163. print_stdout = True
  1164. filter_fn = None
  1165. else:
  1166. print_stdout = False
  1167. filter_fn = self.filter
  1168. if not options.verbose:
  1169. # git clone doesn't seem to insert a newline properly before
  1170. # printing to stdout
  1171. self.Print('')
  1172. # If the parent directory does not exist, Git clone on Windows will not
  1173. # create it, so we need to do it manually.
  1174. parent_dir = os.path.dirname(self.checkout_path)
  1175. gclient_utils.safe_makedirs(parent_dir)
  1176. # Set up Git authentication configuration that is needed to clone/fetch the repo.
  1177. if newauth.Enabled():
  1178. git_auth.ConfigureGlobal('/', url)
  1179. if hasattr(options, 'no_history') and options.no_history:
  1180. self._Run(['init', self.checkout_path], options, cwd=self._root_dir)
  1181. self._Run(['remote', 'add', 'origin', url], options)
  1182. revision = self._AutoFetchRef(options, revision, depth=1)
  1183. remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
  1184. self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
  1185. else:
  1186. cfg = gclient_utils.DefaultIndexPackConfig(url)
  1187. clone_cmd = cfg + ['clone', '--no-checkout', '--progress']
  1188. if self.cache_dir:
  1189. clone_cmd.append('--shared')
  1190. if options.verbose:
  1191. clone_cmd.append('--verbose')
  1192. clone_cmd.append(url)
  1193. tmp_dir = tempfile.mkdtemp(prefix='_gclient_%s_' %
  1194. os.path.basename(self.checkout_path),
  1195. dir=parent_dir)
  1196. clone_cmd.append(tmp_dir)
  1197. try:
  1198. self._Run(clone_cmd,
  1199. options,
  1200. cwd=self._root_dir,
  1201. retry=True,
  1202. print_stdout=print_stdout,
  1203. filter_fn=filter_fn)
  1204. logging.debug(
  1205. 'Cloned into temporary dir, moving to checkout_path')
  1206. gclient_utils.safe_makedirs(self.checkout_path)
  1207. gclient_utils.safe_rename(
  1208. os.path.join(tmp_dir, '.git'),
  1209. os.path.join(self.checkout_path, '.git'))
  1210. except:
  1211. traceback.print_exc(file=self.out_fh)
  1212. raise
  1213. finally:
  1214. if os.listdir(tmp_dir):
  1215. self.Print('_____ removing non-empty tmp dir %s' % tmp_dir)
  1216. gclient_utils.rmtree(tmp_dir)
  1217. self._SetFetchConfig(options)
  1218. self._Fetch(options, prune=options.force)
  1219. revision = self._AutoFetchRef(options, revision)
  1220. remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
  1221. self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
  1222. if self._GetCurrentBranch() is None:
  1223. # Squelch git's very verbose detached HEAD warning and use our own
  1224. self.Print((
  1225. 'Checked out %s to a detached HEAD. Before making any commits\n'
  1226. 'in this repo, you should use \'git checkout <branch>\' to switch \n'
  1227. 'to an existing branch or use \'git checkout %s -b <branch>\' to\n'
  1228. 'create a new branch for your work.') % (revision, self.remote))
  1229. return revision
  1230. def _AskForData(self, prompt, options):
  1231. if options.jobs > 1:
  1232. self.Print(prompt)
  1233. raise gclient_utils.Error("Background task requires input. Rerun "
  1234. "gclient with --jobs=1 so that\n"
  1235. "interaction is possible.")
  1236. return gclient_utils.AskForData(prompt)
  1237. def _AttemptRebase(self,
  1238. upstream,
  1239. files,
  1240. options,
  1241. newbase=None,
  1242. branch=None,
  1243. printed_path=False,
  1244. merge=False):
  1245. """Attempt to rebase onto either upstream or, if specified, newbase."""
  1246. if files is not None:
  1247. files.extend(self._GetDiffFilenames(upstream))
  1248. revision = upstream
  1249. if newbase:
  1250. revision = newbase
  1251. action = 'merge' if merge else 'rebase'
  1252. if not printed_path:
  1253. self.Print('_____ %s : Attempting %s onto %s...' %
  1254. (self.relpath, action, revision))
  1255. printed_path = True
  1256. else:
  1257. self.Print('Attempting %s onto %s...' % (action, revision))
  1258. if merge:
  1259. merge_output = self._Capture(['merge', revision])
  1260. if options.verbose:
  1261. self.Print(merge_output)
  1262. return
  1263. # Build the rebase command here using the args
  1264. # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
  1265. rebase_cmd = ['rebase']
  1266. if options.verbose:
  1267. rebase_cmd.append('--verbose')
  1268. if newbase:
  1269. rebase_cmd.extend(['--onto', newbase])
  1270. rebase_cmd.append(upstream)
  1271. if branch:
  1272. rebase_cmd.append(branch)
  1273. try:
  1274. rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
  1275. except subprocess2.CalledProcessError as e:
  1276. if (re.match(
  1277. br'cannot rebase: you have unstaged changes', e.stderr
  1278. ) or re.match(
  1279. br'cannot rebase: your index contains uncommitted changes',
  1280. e.stderr)):
  1281. while True:
  1282. rebase_action = self._AskForData(
  1283. 'Cannot rebase because of unstaged changes.\n'
  1284. '\'git reset --hard HEAD\' ?\n'
  1285. 'WARNING: destroys any uncommitted work in your current branch!'
  1286. ' (y)es / (q)uit / (s)how : ', options)
  1287. if re.match(r'yes|y', rebase_action, re.I):
  1288. self._Scrub('HEAD', options)
  1289. # Should this be recursive?
  1290. rebase_output = scm.GIT.Capture(rebase_cmd,
  1291. cwd=self.checkout_path)
  1292. break
  1293. if re.match(r'quit|q', rebase_action, re.I):
  1294. raise gclient_utils.Error(
  1295. "Please merge or rebase manually\n"
  1296. "cd %s && git " % self.checkout_path +
  1297. "%s" % ' '.join(rebase_cmd))
  1298. if re.match(r'show|s', rebase_action, re.I):
  1299. self.Print('%s' % e.stderr.decode('utf-8').strip())
  1300. continue
  1301. gclient_utils.Error("Input not recognized")
  1302. continue
  1303. elif re.search(br'^CONFLICT', e.stdout, re.M):
  1304. raise gclient_utils.Error(
  1305. "Conflict while rebasing this branch.\n"
  1306. "Fix the conflict and run gclient again.\n"
  1307. "See 'man git-rebase' for details.\n")
  1308. else:
  1309. self.Print(e.stdout.decode('utf-8').strip())
  1310. self.Print('Rebase produced error output:\n%s' %
  1311. e.stderr.decode('utf-8').strip())
  1312. raise gclient_utils.Error(
  1313. "Unrecognized error, please merge or rebase "
  1314. "manually.\ncd %s && git " % self.checkout_path +
  1315. "%s" % ' '.join(rebase_cmd))
  1316. self.Print(rebase_output.strip())
  1317. if not options.verbose:
  1318. # Make the output a little prettier. It's nice to have some
  1319. # whitespace between projects when syncing.
  1320. self.Print('')
  1321. def _EnsureValidHeadObjectOrCheckout(self, revision, options, url):
  1322. # Special case handling if all 3 conditions are met:
  1323. # * the mirros have recently changed, but deps destination remains same,
  1324. # * the git histories of mirrors are conflicting. * git cache is used
  1325. # This manifests itself in current checkout having invalid HEAD commit
  1326. # on most git operations. Since git cache is used, just deleted the .git
  1327. # folder, and re-create it by cloning.
  1328. try:
  1329. return self._Capture(['rev-list', '-n', '1', 'HEAD'])
  1330. except subprocess2.CalledProcessError as e:
  1331. if (b'fatal: bad object HEAD' in e.stderr and self.cache_dir
  1332. and self.cache_dir in url):
  1333. self.Print(
  1334. ('Likely due to DEPS change with git cache_dir, '
  1335. 'the current commit points to no longer existing object.\n'
  1336. '%s' % e))
  1337. self._DeleteOrMove(options.force)
  1338. return self._Clone(revision, url, options)
  1339. raise
  1340. def _IsRebasing(self):
  1341. # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git
  1342. # doesn't have a plumbing command to determine whether a rebase is in
  1343. # progress, so for now emualate (more-or-less) git-rebase.sh /
  1344. # git-completion.bash
  1345. g = os.path.join(self.checkout_path, '.git')
  1346. return (os.path.isdir(os.path.join(g, "rebase-merge"))
  1347. or os.path.isdir(os.path.join(g, "rebase-apply")))
  1348. def _CheckClean(self, revision):
  1349. lockfile = os.path.join(self.checkout_path, ".git", "index.lock")
  1350. if os.path.exists(lockfile):
  1351. raise gclient_utils.Error(
  1352. '\n____ %s at %s\n'
  1353. '\tYour repo is locked, possibly due to a concurrent git process.\n'
  1354. '\tIf no git executable is running, then clean up %r and try again.\n'
  1355. % (self.relpath, revision, lockfile))
  1356. # Ensure that the tree is clean.
  1357. if scm.GIT.Capture([
  1358. 'status', '--porcelain', '--untracked-files=no',
  1359. '--ignore-submodules'
  1360. ],
  1361. cwd=self.checkout_path):
  1362. raise gclient_utils.Error(
  1363. '\n____ %s at %s\n'
  1364. '\tYou have uncommitted changes.\n'
  1365. '\tcd into %s, run git status to see changes,\n'
  1366. '\tand commit, stash, or reset.\n' %
  1367. (self.relpath, revision, self.relpath))
  1368. def _CheckDetachedHead(self, revision, _options):
  1369. # HEAD is detached. Make sure it is safe to move away from (i.e., it is
  1370. # reference by a commit). If not, error out -- most likely a rebase is
  1371. # in progress, try to detect so we can give a better error.
  1372. try:
  1373. scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
  1374. cwd=self.checkout_path)
  1375. except subprocess2.CalledProcessError:
  1376. # Commit is not contained by any rev. See if the user is rebasing:
  1377. if self._IsRebasing():
  1378. # Punt to the user
  1379. raise gclient_utils.Error(
  1380. '\n____ %s at %s\n'
  1381. '\tAlready in a conflict, i.e. (no branch).\n'
  1382. '\tFix the conflict and run gclient again.\n'
  1383. '\tOr to abort run:\n\t\tgit-rebase --abort\n'
  1384. '\tSee man git-rebase for details.\n' %
  1385. (self.relpath, revision))
  1386. # Let's just save off the commit so we can proceed.
  1387. name = ('saved-by-gclient-' +
  1388. self._Capture(['rev-parse', '--short', 'HEAD']))
  1389. self._Capture(['branch', '-f', name])
  1390. self.Print(
  1391. '_____ found an unreferenced commit and saved it as \'%s\'' %
  1392. name)
  1393. def _GetCurrentBranch(self):
  1394. # Returns name of current branch or None for detached HEAD
  1395. branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
  1396. if branch == 'HEAD':
  1397. return None
  1398. return branch
  1399. def _Capture(self, args, **kwargs):
  1400. set_git_dir = 'cwd' not in kwargs
  1401. kwargs.setdefault('cwd', self.checkout_path)
  1402. kwargs.setdefault('stderr', subprocess2.PIPE)
  1403. strip = kwargs.pop('strip', True)
  1404. env = scm.GIT.ApplyEnvVars(kwargs)
  1405. # If an explicit cwd isn't set, then default to the .git/ subdir so we
  1406. # get stricter behavior. This can be useful in cases of slight
  1407. # corruption -- we don't accidentally go corrupting parent git checks
  1408. # too. See https://crbug.com/1000825 for an example.
  1409. if set_git_dir:
  1410. env.setdefault(
  1411. 'GIT_DIR',
  1412. os.path.abspath(os.path.join(self.checkout_path, '.git')))
  1413. kwargs.setdefault('env', env)
  1414. ret = git_common.run(*args, **kwargs)
  1415. if strip:
  1416. ret = ret.strip()
  1417. self.Print('Finished running: %s %s' % ('git', ' '.join(args)))
  1418. return ret
  1419. def _Checkout(self, options, ref, force=False, quiet=None):
  1420. """Performs a 'git-checkout' operation.
  1421. Args:
  1422. options: The configured option set
  1423. ref: (str) The branch/commit to checkout
  1424. quiet: (bool/None) Whether or not the checkout should pass '--quiet'; if
  1425. 'None', the behavior is inferred from 'options.verbose'.
  1426. Returns: (str) The output of the checkout operation
  1427. """
  1428. if quiet is None:
  1429. quiet = (not options.verbose)
  1430. checkout_args = ['checkout']
  1431. if force:
  1432. checkout_args.append('--force')
  1433. if quiet:
  1434. checkout_args.append('--quiet')
  1435. checkout_args.append(ref)
  1436. return self._Capture(checkout_args)
  1437. def _Fetch(self,
  1438. options,
  1439. remote=None,
  1440. prune=False,
  1441. quiet=False,
  1442. refspec=None,
  1443. depth=None):
  1444. cfg = gclient_utils.DefaultIndexPackConfig(self.url)
  1445. # When updating, the ref is modified to be a remote ref .
  1446. # (e.g. refs/heads/NAME becomes refs/remotes/REMOTE/NAME).
  1447. # Try to reverse that mapping.
  1448. original_ref = scm.GIT.RemoteRefToRef(refspec, self.remote)
  1449. if original_ref:
  1450. refspec = original_ref + ':' + refspec
  1451. # When a mirror is configured, it only fetches
  1452. # refs/{heads,branch-heads,tags}/*.
  1453. # If asked to fetch other refs, we must fetch those directly from
  1454. # the repository, and not from the mirror.
  1455. if not original_ref.startswith(
  1456. ('refs/heads/', 'refs/branch-heads/', 'refs/tags/')):
  1457. remote, _ = gclient_utils.SplitUrlRevision(self.url)
  1458. fetch_cmd = cfg + [
  1459. 'fetch',
  1460. remote or self.remote,
  1461. ]
  1462. if refspec:
  1463. fetch_cmd.append(refspec)
  1464. if prune:
  1465. fetch_cmd.append('--prune')
  1466. if options.verbose:
  1467. fetch_cmd.append('--verbose')
  1468. if not hasattr(options, 'with_tags') or not options.with_tags:
  1469. fetch_cmd.append('--no-tags')
  1470. elif quiet:
  1471. fetch_cmd.append('--quiet')
  1472. if depth:
  1473. fetch_cmd.append('--depth=' + str(depth))
  1474. self._Run(fetch_cmd, options, show_header=options.verbose, retry=True)
  1475. def _SetFetchConfig(self, options):
  1476. """Adds, and optionally fetches, "branch-heads" and "tags" refspecs
  1477. if requested."""
  1478. if options.force or options.reset:
  1479. try:
  1480. scm.GIT.SetConfig(self.checkout_path,
  1481. f'remote.{self.remote}.fetch',
  1482. modify_all=True)
  1483. scm.GIT.SetConfig(
  1484. self.checkout_path, f'remote.{self.remote}.fetch',
  1485. f'+refs/heads/*:refs/remotes/{self.remote}/*')
  1486. except subprocess2.CalledProcessError as e:
  1487. # If exit code was 5, it means we attempted to unset a config
  1488. # that didn't exist. Ignore it.
  1489. if e.returncode != 5:
  1490. raise
  1491. if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
  1492. scm.GIT.SetConfig(
  1493. self.checkout_path,
  1494. f'remote.{self.remote}.fetch',
  1495. '+refs/branch-heads/*:refs/remotes/branch-heads/*',
  1496. value_pattern='^\\+refs/branch-heads/\\*:.*$',
  1497. modify_all=True)
  1498. if hasattr(options, 'with_tags') and options.with_tags:
  1499. scm.GIT.SetConfig(self.checkout_path,
  1500. f'remote.{self.remote}.fetch',
  1501. '+refs/tags/*:refs/tags/*',
  1502. value_pattern='^\\+refs/tags/\\*:.*$',
  1503. modify_all=True)
  1504. def _AutoFetchRef(self, options, revision, depth=None):
  1505. """Attempts to fetch |revision| if not available in local repo.
  1506. Returns possibly updated revision."""
  1507. if not scm.GIT.IsValidRevision(self.checkout_path, revision):
  1508. self._Fetch(options, refspec=revision, depth=depth)
  1509. revision = self._Capture(['rev-parse', 'FETCH_HEAD'])
  1510. return revision
  1511. def _Run(self, args, options, **kwargs):
  1512. # Disable 'unused options' warning | pylint: disable=unused-argument
  1513. kwargs.setdefault('cwd', self.checkout_path)
  1514. kwargs.setdefault('filter_fn', self.filter)
  1515. kwargs.setdefault('show_header', True)
  1516. env = scm.GIT.ApplyEnvVars(kwargs)
  1517. cmd = ['git'] + args
  1518. gclient_utils.CheckCallAndFilter(cmd, env=env, **kwargs)
  1519. class CipdPackage(object):
  1520. """A representation of a single CIPD package."""
  1521. def __init__(self, name, version, authority_for_subdir):
  1522. self._authority_for_subdir = authority_for_subdir
  1523. self._name = name
  1524. self._version = version
  1525. @property
  1526. def authority_for_subdir(self):
  1527. """Whether this package has authority to act on behalf of its subdir.
  1528. Some operations should only be performed once per subdirectory. A package
  1529. that has authority for its subdirectory is the only package that should
  1530. perform such operations.
  1531. Returns:
  1532. bool; whether this package has subdir authority.
  1533. """
  1534. return self._authority_for_subdir
  1535. @property
  1536. def name(self):
  1537. return self._name
  1538. @property
  1539. def version(self):
  1540. return self._version
  1541. class CipdRoot(object):
  1542. """A representation of a single CIPD root."""
  1543. def __init__(self, root_dir, service_url, log_level=None):
  1544. self._all_packages = set()
  1545. self._mutator_lock = threading.Lock()
  1546. self._packages_by_subdir = collections.defaultdict(list)
  1547. self._root_dir = root_dir
  1548. self._service_url = service_url
  1549. self._resolved_packages = None
  1550. self._log_level = log_level or 'error'
  1551. def add_package(self, subdir, package, version):
  1552. """Adds a package to this CIPD root.
  1553. As far as clients are concerned, this grants both root and subdir authority
  1554. to packages arbitrarily. (The implementation grants root authority to the
  1555. first package added and subdir authority to the first package added for that
  1556. subdir, but clients should not depend on or expect that behavior.)
  1557. Args:
  1558. subdir: str; relative path to where the package should be installed from
  1559. the cipd root directory.
  1560. package: str; the cipd package name.
  1561. version: str; the cipd package version.
  1562. Returns:
  1563. CipdPackage; the package that was created and added to this root.
  1564. """
  1565. with self._mutator_lock:
  1566. cipd_package = CipdPackage(package, version,
  1567. not self._packages_by_subdir[subdir])
  1568. self._all_packages.add(cipd_package)
  1569. self._packages_by_subdir[subdir].append(cipd_package)
  1570. return cipd_package
  1571. def packages(self, subdir):
  1572. """Get the list of configured packages for the given subdir."""
  1573. return list(self._packages_by_subdir[subdir])
  1574. def resolved_packages(self):
  1575. if not self._resolved_packages:
  1576. self._resolved_packages = self.ensure_file_resolve()
  1577. return self._resolved_packages
  1578. def clobber(self):
  1579. """Remove the .cipd directory.
  1580. This is useful for forcing ensure to redownload and reinitialize all
  1581. packages.
  1582. """
  1583. with self._mutator_lock:
  1584. cipd_cache_dir = os.path.join(self.root_dir, '.cipd')
  1585. try:
  1586. gclient_utils.rmtree(os.path.join(cipd_cache_dir))
  1587. except OSError:
  1588. if os.path.exists(cipd_cache_dir):
  1589. raise
  1590. def expand_package_name(self, package_name_string, **kwargs):
  1591. """Run `cipd expand-package-name`.
  1592. CIPD package names can be declared with placeholder variables
  1593. such as '${platform}', this cmd will return the package name
  1594. with the variables resolved. The resolution is based on the host
  1595. the command is executing on.
  1596. """
  1597. kwargs.setdefault('stderr', subprocess2.PIPE)
  1598. cmd = ['cipd', 'expand-package-name', package_name_string]
  1599. ret = subprocess2.check_output(cmd, **kwargs).decode('utf-8')
  1600. return ret.strip()
  1601. @contextlib.contextmanager
  1602. def _create_ensure_file(self):
  1603. try:
  1604. contents = '$ParanoidMode CheckPresence\n'
  1605. # TODO(crbug/1329641): Remove once cipd packages have been updated
  1606. # to always be created in copy mode.
  1607. contents += '$OverrideInstallMode copy\n\n'
  1608. for subdir, packages in sorted(self._packages_by_subdir.items()):
  1609. contents += '@Subdir %s\n' % subdir
  1610. for package in sorted(packages, key=lambda p: p.name):
  1611. contents += '%s %s\n' % (package.name, package.version)
  1612. contents += '\n'
  1613. ensure_file = None
  1614. with tempfile.NamedTemporaryFile(suffix='.ensure',
  1615. delete=False,
  1616. mode='wb') as ensure_file:
  1617. ensure_file.write(contents.encode('utf-8', 'replace'))
  1618. yield ensure_file.name
  1619. finally:
  1620. if ensure_file is not None and os.path.exists(ensure_file.name):
  1621. os.remove(ensure_file.name)
  1622. def ensure(self):
  1623. """Run `cipd ensure`."""
  1624. with self._mutator_lock:
  1625. with self._create_ensure_file() as ensure_file:
  1626. cmd = [
  1627. 'cipd',
  1628. 'ensure',
  1629. '-log-level',
  1630. self._log_level,
  1631. '-root',
  1632. self.root_dir,
  1633. '-ensure-file',
  1634. ensure_file,
  1635. ]
  1636. gclient_utils.CheckCallAndFilter(cmd,
  1637. print_stdout=True,
  1638. show_header=True)
  1639. @contextlib.contextmanager
  1640. def _create_ensure_file_for_resolve(self):
  1641. try:
  1642. contents = '$ResolvedVersions %s\n' % os.devnull
  1643. for subdir, packages in sorted(self._packages_by_subdir.items()):
  1644. contents += '@Subdir %s\n' % subdir
  1645. for package in sorted(packages, key=lambda p: p.name):
  1646. contents += '%s %s\n' % (package.name, package.version)
  1647. contents += '\n'
  1648. ensure_file = None
  1649. with tempfile.NamedTemporaryFile(suffix='.ensure',
  1650. delete=False,
  1651. mode='wb') as ensure_file:
  1652. ensure_file.write(contents.encode('utf-8', 'replace'))
  1653. yield ensure_file.name
  1654. finally:
  1655. if ensure_file is not None and os.path.exists(ensure_file.name):
  1656. os.remove(ensure_file.name)
  1657. def _create_resolved_file(self):
  1658. return tempfile.NamedTemporaryFile(suffix='.resolved',
  1659. delete=False,
  1660. mode='wb')
  1661. def ensure_file_resolve(self):
  1662. """Run `cipd ensure-file-resolve`."""
  1663. with self._mutator_lock:
  1664. with self._create_resolved_file() as output_file:
  1665. with self._create_ensure_file_for_resolve() as ensure_file:
  1666. cmd = [
  1667. 'cipd',
  1668. 'ensure-file-resolve',
  1669. '-log-level',
  1670. self._log_level,
  1671. '-ensure-file',
  1672. ensure_file,
  1673. '-json-output',
  1674. output_file.name,
  1675. ]
  1676. gclient_utils.CheckCallAndFilter(cmd,
  1677. print_stdout=False,
  1678. show_header=False)
  1679. with open(output_file.name) as f:
  1680. output_json = json.load(f)
  1681. return output_json.get('result', {})
  1682. def run(self, command):
  1683. if command == 'update':
  1684. self.ensure()
  1685. elif command == 'revert':
  1686. self.clobber()
  1687. self.ensure()
  1688. def created_package(self, package):
  1689. """Checks whether this root created the given package.
  1690. Args:
  1691. package: CipdPackage; the package to check.
  1692. Returns:
  1693. bool; whether this root created the given package.
  1694. """
  1695. return package in self._all_packages
  1696. @property
  1697. def root_dir(self):
  1698. return self._root_dir
  1699. @property
  1700. def service_url(self):
  1701. return self._service_url
  1702. class CipdWrapper(SCMWrapper):
  1703. """Wrapper for CIPD.
  1704. Currently only supports chrome-infra-packages.appspot.com.
  1705. """
  1706. name = 'cipd'
  1707. def __init__(self,
  1708. url=None,
  1709. root_dir=None,
  1710. relpath=None,
  1711. out_fh=None,
  1712. out_cb=None,
  1713. root=None,
  1714. package=None):
  1715. super(CipdWrapper, self).__init__(url=url,
  1716. root_dir=root_dir,
  1717. relpath=relpath,
  1718. out_fh=out_fh,
  1719. out_cb=out_cb)
  1720. assert root.created_package(package)
  1721. self._package = package
  1722. self._root = root
  1723. #override
  1724. def GetCacheMirror(self):
  1725. return None
  1726. #override
  1727. def GetActualRemoteURL(self, options):
  1728. return self._root.service_url
  1729. #override
  1730. def DoesRemoteURLMatch(self, options):
  1731. del options
  1732. return True
  1733. def revert(self, options, args, file_list):
  1734. """Does nothing.
  1735. CIPD packages should be reverted at the root by running
  1736. `CipdRoot.run('revert')`.
  1737. """
  1738. def diff(self, options, args, file_list):
  1739. """CIPD has no notion of diffing."""
  1740. def pack(self, options, args, file_list):
  1741. """CIPD has no notion of diffing."""
  1742. def revinfo(self, options, args, file_list):
  1743. """Grab the instance ID."""
  1744. try:
  1745. tmpdir = tempfile.mkdtemp()
  1746. # Attempt to get instance_id from the root resolved cache.
  1747. # Resolved cache will not match on any CIPD packages with
  1748. # variables such as ${platform}, they will fall back to
  1749. # the slower method below.
  1750. resolved = self._root.resolved_packages()
  1751. if resolved:
  1752. # CIPD uses POSIX separators across all platforms, so
  1753. # replace any Windows separators.
  1754. path_split = self.relpath.replace(os.sep, "/").split(":")
  1755. if len(path_split) > 1:
  1756. src_path, package = path_split
  1757. if src_path in resolved:
  1758. for resolved_package in resolved[src_path]:
  1759. if package == resolved_package.get(
  1760. 'pin', {}).get('package'):
  1761. return resolved_package.get(
  1762. 'pin', {}).get('instance_id')
  1763. describe_json_path = os.path.join(tmpdir, 'describe.json')
  1764. cmd = [
  1765. 'cipd', 'describe', self._package.name, '-log-level', 'error',
  1766. '-version', self._package.version, '-json-output',
  1767. describe_json_path
  1768. ]
  1769. gclient_utils.CheckCallAndFilter(cmd)
  1770. with open(describe_json_path) as f:
  1771. describe_json = json.load(f)
  1772. return describe_json.get('result', {}).get('pin',
  1773. {}).get('instance_id')
  1774. finally:
  1775. gclient_utils.rmtree(tmpdir)
  1776. def status(self, options, args, file_list):
  1777. pass
  1778. def update(self, options, args, file_list):
  1779. """Does nothing.
  1780. CIPD packages should be updated at the root by running
  1781. `CipdRoot.run('update')`.
  1782. """
  1783. class GcsRoot(object):
  1784. """Root to keep track of all GCS objects, per checkout"""
  1785. def __init__(self, root_dir):
  1786. self._mutator_lock = threading.Lock()
  1787. self._root_dir = root_dir
  1788. # Populated when the DEPS file is parsed
  1789. # The objects here have not yet been downloaded and written into
  1790. # the .gcs_entries file
  1791. self._parsed_objects = {}
  1792. # .gcs_entries keeps track of which GCS deps have already been installed
  1793. # Maps checkout_name -> {GCS dep path -> [object_name]}
  1794. # This file is in the same directory as .gclient
  1795. self._gcs_entries_file = os.path.join(self._root_dir, '.gcs_entries')
  1796. # Contents of the .gcs_entries file
  1797. self._gcs_entries = self.read_gcs_entries()
  1798. @property
  1799. def root_dir(self):
  1800. return self._root_dir
  1801. def add_object(self, checkout_name, dep_path, object_name):
  1802. """Records the object in the _parsed_objects variable
  1803. This does not actually download the object"""
  1804. with self._mutator_lock:
  1805. if checkout_name not in self._parsed_objects:
  1806. self._parsed_objects[checkout_name] = {}
  1807. if dep_path not in self._parsed_objects[checkout_name]:
  1808. self._parsed_objects[checkout_name][dep_path] = [object_name]
  1809. else:
  1810. self._parsed_objects[checkout_name][dep_path].append(
  1811. object_name)
  1812. def read_gcs_entries(self):
  1813. """Reads .gcs_entries file and loads the content into _gcs_entries"""
  1814. if not os.path.exists(self._gcs_entries_file):
  1815. return {}
  1816. with open(self._gcs_entries_file, 'r') as f:
  1817. content = f.read().rstrip()
  1818. if content:
  1819. return json.loads(content)
  1820. return {}
  1821. def resolve_objects(self, checkout_name):
  1822. """Updates .gcs_entries with objects in _parsed_objects
  1823. This should only be called after the objects have been downloaded
  1824. and extracted."""
  1825. with self._mutator_lock:
  1826. object_dict = self._parsed_objects.get(checkout_name)
  1827. if not object_dict:
  1828. return
  1829. self._gcs_entries[checkout_name] = object_dict
  1830. with open(self._gcs_entries_file, 'w') as f:
  1831. f.write(json.dumps(self._gcs_entries, indent=2))
  1832. self._parsed_objects[checkout_name] = {}
  1833. def clobber_deps_with_updated_objects(self, checkout_name):
  1834. """Clobber the path if an object or GCS dependency is removed/added
  1835. This must be called before the GCS dependencies are
  1836. downloaded and extracted."""
  1837. with self._mutator_lock:
  1838. parsed_object_dict = self._parsed_objects.get(checkout_name, {})
  1839. parsed_paths = set(parsed_object_dict.keys())
  1840. resolved_object_dict = self._gcs_entries.get(checkout_name, {})
  1841. resolved_paths = set(resolved_object_dict.keys())
  1842. # If any GCS deps are added or removed entirely, clobber that path
  1843. intersected_paths = parsed_paths.intersection(resolved_paths)
  1844. # If any objects within a GCS dep are added/removed, clobber its
  1845. # extracted contents and relevant gcs dotfiles
  1846. for path in intersected_paths:
  1847. resolved_objects = resolved_object_dict[path]
  1848. parsed_objects = parsed_object_dict[path]
  1849. full_path = os.path.join(self.root_dir, path)
  1850. if (len(resolved_objects) != len(parsed_objects)
  1851. and os.path.exists(full_path)):
  1852. self.clobber_tar_content_names(full_path)
  1853. self.clobber_hash_files(full_path)
  1854. self.clobber_migration_files(full_path)
  1855. def clobber_tar_content_names(self, entry_directory):
  1856. """Delete paths written in .*_content_names files"""
  1857. content_names_files = glob.glob(
  1858. os.path.join(entry_directory, '.*_content_names'))
  1859. for file in content_names_files:
  1860. with open(file, 'r') as f:
  1861. names = json.loads(f.read().strip())
  1862. for name in names:
  1863. name_path = os.path.join(entry_directory, name)
  1864. if os.path.isdir(
  1865. name_path) or not os.path.exists(name_path):
  1866. continue
  1867. os.remove(os.path.join(entry_directory, name))
  1868. os.remove(file)
  1869. def clobber_hash_files(self, entry_directory):
  1870. files = glob.glob(os.path.join(entry_directory, '.*_hash'))
  1871. for f in files:
  1872. os.remove(f)
  1873. def clobber_migration_files(self, entry_directory):
  1874. files = glob.glob(os.path.join(entry_directory,
  1875. '.*_is_first_class_gcs'))
  1876. for f in files:
  1877. os.remove(f)
  1878. def clobber(self):
  1879. """Remove all dep path gcs items and clear .gcs_entries"""
  1880. for _, objects_dict in self._gcs_entries.items():
  1881. for dep_path, _ in objects_dict.items():
  1882. full_path = os.path.join(self.root_dir, dep_path)
  1883. self.clobber_tar_content_names(full_path)
  1884. self.clobber_hash_files(full_path)
  1885. self.clobber_migration_files(full_path)
  1886. if os.path.exists(self._gcs_entries_file):
  1887. os.remove(self._gcs_entries_file)
  1888. with self._mutator_lock:
  1889. self._gcs_entries = {}
  1890. class GcsWrapper(SCMWrapper):
  1891. """Wrapper for GCS.
  1892. Currently only supports content from Google Cloud Storage.
  1893. """
  1894. name = 'gcs'
  1895. def __init__(self,
  1896. url=None,
  1897. root_dir=None,
  1898. relpath=None,
  1899. out_fh=None,
  1900. out_cb=None):
  1901. super(GcsWrapper, self).__init__(url=url,
  1902. root_dir=root_dir,
  1903. relpath=relpath,
  1904. out_fh=out_fh,
  1905. out_cb=out_cb)
  1906. #override
  1907. def GetCacheMirror(self):
  1908. return None
  1909. #override
  1910. def GetActualRemoteURL(self, options):
  1911. return None
  1912. #override
  1913. def DoesRemoteURLMatch(self, options):
  1914. del options
  1915. return True
  1916. def revert(self, options, args, file_list):
  1917. """Does nothing."""
  1918. def diff(self, options, args, file_list):
  1919. """GCS has no notion of diffing."""
  1920. def pack(self, options, args, file_list):
  1921. """GCS has no notion of diffing."""
  1922. def revinfo(self, options, args, file_list):
  1923. """Does nothing"""
  1924. def status(self, options, args, file_list):
  1925. pass
  1926. def update(self, options, args, file_list):
  1927. """Does nothing."""
  1928. class CogWrapper(SCMWrapper):
  1929. """Wrapper for Cog, all no-op."""
  1930. name = 'cog'
  1931. def __init__(self):
  1932. super(CogWrapper, self).__init__()
  1933. #override
  1934. def GetCacheMirror(self):
  1935. return None
  1936. #override
  1937. def GetActualRemoteURL(self, options):
  1938. return None
  1939. #override
  1940. def GetSubmoduleDiff(self):
  1941. return None
  1942. #override
  1943. def GetSubmoduleStateFromIndex(self):
  1944. return None
  1945. #override
  1946. def DoesRemoteURLMatch(self, options):
  1947. del options
  1948. return True
  1949. def revert(self, options, args, file_list):
  1950. pass
  1951. def diff(self, options, args, file_list):
  1952. pass
  1953. def pack(self, options, args, file_list):
  1954. pass
  1955. def revinfo(self, options, args, file_list):
  1956. pass
  1957. def status(self, options, args, file_list):
  1958. pass
  1959. def update(self, options, args, file_list):
  1960. pass