gclient_scm.py 67 KB

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