gclient_scm.py 95 KB

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