gclient_scm.py 95 KB

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