gclient_scm.py 82 KB

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