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.
5 """Gclient-specific SCM-specific operations."""
7 from __future__ import print_function
19 import download_from_google_storage
27 THIS_FILE_PATH = os.path.abspath(__file__)
29 GSUTIL_DEFAULT_PATH = os.path.join(
30 os.path.dirname(os.path.abspath(__file__)),
31 'third_party', 'gsutil', 'gsutil')
33 CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src.git'
34 class DiffFiltererWrapper(object):
35 """Simple base class which tracks which file is being diffed and
36 replaces instances of its file name in the original and
37 working copy lines of the svn/git diff output."""
39 original_prefix = "--- "
40 working_prefix = "+++ "
42 def __init__(self, relpath, print_func):
43 # Note that we always use '/' as the path separator to be
44 # consistent with svn's cygwin-style output on Windows
45 self._relpath = relpath.replace("\\", "/")
46 self._current_file = None
47 self._print_func = print_func
49 def SetCurrentFile(self, current_file):
50 self._current_file = current_file
53 def _replacement_file(self):
54 return posixpath.join(self._relpath, self._current_file)
56 def _Replace(self, line):
57 return line.replace(self._current_file, self._replacement_file)
59 def Filter(self, line):
60 if (line.startswith(self.index_string)):
61 self.SetCurrentFile(line[len(self.index_string):])
62 line = self._Replace(line)
64 if (line.startswith(self.original_prefix) or
65 line.startswith(self.working_prefix)):
66 line = self._Replace(line)
67 self._print_func(line)
70 class SvnDiffFilterer(DiffFiltererWrapper):
71 index_string = "Index: "
74 class GitDiffFilterer(DiffFiltererWrapper):
75 index_string = "diff --git "
77 def SetCurrentFile(self, current_file):
78 # Get filename by parsing "a/<filename> b/<filename>"
79 self._current_file = current_file[:(len(current_file)/2)][2:]
81 def _Replace(self, line):
82 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
85 ### SCM abstraction layer
87 # Factory Method for SCM wrapper creation
91 url, _ = gclient_utils.SplitUrlRevision(url)
92 if (url.startswith('git://') or url.startswith('ssh://') or
93 url.startswith('git+http://') or url.startswith('git+https://') or
94 url.endswith('.git') or url.startswith('sso://') or
95 'googlesource' in url):
97 elif (url.startswith('http://') or url.startswith('https://') or
98 url.startswith('svn://') or url.startswith('svn+ssh://')):
100 elif url.startswith('file://'):
101 if url.endswith('.git'):
107 def CreateSCM(url, root_dir=None, relpath=None, out_fh=None, out_cb=None):
113 scm_name = GetScmName(url)
114 if not scm_name in SCM_MAP:
115 raise gclient_utils.Error('No SCM found for url %s' % url)
116 scm_class = SCM_MAP[scm_name]
117 if not scm_class.BinaryExists():
118 raise gclient_utils.Error('%s command not found' % scm_name)
119 return scm_class(url, root_dir, relpath, out_fh, out_cb)
122 # SCMWrapper base class
124 class SCMWrapper(object):
125 """Add necessary glue between all the supported SCM.
127 This is the abstraction layer to bind to different SCM.
130 def __init__(self, url=None, root_dir=None, relpath=None, out_fh=None,
133 self._root_dir = root_dir
135 self._root_dir = self._root_dir.replace('/', os.sep)
136 self.relpath = relpath
138 self.relpath = self.relpath.replace('/', os.sep)
139 if self.relpath and self._root_dir:
140 self.checkout_path = os.path.join(self._root_dir, self.relpath)
146 def Print(self, *args, **kwargs):
147 kwargs.setdefault('file', self.out_fh)
148 if kwargs.pop('timestamp', True):
149 self.out_fh.write('[%s] ' % gclient_utils.Elapsed())
150 print(*args, **kwargs)
152 def RunCommand(self, command, options, args, file_list=None):
153 commands = ['cleanup', 'update', 'updatesingle', 'revert',
154 'revinfo', 'status', 'diff', 'pack', 'runhooks']
156 if not command in commands:
157 raise gclient_utils.Error('Unknown command %s' % command)
159 if not command in dir(self):
160 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
161 command, self.__class__.__name__))
163 return getattr(self, command)(options, args, file_list)
166 def _get_first_remote_url(checkout_path):
167 log = scm.GIT.Capture(
168 ['config', '--local', '--get-regexp', r'remote.*.url'],
170 # Get the second token of the first line of the log.
171 return log.splitlines()[0].split(' ', 1)[1]
173 def GetActualRemoteURL(self, options):
174 """Attempt to determine the remote URL for this SCMWrapper."""
176 if os.path.exists(os.path.join(self.checkout_path, '.git')):
177 actual_remote_url = self._get_first_remote_url(self.checkout_path)
179 # If a cache_dir is used, obtain the actual remote URL from the cache.
180 if getattr(self, 'cache_dir', None):
181 url, _ = gclient_utils.SplitUrlRevision(self.url)
182 mirror = git_cache.Mirror(url)
183 if (mirror.exists() and mirror.mirror_path.replace('\\', '/') ==
184 actual_remote_url.replace('\\', '/')):
185 actual_remote_url = self._get_first_remote_url(mirror.mirror_path)
186 return actual_remote_url
189 if os.path.exists(os.path.join(self.checkout_path, '.svn')):
190 return scm.SVN.CaptureLocalInfo([], self.checkout_path)['URL']
193 def DoesRemoteURLMatch(self, options):
194 """Determine whether the remote URL of this checkout is the expected URL."""
195 if not os.path.exists(self.checkout_path):
196 # A checkout which doesn't exist can't be broken.
199 actual_remote_url = self.GetActualRemoteURL(options)
200 if actual_remote_url:
201 return (gclient_utils.SplitUrlRevision(actual_remote_url)[0].rstrip('/')
202 == gclient_utils.SplitUrlRevision(self.url)[0].rstrip('/'))
204 # This may occur if the self.checkout_path exists but does not contain a
205 # valid git or svn checkout.
208 def _DeleteOrMove(self, force):
209 """Delete the checkout directory or move it out of the way.
212 force: bool; if True, delete the directory. Otherwise, just move it.
214 if force and os.environ.get('CHROME_HEADLESS') == '1':
215 self.Print('_____ Conflicting directory found in %s. Removing.'
216 % self.checkout_path)
217 gclient_utils.AddWarning('Conflicting directory %s deleted.'
218 % self.checkout_path)
219 gclient_utils.rmtree(self.checkout_path)
221 bad_scm_dir = os.path.join(self._root_dir, '_bad_scm',
222 os.path.dirname(self.relpath))
225 os.makedirs(bad_scm_dir)
227 if e.errno != errno.EEXIST:
230 dest_path = tempfile.mkdtemp(
231 prefix=os.path.basename(self.relpath),
233 self.Print('_____ Conflicting directory found in %s. Moving to %s.'
234 % (self.checkout_path, dest_path))
235 gclient_utils.AddWarning('Conflicting directory %s moved to %s.'
236 % (self.checkout_path, dest_path))
237 shutil.move(self.checkout_path, dest_path)
240 class GitWrapper(SCMWrapper):
241 """Wrapper for Git"""
247 def __init__(self, url=None, *args):
248 """Removes 'git+' fake prefix from git URL."""
249 if url.startswith('git+http://') or url.startswith('git+https://'):
251 SCMWrapper.__init__(self, url, *args)
252 filter_kwargs = { 'time_throttle': 1, 'out_fh': self.out_fh }
254 filter_kwargs['predicate'] = self.out_cb
255 self.filter = gclient_utils.GitFilter(**filter_kwargs)
259 """Returns true if the command exists."""
261 # We assume git is newer than 1.7. See: crbug.com/114483
262 result, version = scm.GIT.AssertVersion('1.7')
264 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
269 def GetCheckoutRoot(self):
270 return scm.GIT.GetCheckoutRoot(self.checkout_path)
272 def GetRevisionDate(self, _revision):
273 """Returns the given revision's date in ISO-8601 format (which contains the
275 # TODO(floitsch): get the time-stamp of the given revision and not just the
276 # time-stamp of the currently checked out revision.
277 return self._Capture(['log', '-n', '1', '--format=%ai'])
280 def cleanup(options, args, file_list):
281 """'Cleanup' the repo.
283 There's no real git equivalent for the svn cleanup command, do a no-op.
286 def diff(self, options, _args, _file_list):
287 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
288 self._Run(['diff', merge_base], options)
290 def pack(self, _options, _args, _file_list):
291 """Generates a patch file which can be applied to the root of the
294 The patch file is generated from a diff of the merge base of HEAD and
297 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
298 gclient_utils.CheckCallAndFilter(
299 ['git', 'diff', merge_base],
300 cwd=self.checkout_path,
301 filter_fn=GitDiffFilterer(self.relpath, print_func=self.Print).Filter)
303 def _FetchAndReset(self, revision, file_list, options):
304 """Equivalent to git fetch; git reset."""
306 if not options.verbose:
308 self._UpdateBranchHeads(options, fetch=False)
310 self._Fetch(options, prune=True, quiet=options.verbose)
311 self._Run(['reset', '--hard', revision] + quiet, options)
312 if file_list is not None:
313 files = self._Capture(['ls-files']).splitlines()
314 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
316 def _DisableHooks(self):
317 hook_dir = os.path.join(self.checkout_path, '.git', 'hooks')
318 if not os.path.isdir(hook_dir):
320 for f in os.listdir(hook_dir):
321 if not f.endswith('.sample') and not f.endswith('.disabled'):
322 os.rename(os.path.join(hook_dir, f),
323 os.path.join(hook_dir, f + '.disabled'))
325 def update(self, options, args, file_list):
326 """Runs git to update or transparently checkout the working copy.
328 All updated files will be appended to file_list.
331 Error: if can't get URL for relative path.
334 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
336 self._CheckMinVersion("1.6.6")
338 # If a dependency is not pinned, track the default remote branch.
339 default_rev = 'refs/remotes/%s/master' % self.remote
340 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
342 revision = deps_revision
345 # Override the revision number.
346 revision = str(options.revision)
347 if revision == 'unmanaged':
348 # Check again for a revision in case an initial ref was specified
349 # in the url, for example bla.git@refs/heads/custombranch
350 revision = deps_revision
353 revision = default_rev
358 if gclient_utils.IsDateRevision(revision):
359 # Date-revisions only work on git-repositories if the reflog hasn't
360 # expired yet. Use rev-list to get the corresponding revision.
361 # git rev-list -n 1 --before='time-stamp' branchname
362 if options.transitive:
363 self.Print('Warning: --transitive only works for SVN repositories.')
364 revision = default_rev
366 rev_str = ' at %s' % revision
367 files = [] if file_list is not None else None
372 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
373 verbose = ['--verbose']
376 remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
378 # Rewrite remote refs to their local equivalents.
379 revision = ''.join(remote_ref)
381 elif revision.startswith('refs/'):
382 # Local branch? We probably don't want to support, since DEPS should
383 # always specify branches as they are in the upstream repo.
386 # hash is also a tag, only make a distinction at checkout
389 mirror = self._GetMirror(url, options)
391 url = mirror.mirror_path
393 if (not os.path.exists(self.checkout_path) or
394 (os.path.isdir(self.checkout_path) and
395 not os.path.exists(os.path.join(self.checkout_path, '.git')))):
397 self._UpdateMirror(mirror, options)
399 self._Clone(revision, url, options)
400 except subprocess2.CalledProcessError:
401 self._DeleteOrMove(options.force)
402 self._Clone(revision, url, options)
403 if file_list is not None:
404 files = self._Capture(['ls-files']).splitlines()
405 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
407 # Make the output a little prettier. It's nice to have some whitespace
408 # between projects when cloning.
410 return self._Capture(['rev-parse', '--verify', 'HEAD'])
413 self._UpdateBranchHeads(options, fetch=False)
414 self.Print('________ unmanaged solution; skipping %s' % self.relpath)
415 return self._Capture(['rev-parse', '--verify', 'HEAD'])
418 self._UpdateMirror(mirror, options)
420 # See if the url has changed (the unittests use git://foo for the url, let
422 current_url = self._Capture(['config', 'remote.%s.url' % self.remote])
424 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
425 # unit test pass. (and update the comment above)
426 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
427 # This allows devs to use experimental repos which have a different url
428 # but whose branch(s) are the same as official repos.
429 if (current_url.rstrip('/') != url.rstrip('/') and
430 url != 'git://foo' and
432 ['git', 'config', 'remote.%s.gclient-auto-fix-url' % self.remote],
433 cwd=self.checkout_path).strip() != 'False'):
434 self.Print('_____ switching %s to a new upstream' % self.relpath)
435 if not (options.force or options.reset):
436 # Make sure it's clean
437 self._CheckClean(rev_str)
438 # Switch over to the new upstream
439 self._Run(['remote', 'set-url', self.remote, url], options)
440 self._FetchAndReset(revision, file_list, options)
444 return self._Capture(['rev-parse', '--verify', 'HEAD'])
446 cur_branch = self._GetCurrentBranch()
449 # 0) HEAD is detached. Probably from our initial clone.
450 # - make sure HEAD is contained by a named ref, then update.
451 # Cases 1-4. HEAD is a branch.
452 # 1) current branch is not tracking a remote branch (could be git-svn)
453 # - try to rebase onto the new hash or branch
454 # 2) current branch is tracking a remote branch with local committed
455 # changes, but the DEPS file switched to point to a hash
456 # - rebase those changes on top of the hash
457 # 3) current branch is tracking a remote branch w/or w/out changes, and
459 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
460 # 4) current branch is tracking a remote branch, but DEPS switches to a
461 # different remote branch, and
462 # a) current branch has no local changes, and --force:
463 # - checkout new branch
464 # b) current branch has local changes, and --force and --reset:
465 # - checkout new branch
468 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
470 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
471 # or it returns None if it couldn't find an upstream
472 if cur_branch is None:
473 upstream_branch = None
474 current_type = "detached"
475 logging.debug("Detached HEAD")
477 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
478 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
479 current_type = "hash"
480 logging.debug("Current branch is not tracking an upstream (remote)"
482 elif upstream_branch.startswith('refs/remotes'):
483 current_type = "branch"
485 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
487 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
488 # Update the remotes first so we have all the refs.
489 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
490 cwd=self.checkout_path)
492 self.Print(remote_output)
494 self._UpdateBranchHeads(options, fetch=True)
496 # This is a big hammer, debatable if it should even be here...
497 if options.force or options.reset:
499 if options.upstream and upstream_branch:
500 target = upstream_branch
501 self._Run(['reset', '--hard', target], options)
503 if current_type == 'detached':
505 self._CheckClean(rev_str)
506 self._CheckDetachedHead(rev_str, options)
507 if self._Capture(['rev-list', '-n', '1', 'HEAD']) == revision:
508 self.Print('Up-to-date; skipping checkout.')
510 # 'git checkout' may need to overwrite existing untracked files. Allow
511 # it only when nuclear options are enabled.
515 force=(options.force and options.delete_unversioned_trees),
519 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
520 elif current_type == 'hash':
522 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
523 # Our git-svn branch (upstream_branch) is our upstream
524 self._AttemptRebase(upstream_branch, files, options,
525 newbase=revision, printed_path=printed_path,
529 # Can't find a merge-base since we don't know our upstream. That makes
530 # this command VERY likely to produce a rebase failure. For now we
531 # assume origin is our upstream since that's what the old behavior was.
532 upstream_branch = self.remote
533 if options.revision or deps_revision:
534 upstream_branch = revision
535 self._AttemptRebase(upstream_branch, files, options,
536 printed_path=printed_path, merge=options.merge)
538 elif rev_type == 'hash':
540 self._AttemptRebase(upstream_branch, files, options,
541 newbase=revision, printed_path=printed_path,
544 elif remote_ref and ''.join(remote_ref) != upstream_branch:
546 new_base = ''.join(remote_ref)
548 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
549 switch_error = ("Could not switch upstream branch from %s to %s\n"
550 % (upstream_branch, new_base) +
551 "Please use --force or merge or rebase manually:\n" +
552 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
553 "OR git checkout -b <some new branch> %s" % new_base)
557 self._CheckClean(rev_str)
560 except gclient_utils.Error as e:
565 switch_error = '%s\n%s' % (e.message, switch_error)
567 self.Print("Switching upstream branch from %s to %s" %
568 (upstream_branch, new_base))
569 switch_branch = 'gclient_' + remote_ref[1]
570 self._Capture(['branch', '-f', switch_branch, new_base])
571 self._Checkout(options, switch_branch, force=True, quiet=True)
574 raise gclient_utils.Error(switch_error)
576 # case 3 - the default case
577 if files is not None:
578 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
580 self.Print('Trying fast-forward merge to branch : %s' % upstream_branch)
582 merge_args = ['merge']
584 merge_args.append('--ff')
586 merge_args.append('--ff-only')
587 merge_args.append(upstream_branch)
588 merge_output = self._Capture(merge_args)
589 except subprocess2.CalledProcessError as e:
590 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
593 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
597 action = self._AskForData(
598 'Cannot %s, attempt to rebase? '
599 '(y)es / (q)uit / (s)kip : ' %
600 ('merge' if options.merge else 'fast-forward merge'),
603 raise gclient_utils.Error('Invalid Character')
604 if re.match(r'yes|y', action, re.I):
605 self._AttemptRebase(upstream_branch, files, options,
606 printed_path=printed_path, merge=False)
609 elif re.match(r'quit|q', action, re.I):
610 raise gclient_utils.Error("Can't fast-forward, please merge or "
612 "cd %s && git " % self.checkout_path
613 + "rebase %s" % upstream_branch)
614 elif re.match(r'skip|s', action, re.I):
615 self.Print('Skipping %s' % self.relpath)
618 self.Print('Input not recognized')
619 elif re.match("error: Your local changes to '.*' would be "
620 "overwritten by merge. Aborting.\nPlease, commit your "
621 "changes or stash them before you can merge.\n",
624 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
626 raise gclient_utils.Error(e.stderr)
628 # Some other problem happened with the merge
629 logging.error("Error during fast-forward merge in %s!" % self.relpath)
633 # Fast-forward merge was successful
634 if not re.match('Already up-to-date.', merge_output) or verbose:
636 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
638 self.Print(merge_output.strip())
640 # Make the output a little prettier. It's nice to have some
641 # whitespace between projects when syncing.
644 if file_list is not None:
645 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
647 # If the rebase generated a conflict, abort and ask user to fix
648 if self._IsRebasing():
649 raise gclient_utils.Error('\n____ %s%s\n'
650 '\nConflict while rebasing this branch.\n'
651 'Fix the conflict and run gclient again.\n'
652 'See man git-rebase for details.\n'
653 % (self.relpath, rev_str))
656 self.Print('Checked out revision %s' % self.revinfo(options, (), None),
659 # If --reset and --delete_unversioned_trees are specified, remove any
660 # untracked directories.
661 if options.reset and options.delete_unversioned_trees:
662 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
663 # merge-base by default), so doesn't include untracked files. So we use
664 # 'git ls-files --directory --others --exclude-standard' here directly.
665 paths = scm.GIT.Capture(
666 ['ls-files', '--directory', '--others', '--exclude-standard'],
668 for path in (p for p in paths.splitlines() if p.endswith('/')):
669 full_path = os.path.join(self.checkout_path, path)
670 if not os.path.islink(full_path):
671 self.Print('_____ removing unversioned directory %s' % path)
672 gclient_utils.rmtree(full_path)
674 return self._Capture(['rev-parse', '--verify', 'HEAD'])
677 def revert(self, options, _args, file_list):
678 """Reverts local modifications.
680 All reverted files will be appended to file_list.
682 if not os.path.isdir(self.checkout_path):
683 # revert won't work if the directory doesn't exist. It needs to
685 self.Print('_____ %s is missing, synching instead' % self.relpath)
686 # Don't reuse the args.
687 return self.update(options, [], file_list)
689 default_rev = "refs/heads/master"
691 if self._GetCurrentBranch():
692 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
693 default_rev = upstream_branch or default_rev
694 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
695 if not deps_revision:
696 deps_revision = default_rev
697 if deps_revision.startswith('refs/heads/'):
698 deps_revision = deps_revision.replace('refs/heads/', self.remote + '/')
699 deps_revision = self.GetUsableRev(deps_revision, options)
701 if file_list is not None:
702 files = self._Capture(['diff', deps_revision, '--name-only']).split()
704 self._Run(['reset', '--hard', deps_revision], options)
705 self._Run(['clean', '-f', '-d'], options)
707 if file_list is not None:
708 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
710 def revinfo(self, _options, _args, _file_list):
711 """Returns revision"""
712 return self._Capture(['rev-parse', 'HEAD'])
714 def runhooks(self, options, args, file_list):
715 self.status(options, args, file_list)
717 def status(self, options, _args, file_list):
718 """Display status information."""
719 if not os.path.isdir(self.checkout_path):
720 self.Print('________ couldn\'t run status in %s:\n'
721 'The directory does not exist.' % self.checkout_path)
723 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
724 self._Run(['diff', '--name-status', merge_base], options,
726 if file_list is not None:
727 files = self._Capture(['diff', '--name-only', merge_base]).split()
728 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
730 def GetUsableRev(self, rev, options):
731 """Finds a useful revision for this repository.
733 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
734 will be called on the source."""
736 if not os.path.isdir(self.checkout_path):
737 raise gclient_utils.Error(
738 ( 'We could not find a valid hash for safesync_url response "%s".\n'
739 'Safesync URLs with a git checkout currently require the repo to\n'
740 'be cloned without a safesync_url before adding the safesync_url.\n'
741 'For more info, see: '
742 'http://code.google.com/p/chromium/wiki/UsingNewGit'
743 '#Initial_checkout' ) % rev)
744 elif rev.isdigit() and len(rev) < 7:
745 # Handles an SVN rev. As an optimization, only verify an SVN revision as
746 # [0-9]{1,6} for now to avoid making a network request.
747 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
748 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
749 if not local_head or local_head < int(rev):
751 logging.debug('Looking for git-svn configuration optimizations.')
752 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
753 cwd=self.checkout_path):
755 except subprocess2.CalledProcessError:
756 logging.debug('git config --get svn-remote.svn.fetch failed, '
757 'ignoring possible optimization.')
759 self.Print('Running git svn fetch. This might take a while.\n')
760 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
762 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
763 cwd=self.checkout_path, rev=rev)
764 except gclient_utils.Error, e:
766 self.Print('Warning: Could not find a git revision with accurate\n'
767 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
768 'the closest sane git revision, which is:\n'
769 ' %s\n' % (rev, e.message))
771 raise gclient_utils.Error(
772 ( 'It appears that either your git-svn remote is incorrectly\n'
773 'configured or the revision in your safesync_url is\n'
774 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
775 'corresponding git hash for SVN rev %s.' ) % rev)
777 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
780 # May exist in origin, but we don't have it yet, so fetch and look
783 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
787 raise gclient_utils.Error(
788 ( 'We could not find a valid hash for safesync_url response "%s".\n'
789 'Safesync URLs with a git checkout currently require a git-svn\n'
790 'remote or a safesync_url that provides git sha1s. Please add a\n'
791 'git-svn remote or change your safesync_url. For more info, see:\n'
792 'http://code.google.com/p/chromium/wiki/UsingNewGit'
793 '#Initial_checkout' ) % rev)
797 def FullUrlForRelativeUrl(self, url):
798 # Strip from last '/'
799 # Equivalent to unix basename
801 return base_url[:base_url.rfind('/')] + url
803 def _GetMirror(self, url, options):
804 """Get a git_cache.Mirror object for the argument url."""
805 if not git_cache.Mirror.GetCachePath():
808 'print_func': self.filter,
811 # TODO(hinoka): This currently just fails because lkcr/lkgr are branches
812 # not tags. This also adds 20 seconds to every bot_update
813 # run, so I'm commenting this out until lkcr/lkgr become
815 # if url == CHROMIUM_SRC_URL or url + '.git' == CHROMIUM_SRC_URL:
816 # mirror_kwargs['refs'].extend(['refs/tags/lkgr', 'refs/tags/lkcr'])
817 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
818 mirror_kwargs['refs'].append('refs/branch-heads/*')
819 if hasattr(options, 'with_tags') and options.with_tags:
820 mirror_kwargs['refs'].append('refs/tags/*')
821 return git_cache.Mirror(url, **mirror_kwargs)
824 def _UpdateMirror(mirror, options):
825 """Update a git mirror by fetching the latest commits from the remote."""
826 if getattr(options, 'shallow', False):
827 # HACK(hinoka): These repositories should be super shallow.
828 if 'flash' in mirror.url:
834 mirror.populate(verbose=options.verbose, bootstrap=True, depth=depth,
835 ignore_lock=getattr(options, 'ignore_locks', False))
838 def _Clone(self, revision, url, options):
839 """Clone a git repository from the given URL.
841 Once we've cloned the repo, we checkout a working branch if the specified
842 revision is a branch head. If it is a tag or a specific commit, then we
843 leave HEAD detached as it makes future updates simpler -- in this case the
844 user should first create a new branch or switch to an existing branch before
845 making changes in the repo."""
846 if not options.verbose:
847 # git clone doesn't seem to insert a newline properly before printing
850 cfg = gclient_utils.DefaultIndexPackConfig(url)
851 clone_cmd = cfg + ['clone', '--no-checkout', '--progress']
853 clone_cmd.append('--shared')
855 clone_cmd.append('--verbose')
856 clone_cmd.append(url)
857 # If the parent directory does not exist, Git clone on Windows will not
858 # create it, so we need to do it manually.
859 parent_dir = os.path.dirname(self.checkout_path)
860 gclient_utils.safe_makedirs(parent_dir)
863 if hasattr(options, 'no_history') and options.no_history:
864 if gclient_utils.IsGitSha(revision):
865 # In the case of a subproject, the pinned sha is not necessarily the
866 # head of the remote branch (so we can't just use --depth=N). Instead,
867 # we tell git to fetch all the remote objects from SHA..HEAD by means of
868 # a template git dir which has a 'shallow' file pointing to the sha.
869 template_dir = tempfile.mkdtemp(
870 prefix='_gclient_gittmp_%s' % os.path.basename(self.checkout_path),
872 self._Run(['init', '--bare', template_dir], options, cwd=self._root_dir)
873 with open(os.path.join(template_dir, 'shallow'), 'w') as template_file:
874 template_file.write(revision)
875 clone_cmd.append('--template=' + template_dir)
877 # Otherwise, we're just interested in the HEAD. Just use --depth.
878 clone_cmd.append('--depth=1')
880 tmp_dir = tempfile.mkdtemp(
881 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
884 clone_cmd.append(tmp_dir)
885 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
886 gclient_utils.safe_makedirs(self.checkout_path)
887 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
888 os.path.join(self.checkout_path, '.git'))
890 traceback.print_exc(file=self.out_fh)
893 if os.listdir(tmp_dir):
894 self.Print('_____ removing non-empty tmp dir %s' % tmp_dir)
895 gclient_utils.rmtree(tmp_dir)
897 gclient_utils.rmtree(template_dir)
898 self._UpdateBranchHeads(options, fetch=True)
899 remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
900 self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
901 if self._GetCurrentBranch() is None:
902 # Squelch git's very verbose detached HEAD warning and use our own
904 ('Checked out %s to a detached HEAD. Before making any commits\n'
905 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
906 'an existing branch or use \'git checkout %s -b <branch>\' to\n'
907 'create a new branch for your work.') % (revision, self.remote))
909 def _AskForData(self, prompt, options):
912 raise gclient_utils.Error("Background task requires input. Rerun "
913 "gclient with --jobs=1 so that\n"
914 "interaction is possible.")
916 return raw_input(prompt)
917 except KeyboardInterrupt:
918 # Hide the exception.
922 def _AttemptRebase(self, upstream, files, options, newbase=None,
923 branch=None, printed_path=False, merge=False):
924 """Attempt to rebase onto either upstream or, if specified, newbase."""
925 if files is not None:
926 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
930 action = 'merge' if merge else 'rebase'
932 self.Print('_____ %s : Attempting %s onto %s...' % (
933 self.relpath, action, revision))
936 self.Print('Attempting %s onto %s...' % (action, revision))
939 merge_output = self._Capture(['merge', revision])
941 self.Print(merge_output)
944 # Build the rebase command here using the args
945 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
946 rebase_cmd = ['rebase']
948 rebase_cmd.append('--verbose')
950 rebase_cmd.extend(['--onto', newbase])
951 rebase_cmd.append(upstream)
953 rebase_cmd.append(branch)
956 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
957 except subprocess2.CalledProcessError, e:
958 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
959 re.match(r'cannot rebase: your index contains uncommitted changes',
962 rebase_action = self._AskForData(
963 'Cannot rebase because of unstaged changes.\n'
964 '\'git reset --hard HEAD\' ?\n'
965 'WARNING: destroys any uncommitted work in your current branch!'
966 ' (y)es / (q)uit / (s)how : ', options)
967 if re.match(r'yes|y', rebase_action, re.I):
968 self._Run(['reset', '--hard', 'HEAD'], options)
969 # Should this be recursive?
970 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
972 elif re.match(r'quit|q', rebase_action, re.I):
973 raise gclient_utils.Error("Please merge or rebase manually\n"
974 "cd %s && git " % self.checkout_path
975 + "%s" % ' '.join(rebase_cmd))
976 elif re.match(r'show|s', rebase_action, re.I):
977 self.Print('%s' % e.stderr.strip())
980 gclient_utils.Error("Input not recognized")
982 elif re.search(r'^CONFLICT', e.stdout, re.M):
983 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
984 "Fix the conflict and run gclient again.\n"
985 "See 'man git-rebase' for details.\n")
987 self.Print(e.stdout.strip())
988 self.Print('Rebase produced error output:\n%s' % e.stderr.strip())
989 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
990 "manually.\ncd %s && git " %
992 + "%s" % ' '.join(rebase_cmd))
994 self.Print(rebase_output.strip())
995 if not options.verbose:
996 # Make the output a little prettier. It's nice to have some
997 # whitespace between projects when syncing.
1001 def _CheckMinVersion(min_version):
1002 (ok, current_version) = scm.GIT.AssertVersion(min_version)
1004 raise gclient_utils.Error('git version %s < minimum required %s' %
1005 (current_version, min_version))
1007 def _IsRebasing(self):
1008 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
1009 # have a plumbing command to determine whether a rebase is in progress, so
1010 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
1011 g = os.path.join(self.checkout_path, '.git')
1013 os.path.isdir(os.path.join(g, "rebase-merge")) or
1014 os.path.isdir(os.path.join(g, "rebase-apply")))
1016 def _CheckClean(self, rev_str):
1017 # Make sure the tree is clean; see git-rebase.sh for reference
1019 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
1020 cwd=self.checkout_path)
1021 except subprocess2.CalledProcessError:
1022 raise gclient_utils.Error('\n____ %s%s\n'
1023 '\tYou have unstaged changes.\n'
1024 '\tPlease commit, stash, or reset.\n'
1025 % (self.relpath, rev_str))
1027 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
1028 '--ignore-submodules', 'HEAD', '--'],
1029 cwd=self.checkout_path)
1030 except subprocess2.CalledProcessError:
1031 raise gclient_utils.Error('\n____ %s%s\n'
1032 '\tYour index contains uncommitted changes\n'
1033 '\tPlease commit, stash, or reset.\n'
1034 % (self.relpath, rev_str))
1036 def _CheckDetachedHead(self, rev_str, _options):
1037 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
1038 # reference by a commit). If not, error out -- most likely a rebase is
1039 # in progress, try to detect so we can give a better error.
1041 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
1042 cwd=self.checkout_path)
1043 except subprocess2.CalledProcessError:
1044 # Commit is not contained by any rev. See if the user is rebasing:
1045 if self._IsRebasing():
1047 raise gclient_utils.Error('\n____ %s%s\n'
1048 '\tAlready in a conflict, i.e. (no branch).\n'
1049 '\tFix the conflict and run gclient again.\n'
1050 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
1051 '\tSee man git-rebase for details.\n'
1052 % (self.relpath, rev_str))
1053 # Let's just save off the commit so we can proceed.
1054 name = ('saved-by-gclient-' +
1055 self._Capture(['rev-parse', '--short', 'HEAD']))
1056 self._Capture(['branch', '-f', name])
1057 self.Print('_____ found an unreferenced commit and saved it as \'%s\'' %
1060 def _GetCurrentBranch(self):
1061 # Returns name of current branch or None for detached HEAD
1062 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
1063 if branch == 'HEAD':
1067 def _Capture(self, args, **kwargs):
1068 kwargs.setdefault('cwd', self.checkout_path)
1069 kwargs.setdefault('stderr', subprocess2.PIPE)
1070 env = scm.GIT.ApplyEnvVars(kwargs)
1071 return subprocess2.check_output(['git'] + args, env=env, **kwargs).strip()
1073 def _Checkout(self, options, ref, force=False, quiet=None):
1074 """Performs a 'git-checkout' operation.
1077 options: The configured option set
1078 ref: (str) The branch/commit to checkout
1079 quiet: (bool/None) Whether or not the checkout shoud pass '--quiet'; if
1080 'None', the behavior is inferred from 'options.verbose'.
1081 Returns: (str) The output of the checkout operation
1084 quiet = (not options.verbose)
1085 checkout_args = ['checkout']
1087 checkout_args.append('--force')
1089 checkout_args.append('--quiet')
1090 checkout_args.append(ref)
1091 return self._Capture(checkout_args)
1093 def _Fetch(self, options, remote=None, prune=False, quiet=False):
1094 cfg = gclient_utils.DefaultIndexPackConfig(self.url)
1097 remote or self.remote,
1101 fetch_cmd.append('--prune')
1103 fetch_cmd.append('--verbose')
1105 fetch_cmd.append('--quiet')
1106 self._Run(fetch_cmd, options, show_header=options.verbose, retry=True)
1108 # Return the revision that was fetched; this will be stored in 'FETCH_HEAD'
1109 return self._Capture(['rev-parse', '--verify', 'FETCH_HEAD'])
1111 def _UpdateBranchHeads(self, options, fetch=False):
1112 """Adds, and optionally fetches, "branch-heads" and "tags" refspecs
1115 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
1116 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
1117 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1118 '^\\+refs/branch-heads/\\*:.*$']
1119 self._Run(config_cmd, options)
1121 if hasattr(options, 'with_tags') and options.with_tags:
1122 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
1123 '+refs/tags/*:refs/tags/*',
1124 '^\\+refs/tags/\\*:.*$']
1125 self._Run(config_cmd, options)
1127 if fetch and need_fetch:
1128 self._Fetch(options)
1130 def _Run(self, args, options, show_header=True, **kwargs):
1131 # Disable 'unused options' warning | pylint: disable=W0613
1132 kwargs.setdefault('cwd', self.checkout_path)
1133 kwargs.setdefault('stdout', self.out_fh)
1134 kwargs['filter_fn'] = self.filter
1135 kwargs.setdefault('print_stdout', False)
1136 env = scm.GIT.ApplyEnvVars(kwargs)
1137 cmd = ['git'] + args
1139 gclient_utils.CheckCallAndFilterAndHeader(cmd, env=env, **kwargs)
1141 gclient_utils.CheckCallAndFilter(cmd, env=env, **kwargs)
1144 class SVNWrapper(SCMWrapper):
1145 """ Wrapper for SVN """
1150 """Returns true if the command exists."""
1152 result, version = scm.SVN.AssertVersion('1.4')
1154 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1159 def GetCheckoutRoot(self):
1160 return scm.SVN.GetCheckoutRoot(self.checkout_path)
1162 def GetRevisionDate(self, revision):
1163 """Returns the given revision's date in ISO-8601 format (which contains the
1165 date = scm.SVN.Capture(
1166 ['propget', '--revprop', 'svn:date', '-r', revision],
1167 os.path.join(self.checkout_path, '.'))
1170 def cleanup(self, options, args, _file_list):
1171 """Cleanup working copy."""
1172 self._Run(['cleanup'] + args, options)
1174 def diff(self, options, args, _file_list):
1175 # NOTE: This function does not currently modify file_list.
1176 if not os.path.isdir(self.checkout_path):
1177 raise gclient_utils.Error('Directory %s is not present.' %
1179 self._Run(['diff'] + args, options)
1181 def pack(self, _options, args, _file_list):
1182 """Generates a patch file which can be applied to the root of the
1184 if not os.path.isdir(self.checkout_path):
1185 raise gclient_utils.Error('Directory %s is not present.' %
1187 gclient_utils.CheckCallAndFilter(
1188 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1189 cwd=self.checkout_path,
1191 filter_fn=SvnDiffFilterer(self.relpath, print_func=self.Print).Filter)
1193 def update(self, options, args, file_list):
1194 """Runs svn to update or transparently checkout the working copy.
1196 All updated files will be appended to file_list.
1199 Error: if can't get URL for relative path.
1201 # Only update if hg is not controlling the directory.
1202 hg_path = os.path.join(self.checkout_path, '.hg')
1203 if os.path.exists(hg_path):
1204 self.Print('________ found .hg directory; skipping %s' % self.relpath)
1208 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1210 # revision is the revision to match. It is None if no revision is specified,
1211 # i.e. the 'deps ain't pinned'.
1212 url, revision = gclient_utils.SplitUrlRevision(self.url)
1213 # Keep the original unpinned url for reference in case the repo is switched.
1216 if options.revision:
1217 # Override the revision number.
1218 revision = str(options.revision)
1220 if revision != 'unmanaged':
1221 forced_revision = True
1222 # Reconstruct the url.
1223 url = '%s@%s' % (url, revision)
1224 rev_str = ' at %s' % revision
1229 forced_revision = False
1232 exists = os.path.exists(self.checkout_path)
1233 if exists and managed:
1234 # Git is only okay if it's a git-svn checkout of the right repo.
1235 if scm.GIT.IsGitSvn(self.checkout_path):
1236 remote_url = scm.GIT.Capture(['config', '--local', '--get',
1237 'svn-remote.svn.url'],
1238 cwd=self.checkout_path).rstrip()
1239 if remote_url.rstrip('/') == base_url.rstrip('/'):
1240 self.Print('\n_____ %s looks like a git-svn checkout. Skipping.'
1242 return # TODO(borenet): Get the svn revision number?
1244 # Get the existing scm url and the revision number of the current checkout.
1245 if exists and managed:
1247 from_info = scm.SVN.CaptureLocalInfo(
1248 [], os.path.join(self.checkout_path, '.'))
1249 except (gclient_utils.Error, subprocess2.CalledProcessError):
1250 self._DeleteOrMove(options.force)
1254 '/chrome/trunk/src': 'gs://chromium-svn-checkout/chrome/',
1255 '/blink/trunk': 'gs://chromium-svn-checkout/blink/',
1257 WHITELISTED_ROOTS = [
1258 'svn://svn.chromium.org',
1259 'svn://svn-mirror.golo.chromium.org',
1263 # Split out the revision number since it's not useful for us.
1264 base_path = urlparse.urlparse(url).path.split('@')[0]
1265 # Check to see if we're on a whitelisted root. We do this because
1266 # only some svn servers have matching UUIDs.
1267 local_parsed = urlparse.urlparse(url)
1268 local_root = '%s://%s' % (local_parsed.scheme, local_parsed.netloc)
1269 if ('CHROME_HEADLESS' in os.environ
1270 and sys.platform == 'linux2' # TODO(hinoka): Enable for win/mac.
1271 and base_path in BASE_URLS
1272 and local_root in WHITELISTED_ROOTS):
1274 # Use a tarball for initial sync if we are on a bot.
1275 # Get an unauthenticated gsutil instance.
1276 gsutil = download_from_google_storage.Gsutil(
1277 GSUTIL_DEFAULT_PATH, boto_path=os.devnull)
1279 gs_path = BASE_URLS[base_path]
1280 _, out, _ = gsutil.check_call('ls', gs_path)
1281 # So that we can get the most recent revision.
1282 sorted_items = sorted(out.splitlines())
1283 latest_checkout = sorted_items[-1]
1285 tempdir = tempfile.mkdtemp()
1286 self.Print('Downloading %s...' % latest_checkout)
1287 code, out, err = gsutil.check_call('cp', latest_checkout, tempdir)
1289 self.Print('%s\n%s' % (out, err))
1291 filename = latest_checkout.split('/')[-1]
1292 tarball = os.path.join(tempdir, filename)
1293 self.Print('Unpacking into %s...' % self.checkout_path)
1294 gclient_utils.safe_makedirs(self.checkout_path)
1295 # TODO(hinoka): Use 7z for windows.
1296 cmd = ['tar', '--extract', '--ungzip',
1297 '--directory', self.checkout_path,
1299 gclient_utils.CheckCallAndFilter(
1300 cmd, stdout=sys.stdout, print_stdout=True)
1302 self.Print('Deleting temp file')
1303 gclient_utils.rmtree(tempdir)
1305 # Rewrite the repository root to match.
1306 tarball_url = scm.SVN.CaptureLocalInfo(
1307 ['.'], self.checkout_path)['Repository Root']
1308 tarball_parsed = urlparse.urlparse(tarball_url)
1309 tarball_root = '%s://%s' % (tarball_parsed.scheme,
1310 tarball_parsed.netloc)
1312 if tarball_root != local_root:
1313 self.Print('Switching repository root to %s' % local_root)
1314 self._Run(['switch', '--relocate', tarball_root,
1315 local_root, self.checkout_path],
1317 except Exception as e:
1318 self.Print('We tried to get a source tarball but failed.')
1319 self.Print('Resuming normal operations.')
1322 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
1323 # We need to checkout.
1324 command = ['checkout', url, self.checkout_path]
1325 command = self._AddAdditionalUpdateFlags(command, options, revision)
1326 self._RunAndGetFileList(command, options, file_list, self._root_dir)
1327 return self.Svnversion()
1330 self.Print(('________ unmanaged solution; skipping %s' % self.relpath))
1331 if os.path.exists(os.path.join(self.checkout_path, '.svn')):
1332 return self.Svnversion()
1335 if 'URL' not in from_info:
1336 raise gclient_utils.Error(
1337 ('gclient is confused. Couldn\'t get the url for %s.\n'
1338 'Try using @unmanaged.\n%s') % (
1339 self.checkout_path, from_info))
1341 # Look for locked directories.
1342 dir_info = scm.SVN.CaptureStatus(
1343 None, os.path.join(self.checkout_path, '.'))
1344 if any(d[0][2] == 'L' for d in dir_info):
1346 self._Run(['cleanup', self.checkout_path], options)
1347 except subprocess2.CalledProcessError, e:
1348 # Get the status again, svn cleanup may have cleaned up at least
1350 dir_info = scm.SVN.CaptureStatus(
1351 None, os.path.join(self.checkout_path, '.'))
1353 # Try to fix the failures by removing troublesome files.
1356 if d[0][0] == '!' and options.force:
1357 # We don't pass any files/directories to CaptureStatus and set
1358 # cwd=self.checkout_path, so we should get relative paths here.
1359 assert not os.path.isabs(d[1])
1360 path_to_remove = os.path.normpath(
1361 os.path.join(self.checkout_path, d[1]))
1362 self.Print('Removing troublesome path %s' % path_to_remove)
1363 gclient_utils.rmtree(path_to_remove)
1366 'Not removing troublesome path %s automatically.' % d[1])
1368 self.Print('You can pass --force to enable automatic removal.')
1371 # Retrieve the current HEAD version because svn is slow at null updates.
1372 if options.manually_grab_svn_rev and not revision:
1373 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
1374 revision = str(from_info_live['Revision'])
1375 rev_str = ' at %s' % revision
1377 if from_info['URL'].rstrip('/') != base_url.rstrip('/'):
1378 # The repository url changed, need to switch.
1380 to_info = scm.SVN.CaptureRemoteInfo(url)
1381 except (gclient_utils.Error, subprocess2.CalledProcessError):
1382 # The url is invalid or the server is not accessible, it's safer to bail
1384 raise gclient_utils.Error('This url is unreachable: %s' % url)
1385 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1386 and (from_info['UUID'] == to_info['UUID']))
1388 self.Print('_____ relocating %s to a new checkout' % self.relpath)
1389 # We have different roots, so check if we can switch --relocate.
1390 # Subversion only permits this if the repository UUIDs match.
1391 # Perform the switch --relocate, then rewrite the from_url
1392 # to reflect where we "are now." (This is the same way that
1393 # Subversion itself handles the metadata when switch --relocate
1394 # is used.) This makes the checks below for whether we
1395 # can update to a revision or have to switch to a different
1396 # branch work as expected.
1397 # TODO(maruel): TEST ME !
1398 command = ['switch', '--relocate',
1399 from_info['Repository Root'],
1400 to_info['Repository Root'],
1402 self._Run(command, options, cwd=self._root_dir)
1403 from_info['URL'] = from_info['URL'].replace(
1404 from_info['Repository Root'],
1405 to_info['Repository Root'])
1407 if not options.force and not options.reset:
1408 # Look for local modifications but ignore unversioned files.
1409 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1410 if status[0][0] != '?':
1411 raise gclient_utils.Error(
1412 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1413 'there is local changes in %s. Delete the directory and '
1414 'try again.') % (url, self.checkout_path))
1416 self.Print('_____ switching %s to a new checkout' % self.relpath)
1417 gclient_utils.rmtree(self.checkout_path)
1418 # We need to checkout.
1419 command = ['checkout', url, self.checkout_path]
1420 command = self._AddAdditionalUpdateFlags(command, options, revision)
1421 self._RunAndGetFileList(command, options, file_list, self._root_dir)
1422 return self.Svnversion()
1424 # If the provided url has a revision number that matches the revision
1425 # number of the existing directory, then we don't need to bother updating.
1426 if not options.force and str(from_info['Revision']) == revision:
1427 if options.verbose or not forced_revision:
1428 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
1430 command = ['update', self.checkout_path]
1431 command = self._AddAdditionalUpdateFlags(command, options, revision)
1432 self._RunAndGetFileList(command, options, file_list, self._root_dir)
1434 # If --reset and --delete_unversioned_trees are specified, remove any
1435 # untracked files and directories.
1436 if options.reset and options.delete_unversioned_trees:
1437 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1438 full_path = os.path.join(self.checkout_path, status[1])
1439 if (status[0][0] == '?'
1440 and os.path.isdir(full_path)
1441 and not os.path.islink(full_path)):
1442 self.Print('_____ removing unversioned directory %s' % status[1])
1443 gclient_utils.rmtree(full_path)
1444 return self.Svnversion()
1446 def updatesingle(self, options, args, file_list):
1447 filename = args.pop()
1448 if scm.SVN.AssertVersion("1.5")[0]:
1449 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
1450 # Create an empty checkout and then update the one file we want. Future
1451 # operations will only apply to the one file we checked out.
1452 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
1453 self._Run(command, options, cwd=self._root_dir)
1454 if os.path.exists(os.path.join(self.checkout_path, filename)):
1455 os.remove(os.path.join(self.checkout_path, filename))
1456 command = ["update", filename]
1457 self._RunAndGetFileList(command, options, file_list)
1458 # After the initial checkout, we can use update as if it were any other
1460 self.update(options, args, file_list)
1462 # If the installed version of SVN doesn't support --depth, fallback to
1463 # just exporting the file. This has the downside that revision
1464 # information is not stored next to the file, so we will have to
1465 # re-export the file every time we sync.
1466 if not os.path.exists(self.checkout_path):
1467 gclient_utils.safe_makedirs(self.checkout_path)
1468 command = ["export", os.path.join(self.url, filename),
1469 os.path.join(self.checkout_path, filename)]
1470 command = self._AddAdditionalUpdateFlags(command, options,
1472 self._Run(command, options, cwd=self._root_dir)
1474 def revert(self, options, _args, file_list):
1475 """Reverts local modifications. Subversion specific.
1477 All reverted files will be appended to file_list, even if Subversion
1478 doesn't know about them.
1480 if not os.path.isdir(self.checkout_path):
1481 if os.path.exists(self.checkout_path):
1482 gclient_utils.rmtree(self.checkout_path)
1483 # svn revert won't work if the directory doesn't exist. It needs to
1485 self.Print('_____ %s is missing, synching instead' % self.relpath)
1486 # Don't reuse the args.
1487 return self.update(options, [], file_list)
1489 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1490 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1491 self.Print('________ found .git directory; skipping %s' % self.relpath)
1493 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1494 self.Print('________ found .hg directory; skipping %s' % self.relpath)
1496 if not options.force:
1497 raise gclient_utils.Error('Invalid checkout path, aborting')
1499 '\n_____ %s is not a valid svn checkout, synching instead' %
1501 gclient_utils.rmtree(self.checkout_path)
1502 # Don't reuse the args.
1503 return self.update(options, [], file_list)
1505 def printcb(file_status):
1506 if file_list is not None:
1507 file_list.append(file_status[1])
1508 if logging.getLogger().isEnabledFor(logging.INFO):
1509 logging.info('%s%s' % (file_status[0], file_status[1]))
1511 self.Print(os.path.join(self.checkout_path, file_status[1]))
1512 scm.SVN.Revert(self.checkout_path, callback=printcb)
1514 # Revert() may delete the directory altogether.
1515 if not os.path.isdir(self.checkout_path):
1516 # Don't reuse the args.
1517 return self.update(options, [], file_list)
1520 # svn revert is so broken we don't even use it. Using
1521 # "svn up --revision BASE" achieve the same effect.
1522 # file_list will contain duplicates.
1523 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1526 # Maybe the directory disapeared meanwhile. Do not throw an exception.
1527 logging.error('Failed to update:\n%s' % str(e))
1529 def revinfo(self, _options, _args, _file_list):
1530 """Display revision"""
1532 return scm.SVN.CaptureRevision(self.checkout_path)
1533 except (gclient_utils.Error, subprocess2.CalledProcessError):
1536 def runhooks(self, options, args, file_list):
1537 self.status(options, args, file_list)
1539 def status(self, options, args, file_list):
1540 """Display status information."""
1541 command = ['status'] + args
1542 if not os.path.isdir(self.checkout_path):
1543 # svn status won't work if the directory doesn't exist.
1544 self.Print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1545 'The directory does not exist.') %
1546 (' '.join(command), self.checkout_path))
1547 # There's no file list to retrieve.
1549 self._RunAndGetFileList(command, options, file_list)
1551 def GetUsableRev(self, rev, _options):
1552 """Verifies the validity of the revision for this repository."""
1553 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1554 raise gclient_utils.Error(
1555 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1559 def FullUrlForRelativeUrl(self, url):
1560 # Find the forth '/' and strip from there. A bit hackish.
1561 return '/'.join(self.url.split('/')[:4]) + url
1563 def _Run(self, args, options, **kwargs):
1564 """Runs a commands that goes to stdout."""
1565 kwargs.setdefault('cwd', self.checkout_path)
1566 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
1567 always=options.verbose, **kwargs)
1569 def Svnversion(self):
1570 """Runs the lowest checked out revision in the current project."""
1571 info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1572 return info['Revision']
1574 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1575 """Runs a commands that goes to stdout and grabs the file listed."""
1576 cwd = cwd or self.checkout_path
1577 scm.SVN.RunAndGetFileList(
1579 args + ['--ignore-externals'],
1581 file_list=file_list)
1584 def _AddAdditionalUpdateFlags(command, options, revision):
1585 """Add additional flags to command depending on what options are set.
1586 command should be a list of strings that represents an svn command.
1588 This method returns a new list to be used as a command."""
1589 new_command = command[:]
1591 new_command.extend(['--revision', str(revision).strip()])
1592 # We don't want interaction when jobs are used.
1593 if options.jobs > 1:
1594 new_command.append('--non-interactive')
1595 # --force was added to 'svn update' in svn 1.5.
1596 # --accept was added to 'svn update' in svn 1.6.
1597 if not scm.SVN.AssertVersion('1.5')[0]:
1600 # It's annoying to have it block in the middle of a sync, just sensible
1603 new_command.append('--force')
1604 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1605 new_command.extend(('--accept', 'theirs-conflict'))
1606 elif options.manually_grab_svn_rev:
1607 new_command.append('--force')
1608 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1609 new_command.extend(('--accept', 'postpone'))
1610 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1611 new_command.extend(('--accept', 'postpone'))