gclient_scm.py 61 KB

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