gclient_scm.py 92 KB

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