gclient_scm.py 82 KB

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