gclient_scm.py 62 KB

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