blob: 151fe147b4e2f54d059901c21c3d553aa12b4d85 [file] [log] [blame]
[email protected]93567042012-02-15 01:02:261# Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]5aeb7dd2009-11-17 18:09:012# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
[email protected]5f3eee32009-09-17 00:34:304
[email protected]d5800f12009-11-12 20:03:435"""Gclient-specific SCM-specific operations."""
[email protected]5f3eee32009-09-17 00:34:306
[email protected]754960e2009-09-21 12:31:057import logging
[email protected]5f3eee32009-09-17 00:34:308import os
[email protected]ee4071d2009-12-22 22:25:379import posixpath
[email protected]5f3eee32009-09-17 00:34:3010import re
[email protected]90541732011-04-01 17:54:1811import sys
[email protected]3534aa52013-07-20 01:58:0812import tempfile
[email protected]6279e8a2014-02-13 01:45:2513import traceback
[email protected]2f2ca142014-01-07 03:59:1814import urlparse
[email protected]5f3eee32009-09-17 00:34:3015
[email protected]2f2ca142014-01-07 03:59:1816import download_from_google_storage
[email protected]5f3eee32009-09-17 00:34:3017import gclient_utils
[email protected]31cb48a2011-04-04 18:01:3618import scm
19import subprocess2
[email protected]5f3eee32009-09-17 00:34:3020
21
[email protected]71cbb502013-04-19 23:30:1522THIS_FILE_PATH = os.path.abspath(__file__)
23
[email protected]2f2ca142014-01-07 03:59:1824GSUTIL_DEFAULT_PATH = os.path.join(
25 os.path.dirname(os.path.abspath(__file__)),
26 'third_party', 'gsutil', 'gsutil')
27
[email protected]71cbb502013-04-19 23:30:1528
[email protected]306080c2012-05-04 13:11:2929class DiffFiltererWrapper(object):
30 """Simple base class which tracks which file is being diffed and
[email protected]ee4071d2009-12-22 22:25:3731 replaces instances of its file name in the original and
[email protected]d6504212010-01-13 17:34:3132 working copy lines of the svn/git diff output."""
[email protected]306080c2012-05-04 13:11:2933 index_string = None
[email protected]ee4071d2009-12-22 22:25:3734 original_prefix = "--- "
35 working_prefix = "+++ "
36
[email protected]77e4eca2010-09-21 13:23:0737 def __init__(self, relpath):
[email protected]ee4071d2009-12-22 22:25:3738 # Note that we always use '/' as the path separator to be
39 # consistent with svn's cygwin-style output on Windows
40 self._relpath = relpath.replace("\\", "/")
[email protected]306080c2012-05-04 13:11:2941 self._current_file = None
[email protected]ee4071d2009-12-22 22:25:3742
[email protected]6e29d572010-06-04 17:32:2043 def SetCurrentFile(self, current_file):
44 self._current_file = current_file
[email protected]306080c2012-05-04 13:11:2945
[email protected]3830a672013-02-19 20:15:1446 @property
47 def _replacement_file(self):
[email protected]306080c2012-05-04 13:11:2948 return posixpath.join(self._relpath, self._current_file)
[email protected]ee4071d2009-12-22 22:25:3749
[email protected]f5d37bf2010-09-02 00:50:3450 def _Replace(self, line):
51 return line.replace(self._current_file, self._replacement_file)
[email protected]ee4071d2009-12-22 22:25:3752
53 def Filter(self, line):
54 if (line.startswith(self.index_string)):
55 self.SetCurrentFile(line[len(self.index_string):])
[email protected]f5d37bf2010-09-02 00:50:3456 line = self._Replace(line)
[email protected]ee4071d2009-12-22 22:25:3757 else:
58 if (line.startswith(self.original_prefix) or
59 line.startswith(self.working_prefix)):
[email protected]f5d37bf2010-09-02 00:50:3460 line = self._Replace(line)
[email protected]77e4eca2010-09-21 13:23:0761 print(line)
[email protected]ee4071d2009-12-22 22:25:3762
63
[email protected]306080c2012-05-04 13:11:2964class SvnDiffFilterer(DiffFiltererWrapper):
65 index_string = "Index: "
66
67
68class GitDiffFilterer(DiffFiltererWrapper):
69 index_string = "diff --git "
70
71 def SetCurrentFile(self, current_file):
72 # Get filename by parsing "a/<filename> b/<filename>"
73 self._current_file = current_file[:(len(current_file)/2)][2:]
74
75 def _Replace(self, line):
76 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
77
78
[email protected]5f3eee32009-09-17 00:34:3079### SCM abstraction layer
80
[email protected]cb5442b2009-09-22 16:51:2481# Factory Method for SCM wrapper creation
82
[email protected]9eda4112010-06-11 18:56:1083def GetScmName(url):
84 if url:
85 url, _ = gclient_utils.SplitUrlRevision(url)
86 if (url.startswith('git://') or url.startswith('ssh://') or
[email protected]4e075672011-11-21 16:35:0887 url.startswith('git+http://') or url.startswith('git+https://') or
[email protected]a2ede5c2014-02-05 22:05:1788 url.endswith('.git') or url.startswith('sso://')):
[email protected]9eda4112010-06-11 18:56:1089 return 'git'
[email protected]b74dca22010-06-11 20:10:4090 elif (url.startswith('http://') or url.startswith('https://') or
[email protected]54a07a22010-06-14 19:07:3991 url.startswith('svn://') or url.startswith('svn+ssh://')):
[email protected]9eda4112010-06-11 18:56:1092 return 'svn'
93 return None
94
95
96def CreateSCM(url, root_dir=None, relpath=None):
97 SCM_MAP = {
[email protected]cb5442b2009-09-22 16:51:2498 'svn' : SVNWrapper,
[email protected]e28e4982009-09-25 20:51:4599 'git' : GitWrapper,
[email protected]cb5442b2009-09-22 16:51:24100 }
[email protected]e28e4982009-09-25 20:51:45101
[email protected]9eda4112010-06-11 18:56:10102 scm_name = GetScmName(url)
103 if not scm_name in SCM_MAP:
104 raise gclient_utils.Error('No SCM found for url %s' % url)
[email protected]9e3e82c2012-04-18 12:55:43105 scm_class = SCM_MAP[scm_name]
106 if not scm_class.BinaryExists():
107 raise gclient_utils.Error('%s command not found' % scm_name)
108 return scm_class(url, root_dir, relpath)
[email protected]cb5442b2009-09-22 16:51:24109
110
111# SCMWrapper base class
112
[email protected]5f3eee32009-09-17 00:34:30113class SCMWrapper(object):
114 """Add necessary glue between all the supported SCM.
115
[email protected]d6504212010-01-13 17:34:31116 This is the abstraction layer to bind to different SCM.
117 """
[email protected]9eda4112010-06-11 18:56:10118 def __init__(self, url=None, root_dir=None, relpath=None):
[email protected]5f3eee32009-09-17 00:34:30119 self.url = url
[email protected]5e73b0c2009-09-18 19:47:48120 self._root_dir = root_dir
121 if self._root_dir:
122 self._root_dir = self._root_dir.replace('/', os.sep)
123 self.relpath = relpath
124 if self.relpath:
125 self.relpath = self.relpath.replace('/', os.sep)
[email protected]e28e4982009-09-25 20:51:45126 if self.relpath and self._root_dir:
127 self.checkout_path = os.path.join(self._root_dir, self.relpath)
[email protected]5f3eee32009-09-17 00:34:30128
[email protected]5f3eee32009-09-17 00:34:30129 def RunCommand(self, command, options, args, file_list=None):
[email protected]6e043f72011-05-02 07:24:32130 commands = ['cleanup', 'update', 'updatesingle', 'revert',
[email protected]4b5b1772010-04-08 01:52:56131 'revinfo', 'status', 'diff', 'pack', 'runhooks']
[email protected]5f3eee32009-09-17 00:34:30132
133 if not command in commands:
134 raise gclient_utils.Error('Unknown command %s' % command)
135
[email protected]cb5442b2009-09-22 16:51:24136 if not command in dir(self):
[email protected]ee4071d2009-12-22 22:25:37137 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
[email protected]9eda4112010-06-11 18:56:10138 command, self.__class__.__name__))
[email protected]cb5442b2009-09-22 16:51:24139
140 return getattr(self, command)(options, args, file_list)
141
142
[email protected]55e724e2010-03-11 19:36:49143class GitWrapper(SCMWrapper):
[email protected]e28e4982009-09-25 20:51:45144 """Wrapper for Git"""
[email protected]2702bcd2013-09-24 19:10:07145 name = 'git'
[email protected]1a60dca2013-11-26 14:06:26146 remote = 'origin'
[email protected]e28e4982009-09-25 20:51:45147
[email protected]53456aa2013-07-03 19:38:34148 cache_dir = None
[email protected]53456aa2013-07-03 19:38:34149
[email protected]4e075672011-11-21 16:35:08150 def __init__(self, url=None, root_dir=None, relpath=None):
151 """Removes 'git+' fake prefix from git URL."""
152 if url.startswith('git+http://') or url.startswith('git+https://'):
153 url = url[4:]
154 SCMWrapper.__init__(self, url, root_dir, relpath)
155
[email protected]9e3e82c2012-04-18 12:55:43156 @staticmethod
157 def BinaryExists():
158 """Returns true if the command exists."""
159 try:
160 # We assume git is newer than 1.7. See: crbug.com/114483
161 result, version = scm.GIT.AssertVersion('1.7')
162 if not result:
163 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
164 return result
165 except OSError:
166 return False
167
[email protected]885a9602013-05-31 09:54:40168 def GetCheckoutRoot(self):
169 return scm.GIT.GetCheckoutRoot(self.checkout_path)
170
[email protected]396e1a62013-07-03 19:41:04171 def GetRevisionDate(self, _revision):
[email protected]eaab7842011-04-28 09:07:58172 """Returns the given revision's date in ISO-8601 format (which contains the
173 time zone)."""
174 # TODO(floitsch): get the time-stamp of the given revision and not just the
175 # time-stamp of the currently checked out revision.
176 return self._Capture(['log', '-n', '1', '--format=%ai'])
177
[email protected]6e29d572010-06-04 17:32:20178 @staticmethod
179 def cleanup(options, args, file_list):
[email protected]d8a63782010-01-25 17:47:05180 """'Cleanup' the repo.
181
182 There's no real git equivalent for the svn cleanup command, do a no-op.
183 """
[email protected]e28e4982009-09-25 20:51:45184
[email protected]396e1a62013-07-03 19:41:04185 def diff(self, options, _args, _file_list):
[email protected]1a60dca2013-11-26 14:06:26186 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
[email protected]37e89872010-09-07 16:11:33187 self._Run(['diff', merge_base], options)
[email protected]e28e4982009-09-25 20:51:45188
[email protected]396e1a62013-07-03 19:41:04189 def pack(self, _options, _args, _file_list):
[email protected]ee4071d2009-12-22 22:25:37190 """Generates a patch file which can be applied to the root of the
[email protected]d6504212010-01-13 17:34:31191 repository.
192
193 The patch file is generated from a diff of the merge base of HEAD and
194 its upstream branch.
195 """
[email protected]1a60dca2013-11-26 14:06:26196 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
[email protected]17d01792010-09-01 18:07:10197 gclient_utils.CheckCallAndFilter(
[email protected]8469bf92010-09-03 19:03:15198 ['git', 'diff', merge_base],
199 cwd=self.checkout_path,
[email protected]306080c2012-05-04 13:11:29200 filter_fn=GitDiffFilterer(self.relpath).Filter)
[email protected]ee4071d2009-12-22 22:25:37201
[email protected]d4af6622012-06-04 22:13:55202 def UpdateSubmoduleConfig(self):
203 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
[email protected]37e4f232012-06-21 21:47:42204 'submodule.$name.ignore', 'all']
[email protected]d4af6622012-06-04 22:13:55205 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
[email protected]78f5c162012-06-22 22:34:25206 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
[email protected]987b0612012-07-09 23:41:08207 cmd3 = ['git', 'config', 'branch.autosetupmerge']
[email protected]08b21bf2013-04-05 03:38:10208 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
[email protected]987b0612012-07-09 23:41:08209 kwargs = {'cwd': self.checkout_path,
210 'print_stdout': False,
211 'filter_fn': lambda x: None}
[email protected]d4af6622012-06-04 22:13:55212 try:
[email protected]987b0612012-07-09 23:41:08213 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
214 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
[email protected]d4af6622012-06-04 22:13:55215 except subprocess2.CalledProcessError:
216 # Not a fatal error, or even very interesting in a non-git-submodule
217 # world. So just keep it quiet.
218 pass
[email protected]987b0612012-07-09 23:41:08219 try:
220 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
221 except subprocess2.CalledProcessError:
222 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
[email protected]d4af6622012-06-04 22:13:55223
[email protected]08b21bf2013-04-05 03:38:10224 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
225
[email protected]50fd47f2014-02-13 01:03:19226 def _FetchAndReset(self, revision, file_list, options):
227 """Equivalent to git fetch; git reset."""
228 quiet = []
229 if not options.verbose:
230 quiet = ['--quiet']
231 self._UpdateBranchHeads(options, fetch=False)
232
233 fetch_cmd = [
234 '-c', 'core.deltaBaseCacheLimit=2g', 'fetch', self.remote, '--prune']
235 self._Run(fetch_cmd + quiet, options, retry=True)
236 self._Run(['reset', '--hard', revision] + quiet, options)
237 self.UpdateSubmoduleConfig()
238 if file_list is not None:
239 files = self._Capture(['ls-files']).splitlines()
240 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
241
[email protected]e28e4982009-09-25 20:51:45242 def update(self, options, args, file_list):
243 """Runs git to update or transparently checkout the working copy.
244
245 All updated files will be appended to file_list.
246
247 Raises:
248 Error: if can't get URL for relative path.
249 """
[email protected]e28e4982009-09-25 20:51:45250 if args:
251 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
252
[email protected]ece406f2010-02-23 17:29:15253 self._CheckMinVersion("1.6.6")
[email protected]923a0372009-12-11 20:42:43254
[email protected]1a60dca2013-11-26 14:06:26255 # If a dependency is not pinned, track the default remote branch.
256 default_rev = 'refs/remotes/%s/master' % self.remote
[email protected]7080e942010-03-15 15:06:16257 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]ac915bb2009-11-13 17:03:01258 rev_str = ""
[email protected]7080e942010-03-15 15:06:16259 revision = deps_revision
[email protected]eb2756d2011-09-20 20:17:51260 managed = True
[email protected]e28e4982009-09-25 20:51:45261 if options.revision:
[email protected]ac915bb2009-11-13 17:03:01262 # Override the revision number.
263 revision = str(options.revision)
[email protected]eb2756d2011-09-20 20:17:51264 if revision == 'unmanaged':
265 revision = None
266 managed = False
[email protected]d90ba3f2010-02-23 14:42:57267 if not revision:
268 revision = default_rev
[email protected]e28e4982009-09-25 20:51:45269
[email protected]eaab7842011-04-28 09:07:58270 if gclient_utils.IsDateRevision(revision):
271 # Date-revisions only work on git-repositories if the reflog hasn't
272 # expired yet. Use rev-list to get the corresponding revision.
273 # git rev-list -n 1 --before='time-stamp' branchname
274 if options.transitive:
275 print('Warning: --transitive only works for SVN repositories.')
276 revision = default_rev
277
[email protected]d90ba3f2010-02-23 14:42:57278 rev_str = ' at %s' % revision
[email protected]396e1a62013-07-03 19:41:04279 files = [] if file_list is not None else None
[email protected]d90ba3f2010-02-23 14:42:57280
281 printed_path = False
282 verbose = []
[email protected]b1a22bf2009-11-07 02:33:50283 if options.verbose:
[email protected]77e4eca2010-09-21 13:23:07284 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57285 verbose = ['--verbose']
286 printed_path = True
287
[email protected]53456aa2013-07-03 19:38:34288 url = self._CreateOrUpdateCache(url, options)
289
[email protected]a41249c2013-07-03 00:09:12290 if revision.startswith('refs/'):
[email protected]d90ba3f2010-02-23 14:42:57291 rev_type = "branch"
[email protected]1a60dca2013-11-26 14:06:26292 elif revision.startswith(self.remote + '/'):
293 # For compatibility with old naming, translate 'origin' to 'refs/heads'
294 revision = revision.replace(self.remote + '/', 'refs/heads/')
[email protected]d90ba3f2010-02-23 14:42:57295 rev_type = "branch"
296 else:
297 # hash is also a tag, only make a distinction at checkout
298 rev_type = "hash"
299
[email protected]6c2b49d2014-02-26 23:57:38300 if (not os.path.exists(self.checkout_path) or
301 (os.path.isdir(self.checkout_path) and
302 not os.path.exists(os.path.join(self.checkout_path, '.git')))):
[email protected]7ff04292014-03-10 12:57:25303 if (os.path.isdir(self.checkout_path) and
304 not os.path.exists(os.path.join(self.checkout_path, '.git'))):
305 if options.force:
306 # Delete and re-sync.
307 print('_____ Conflicting directory found in %s. Removing.'
308 % self.checkout_path)
309 gclient_utils.rmtree(self.checkout_path)
310 else:
311 raise gclient_utils.Error('\n____ %s%s\n'
312 '\tPath is not a git repo. No .git dir.\n'
313 '\tTo resolve:\n'
314 '\t\trm -rf %s\n'
315 '\tAnd run gclient sync again\n'
316 '\tOr run with --force\n'
317 % (self.relpath, rev_str, self.relpath))
[email protected]f5d37bf2010-09-02 00:50:34318 self._Clone(revision, url, options)
[email protected]d4af6622012-06-04 22:13:55319 self.UpdateSubmoduleConfig()
[email protected]396e1a62013-07-03 19:41:04320 if file_list is not None:
321 files = self._Capture(['ls-files']).splitlines()
322 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]d90ba3f2010-02-23 14:42:57323 if not verbose:
324 # Make the output a little prettier. It's nice to have some whitespace
325 # between projects when cloning.
[email protected]77e4eca2010-09-21 13:23:07326 print('')
[email protected]2702bcd2013-09-24 19:10:07327 return self._Capture(['rev-parse', '--verify', 'HEAD'])
[email protected]e28e4982009-09-25 20:51:45328
[email protected]6c2b49d2014-02-26 23:57:38329 if not managed:
330 self._UpdateBranchHeads(options, fetch=False)
331 self.UpdateSubmoduleConfig()
332 print ('________ unmanaged solution; skipping %s' % self.relpath)
333 return self._Capture(['rev-parse', '--verify', 'HEAD'])
334
[email protected]6c2b49d2014-02-26 23:57:38335 # See if the url has changed (the unittests use git://foo for the url, let
336 # that through).
337 current_url = self._Capture(['config', 'remote.%s.url' % self.remote])
338 return_early = False
339 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
340 # unit test pass. (and update the comment above)
341 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
342 # This allows devs to use experimental repos which have a different url
343 # but whose branch(s) are the same as official repos.
[email protected]7ff04292014-03-10 12:57:25344 if (current_url.rstrip('/') != url.rstrip('/') and
[email protected]6c2b49d2014-02-26 23:57:38345 url != 'git://foo' and
346 subprocess2.capture(
347 ['git', 'config', 'remote.%s.gclient-auto-fix-url' % self.remote],
348 cwd=self.checkout_path).strip() != 'False'):
349 print('_____ switching %s to a new upstream' % self.relpath)
350 # Make sure it's clean
351 self._CheckClean(rev_str)
352 # Switch over to the new upstream
353 self._Run(['remote', 'set-url', self.remote, url], options)
354 self._FetchAndReset(revision, file_list, options)
355 return_early = True
356
[email protected]50fd47f2014-02-13 01:03:19357 if return_early:
358 return self._Capture(['rev-parse', '--verify', 'HEAD'])
359
[email protected]5bde4852009-12-14 16:47:12360 cur_branch = self._GetCurrentBranch()
361
[email protected]d90ba3f2010-02-23 14:42:57362 # Cases:
[email protected]786fb682010-06-02 15:16:23363 # 0) HEAD is detached. Probably from our initial clone.
364 # - make sure HEAD is contained by a named ref, then update.
365 # Cases 1-4. HEAD is a branch.
366 # 1) current branch is not tracking a remote branch (could be git-svn)
367 # - try to rebase onto the new hash or branch
368 # 2) current branch is tracking a remote branch with local committed
369 # changes, but the DEPS file switched to point to a hash
[email protected]d90ba3f2010-02-23 14:42:57370 # - rebase those changes on top of the hash
[email protected]786fb682010-06-02 15:16:23371 # 3) current branch is tracking a remote branch w/or w/out changes,
372 # no switch
[email protected]d90ba3f2010-02-23 14:42:57373 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
[email protected]786fb682010-06-02 15:16:23374 # 4) current branch is tracking a remote branch, switches to a different
375 # remote branch
[email protected]d90ba3f2010-02-23 14:42:57376 # - exit
377
[email protected]81e012c2010-04-29 16:07:24378 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
379 # a tracking branch
[email protected]d90ba3f2010-02-23 14:42:57380 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
381 # or it returns None if it couldn't find an upstream
[email protected]786fb682010-06-02 15:16:23382 if cur_branch is None:
383 upstream_branch = None
384 current_type = "detached"
385 logging.debug("Detached HEAD")
[email protected]d90ba3f2010-02-23 14:42:57386 else:
[email protected]786fb682010-06-02 15:16:23387 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
388 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
389 current_type = "hash"
390 logging.debug("Current branch is not tracking an upstream (remote)"
391 " branch.")
392 elif upstream_branch.startswith('refs/remotes'):
393 current_type = "branch"
394 else:
395 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
[email protected]d90ba3f2010-02-23 14:42:57396
[email protected]a41249c2013-07-03 00:09:12397 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
[email protected]cbd20a42012-06-27 13:49:27398 # Update the remotes first so we have all the refs.
[email protected]a41249c2013-07-03 00:09:12399 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
[email protected]cbd20a42012-06-27 13:49:27400 cwd=self.checkout_path)
[email protected]cbd20a42012-06-27 13:49:27401 if verbose:
[email protected]a41249c2013-07-03 00:09:12402 print(remote_output)
[email protected]d90ba3f2010-02-23 14:42:57403
[email protected]e409df62013-04-16 17:28:57404 self._UpdateBranchHeads(options, fetch=True)
405
[email protected]d90ba3f2010-02-23 14:42:57406 # This is a big hammer, debatable if it should even be here...
[email protected]793796d2010-02-19 17:27:41407 if options.force or options.reset:
[email protected]d4fffee2013-06-28 00:35:26408 target = 'HEAD'
409 if options.upstream and upstream_branch:
410 target = upstream_branch
411 self._Run(['reset', '--hard', target], options)
[email protected]d90ba3f2010-02-23 14:42:57412
[email protected]786fb682010-06-02 15:16:23413 if current_type == 'detached':
414 # case 0
415 self._CheckClean(rev_str)
[email protected]f5d37bf2010-09-02 00:50:34416 self._CheckDetachedHead(rev_str, options)
[email protected]f7826d72011-06-02 18:20:14417 self._Capture(['checkout', '--quiet', '%s' % revision])
[email protected]786fb682010-06-02 15:16:23418 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07419 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23420 elif current_type == 'hash':
[email protected]d90ba3f2010-02-23 14:42:57421 # case 1
[email protected]55e724e2010-03-11 19:36:49422 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
[email protected]d90ba3f2010-02-23 14:42:57423 # Our git-svn branch (upstream_branch) is our upstream
[email protected]f5d37bf2010-09-02 00:50:34424 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56425 newbase=revision, printed_path=printed_path,
426 merge=options.merge)
[email protected]d90ba3f2010-02-23 14:42:57427 printed_path = True
428 else:
429 # Can't find a merge-base since we don't know our upstream. That makes
430 # this command VERY likely to produce a rebase failure. For now we
431 # assume origin is our upstream since that's what the old behavior was.
[email protected]1a60dca2013-11-26 14:06:26432 upstream_branch = self.remote
[email protected]7080e942010-03-15 15:06:16433 if options.revision or deps_revision:
[email protected]3b29de12010-03-08 18:34:28434 upstream_branch = revision
[email protected]f5d37bf2010-09-02 00:50:34435 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56436 printed_path=printed_path, merge=options.merge)
[email protected]d90ba3f2010-02-23 14:42:57437 printed_path = True
[email protected]55e724e2010-03-11 19:36:49438 elif rev_type == 'hash':
[email protected]d90ba3f2010-02-23 14:42:57439 # case 2
[email protected]f5d37bf2010-09-02 00:50:34440 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56441 newbase=revision, printed_path=printed_path,
442 merge=options.merge)
[email protected]d90ba3f2010-02-23 14:42:57443 printed_path = True
[email protected]1a60dca2013-11-26 14:06:26444 elif revision.replace('heads', 'remotes/' + self.remote) != upstream_branch:
[email protected]d90ba3f2010-02-23 14:42:57445 # case 4
[email protected]1a60dca2013-11-26 14:06:26446 new_base = revision.replace('heads', 'remotes/' + self.remote)
[email protected]d90ba3f2010-02-23 14:42:57447 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07448 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57449 switch_error = ("Switching upstream branch from %s to %s\n"
450 % (upstream_branch, new_base) +
451 "Please merge or rebase manually:\n" +
452 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
453 "OR git checkout -b <some new branch> %s" % new_base)
454 raise gclient_utils.Error(switch_error)
455 else:
456 # case 3 - the default case
[email protected]396e1a62013-07-03 19:41:04457 if files is not None:
458 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
[email protected]d90ba3f2010-02-23 14:42:57459 if verbose:
[email protected]77e4eca2010-09-21 13:23:07460 print('Trying fast-forward merge to branch : %s' % upstream_branch)
[email protected]d90ba3f2010-02-23 14:42:57461 try:
[email protected]2aad1b22011-07-22 12:00:41462 merge_args = ['merge']
[email protected]30c46d62014-01-23 12:11:56463 if options.merge:
464 merge_args.append('--ff')
465 else:
[email protected]2aad1b22011-07-22 12:00:41466 merge_args.append('--ff-only')
467 merge_args.append(upstream_branch)
468 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
[email protected]18fa4542013-05-21 13:30:46469 except subprocess2.CalledProcessError as e:
[email protected]d90ba3f2010-02-23 14:42:57470 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
[email protected]30c46d62014-01-23 12:11:56471 files = []
[email protected]d90ba3f2010-02-23 14:42:57472 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07473 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57474 printed_path = True
475 while True:
476 try:
[email protected]30c46d62014-01-23 12:11:56477 action = self._AskForData(
478 'Cannot %s, attempt to rebase? '
479 '(y)es / (q)uit / (s)kip : ' %
480 ('merge' if options.merge else 'fast-forward merge'),
481 options)
[email protected]d90ba3f2010-02-23 14:42:57482 except ValueError:
[email protected]90541732011-04-01 17:54:18483 raise gclient_utils.Error('Invalid Character')
[email protected]d90ba3f2010-02-23 14:42:57484 if re.match(r'yes|y', action, re.I):
[email protected]f5d37bf2010-09-02 00:50:34485 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56486 printed_path=printed_path, merge=False)
[email protected]d90ba3f2010-02-23 14:42:57487 printed_path = True
488 break
489 elif re.match(r'quit|q', action, re.I):
490 raise gclient_utils.Error("Can't fast-forward, please merge or "
491 "rebase manually.\n"
492 "cd %s && git " % self.checkout_path
493 + "rebase %s" % upstream_branch)
494 elif re.match(r'skip|s', action, re.I):
[email protected]77e4eca2010-09-21 13:23:07495 print('Skipping %s' % self.relpath)
[email protected]d90ba3f2010-02-23 14:42:57496 return
497 else:
[email protected]77e4eca2010-09-21 13:23:07498 print('Input not recognized')
[email protected]d90ba3f2010-02-23 14:42:57499 elif re.match("error: Your local changes to '.*' would be "
500 "overwritten by merge. Aborting.\nPlease, commit your "
501 "changes or stash them before you can merge.\n",
502 e.stderr):
503 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07504 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57505 printed_path = True
506 raise gclient_utils.Error(e.stderr)
507 else:
508 # Some other problem happened with the merge
509 logging.error("Error during fast-forward merge in %s!" % self.relpath)
[email protected]77e4eca2010-09-21 13:23:07510 print(e.stderr)
[email protected]d90ba3f2010-02-23 14:42:57511 raise
512 else:
513 # Fast-forward merge was successful
514 if not re.match('Already up-to-date.', merge_output) or verbose:
515 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07516 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57517 printed_path = True
[email protected]77e4eca2010-09-21 13:23:07518 print(merge_output.strip())
[email protected]d90ba3f2010-02-23 14:42:57519 if not verbose:
520 # Make the output a little prettier. It's nice to have some
521 # whitespace between projects when syncing.
[email protected]77e4eca2010-09-21 13:23:07522 print('')
[email protected]d90ba3f2010-02-23 14:42:57523
[email protected]d4af6622012-06-04 22:13:55524 self.UpdateSubmoduleConfig()
[email protected]396e1a62013-07-03 19:41:04525 if file_list is not None:
526 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]5bde4852009-12-14 16:47:12527
528 # If the rebase generated a conflict, abort and ask user to fix
[email protected]786fb682010-06-02 15:16:23529 if self._IsRebasing():
[email protected]5bde4852009-12-14 16:47:12530 raise gclient_utils.Error('\n____ %s%s\n'
531 '\nConflict while rebasing this branch.\n'
532 'Fix the conflict and run gclient again.\n'
533 'See man git-rebase for details.\n'
534 % (self.relpath, rev_str))
535
[email protected]d90ba3f2010-02-23 14:42:57536 if verbose:
[email protected]77e4eca2010-09-21 13:23:07537 print('Checked out revision %s' % self.revinfo(options, (), None))
[email protected]e28e4982009-09-25 20:51:45538
[email protected]98e69452012-02-16 16:36:43539 # If --reset and --delete_unversioned_trees are specified, remove any
540 # untracked directories.
541 if options.reset and options.delete_unversioned_trees:
542 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
543 # merge-base by default), so doesn't include untracked files. So we use
544 # 'git ls-files --directory --others --exclude-standard' here directly.
545 paths = scm.GIT.Capture(
546 ['ls-files', '--directory', '--others', '--exclude-standard'],
547 self.checkout_path)
548 for path in (p for p in paths.splitlines() if p.endswith('/')):
549 full_path = os.path.join(self.checkout_path, path)
550 if not os.path.islink(full_path):
551 print('\n_____ removing unversioned directory %s' % path)
[email protected]dc112ac2013-04-24 13:00:19552 gclient_utils.rmtree(full_path)
[email protected]98e69452012-02-16 16:36:43553
[email protected]2702bcd2013-09-24 19:10:07554 return self._Capture(['rev-parse', '--verify', 'HEAD'])
555
[email protected]98e69452012-02-16 16:36:43556
[email protected]396e1a62013-07-03 19:41:04557 def revert(self, options, _args, file_list):
[email protected]e28e4982009-09-25 20:51:45558 """Reverts local modifications.
559
560 All reverted files will be appended to file_list.
561 """
[email protected]8469bf92010-09-03 19:03:15562 if not os.path.isdir(self.checkout_path):
[email protected]260c6532009-10-28 03:22:35563 # revert won't work if the directory doesn't exist. It needs to
564 # checkout instead.
[email protected]77e4eca2010-09-21 13:23:07565 print('\n_____ %s is missing, synching instead' % self.relpath)
[email protected]260c6532009-10-28 03:22:35566 # Don't reuse the args.
567 return self.update(options, [], file_list)
[email protected]b2b46312010-04-30 20:58:03568
569 default_rev = "refs/heads/master"
[email protected]d4fffee2013-06-28 00:35:26570 if options.upstream:
571 if self._GetCurrentBranch():
572 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
573 default_rev = upstream_branch or default_rev
[email protected]6e29d572010-06-04 17:32:20574 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]b2b46312010-04-30 20:58:03575 if not deps_revision:
576 deps_revision = default_rev
577 if deps_revision.startswith('refs/heads/'):
[email protected]1a60dca2013-11-26 14:06:26578 deps_revision = deps_revision.replace('refs/heads/', self.remote + '/')
[email protected]9a8b0662014-02-20 00:56:15579 deps_revision = self.GetUsableRev(deps_revision, options)
[email protected]b2b46312010-04-30 20:58:03580
[email protected]396e1a62013-07-03 19:41:04581 if file_list is not None:
582 files = self._Capture(['diff', deps_revision, '--name-only']).split()
583
[email protected]37e89872010-09-07 16:11:33584 self._Run(['reset', '--hard', deps_revision], options)
[email protected]ade83db2012-09-27 14:06:49585 self._Run(['clean', '-f', '-d'], options)
[email protected]e28e4982009-09-25 20:51:45586
[email protected]396e1a62013-07-03 19:41:04587 if file_list is not None:
588 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
589
590 def revinfo(self, _options, _args, _file_list):
[email protected]6cafa132010-09-07 14:17:26591 """Returns revision"""
592 return self._Capture(['rev-parse', 'HEAD'])
[email protected]0f282062009-11-06 20:14:02593
[email protected]e28e4982009-09-25 20:51:45594 def runhooks(self, options, args, file_list):
595 self.status(options, args, file_list)
596
[email protected]396e1a62013-07-03 19:41:04597 def status(self, options, _args, file_list):
[email protected]e28e4982009-09-25 20:51:45598 """Display status information."""
599 if not os.path.isdir(self.checkout_path):
[email protected]77e4eca2010-09-21 13:23:07600 print(('\n________ couldn\'t run status in %s:\n'
601 'The directory does not exist.') % self.checkout_path)
[email protected]e28e4982009-09-25 20:51:45602 else:
[email protected]1a60dca2013-11-26 14:06:26603 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
[email protected]37e89872010-09-07 16:11:33604 self._Run(['diff', '--name-status', merge_base], options)
[email protected]396e1a62013-07-03 19:41:04605 if file_list is not None:
606 files = self._Capture(['diff', '--name-only', merge_base]).split()
607 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]e28e4982009-09-25 20:51:45608
[email protected]e5d1e612011-12-19 19:49:19609 def GetUsableRev(self, rev, options):
610 """Finds a useful revision for this repository.
611
612 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
613 will be called on the source."""
614 sha1 = None
[email protected]3830a672013-02-19 20:15:14615 if not os.path.isdir(self.checkout_path):
616 raise gclient_utils.Error(
617 ( 'We could not find a valid hash for safesync_url response "%s".\n'
618 'Safesync URLs with a git checkout currently require the repo to\n'
619 'be cloned without a safesync_url before adding the safesync_url.\n'
620 'For more info, see: '
621 'http://code.google.com/p/chromium/wiki/UsingNewGit'
622 '#Initial_checkout' ) % rev)
623 elif rev.isdigit() and len(rev) < 7:
624 # Handles an SVN rev. As an optimization, only verify an SVN revision as
625 # [0-9]{1,6} for now to avoid making a network request.
[email protected]6c2b49d2014-02-26 23:57:38626 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
[email protected]051c88b2011-12-22 00:23:03627 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
628 if not local_head or local_head < int(rev):
[email protected]2a75fdb2012-02-15 01:32:57629 try:
630 logging.debug('Looking for git-svn configuration optimizations.')
631 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
632 cwd=self.checkout_path):
633 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
634 except subprocess2.CalledProcessError:
635 logging.debug('git config --get svn-remote.svn.fetch failed, '
636 'ignoring possible optimization.')
[email protected]051c88b2011-12-22 00:23:03637 if options.verbose:
638 print('Running git svn fetch. This might take a while.\n')
639 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
[email protected]312a6a42012-10-11 21:19:42640 try:
[email protected]c51def32012-10-15 18:50:37641 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
642 cwd=self.checkout_path, rev=rev)
[email protected]312a6a42012-10-11 21:19:42643 except gclient_utils.Error, e:
644 sha1 = e.message
645 print('\nWarning: Could not find a git revision with accurate\n'
646 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
647 'the closest sane git revision, which is:\n'
648 ' %s\n' % (rev, e.message))
[email protected]051c88b2011-12-22 00:23:03649 if not sha1:
650 raise gclient_utils.Error(
651 ( 'It appears that either your git-svn remote is incorrectly\n'
652 'configured or the revision in your safesync_url is\n'
653 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
654 'corresponding git hash for SVN rev %s.' ) % rev)
[email protected]3830a672013-02-19 20:15:14655 else:
656 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
657 sha1 = rev
658 else:
659 # May exist in origin, but we don't have it yet, so fetch and look
660 # again.
[email protected]1a60dca2013-11-26 14:06:26661 scm.GIT.Capture(['fetch', self.remote], cwd=self.checkout_path)
[email protected]3830a672013-02-19 20:15:14662 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
663 sha1 = rev
[email protected]051c88b2011-12-22 00:23:03664
[email protected]e5d1e612011-12-19 19:49:19665 if not sha1:
666 raise gclient_utils.Error(
[email protected]051c88b2011-12-22 00:23:03667 ( 'We could not find a valid hash for safesync_url response "%s".\n'
668 'Safesync URLs with a git checkout currently require a git-svn\n'
669 'remote or a safesync_url that provides git sha1s. Please add a\n'
670 'git-svn remote or change your safesync_url. For more info, see:\n'
[email protected]e5d1e612011-12-19 19:49:19671 'http://code.google.com/p/chromium/wiki/UsingNewGit'
[email protected]051c88b2011-12-22 00:23:03672 '#Initial_checkout' ) % rev)
673
[email protected]e5d1e612011-12-19 19:49:19674 return sha1
675
[email protected]e6f78352010-01-13 17:05:33676 def FullUrlForRelativeUrl(self, url):
677 # Strip from last '/'
678 # Equivalent to unix basename
679 base_url = self.url
680 return base_url[:base_url.rfind('/')] + url
681
[email protected]53456aa2013-07-03 19:38:34682 def _CreateOrUpdateCache(self, url, options):
683 """Make a new git mirror or update existing mirror for |url|, and return the
684 mirror URI to clone from.
685
686 If no cache-dir is specified, just return |url| unchanged.
687 """
688 if not self.cache_dir:
689 return url
[email protected]53456aa2013-07-03 19:38:34690 v = ['-v'] if options.verbose else []
[email protected]267f33e2014-02-28 22:02:32691 self._Run(['cache', 'populate'] + v +
692 ['--shallow', '--cache-dir', self.cache_dir, url],
693 options, cwd=self._root_dir, retry=True)
694 return self._Run(['cache', 'exists', '--cache-dir', self.cache_dir, url],
[email protected]703fe5d2014-02-28 23:10:51695 options, cwd=self._root_dir, ).strip()
[email protected]53456aa2013-07-03 19:38:34696
[email protected]f5d37bf2010-09-02 00:50:34697 def _Clone(self, revision, url, options):
[email protected]d90ba3f2010-02-23 14:42:57698 """Clone a git repository from the given URL.
699
[email protected]786fb682010-06-02 15:16:23700 Once we've cloned the repo, we checkout a working branch if the specified
701 revision is a branch head. If it is a tag or a specific commit, then we
702 leave HEAD detached as it makes future updates simpler -- in this case the
703 user should first create a new branch or switch to an existing branch before
704 making changes in the repo."""
[email protected]f5d37bf2010-09-02 00:50:34705 if not options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57706 # git clone doesn't seem to insert a newline properly before printing
707 # to stdout
[email protected]77e4eca2010-09-21 13:23:07708 print('')
[email protected]ecb75422013-07-12 21:57:33709 template_path = os.path.join(
710 os.path.dirname(THIS_FILE_PATH), 'git-templates')
[email protected]3534aa52013-07-20 01:58:08711 clone_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'clone', '--no-checkout',
712 '--progress', '--template=%s' % template_path]
[email protected]53456aa2013-07-03 19:38:34713 if self.cache_dir:
714 clone_cmd.append('--shared')
[email protected]f5d37bf2010-09-02 00:50:34715 if options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57716 clone_cmd.append('--verbose')
[email protected]3534aa52013-07-20 01:58:08717 clone_cmd.append(url)
[email protected]328c3c72011-06-01 20:50:27718 # If the parent directory does not exist, Git clone on Windows will not
719 # create it, so we need to do it manually.
720 parent_dir = os.path.dirname(self.checkout_path)
[email protected]3534aa52013-07-20 01:58:08721 gclient_utils.safe_makedirs(parent_dir)
722 tmp_dir = tempfile.mkdtemp(
723 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
724 dir=parent_dir)
725 try:
726 clone_cmd.append(tmp_dir)
[email protected]fd5b6382013-10-25 20:54:34727 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
[email protected]3534aa52013-07-20 01:58:08728 gclient_utils.safe_makedirs(self.checkout_path)
[email protected]ef509e42013-09-20 13:19:08729 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
730 os.path.join(self.checkout_path, '.git'))
[email protected]6279e8a2014-02-13 01:45:25731 except:
732 traceback.print_exc(file=sys.stderr)
733 raise
[email protected]3534aa52013-07-20 01:58:08734 finally:
735 if os.listdir(tmp_dir):
736 print('\n_____ removing non-empty tmp dir %s' % tmp_dir)
737 gclient_utils.rmtree(tmp_dir)
738 if revision.startswith('refs/heads/'):
739 self._Run(
740 ['checkout', '--quiet', revision.replace('refs/heads/', '')], options)
741 else:
[email protected]786fb682010-06-02 15:16:23742 # Squelch git's very verbose detached HEAD warning and use our own
[email protected]3534aa52013-07-20 01:58:08743 self._Run(['checkout', '--quiet', revision], options)
[email protected]77e4eca2010-09-21 13:23:07744 print(
[email protected]f5d37bf2010-09-02 00:50:34745 ('Checked out %s to a detached HEAD. Before making any commits\n'
746 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
[email protected]1a60dca2013-11-26 14:06:26747 'an existing branch or use \'git checkout %s -b <branch>\' to\n'
748 'create a new branch for your work.') % (revision, self.remote))
[email protected]d90ba3f2010-02-23 14:42:57749
[email protected]30c46d62014-01-23 12:11:56750 @staticmethod
751 def _AskForData(prompt, options):
752 if options.jobs > 1:
753 raise gclient_utils.Error("Background task requires input. Rerun "
754 "gclient with --jobs=1 so that\n"
755 "interaction is possible.")
756 try:
757 return raw_input(prompt)
758 except KeyboardInterrupt:
759 # Hide the exception.
760 sys.exit(1)
761
762
[email protected]f5d37bf2010-09-02 00:50:34763 def _AttemptRebase(self, upstream, files, options, newbase=None,
[email protected]30c46d62014-01-23 12:11:56764 branch=None, printed_path=False, merge=False):
[email protected]d90ba3f2010-02-23 14:42:57765 """Attempt to rebase onto either upstream or, if specified, newbase."""
[email protected]396e1a62013-07-03 19:41:04766 if files is not None:
767 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
[email protected]d90ba3f2010-02-23 14:42:57768 revision = upstream
769 if newbase:
770 revision = newbase
[email protected]30c46d62014-01-23 12:11:56771 action = 'merge' if merge else 'rebase'
[email protected]d90ba3f2010-02-23 14:42:57772 if not printed_path:
[email protected]30c46d62014-01-23 12:11:56773 print('\n_____ %s : Attempting %s onto %s...' % (
774 self.relpath, action, revision))
[email protected]d90ba3f2010-02-23 14:42:57775 printed_path = True
776 else:
[email protected]30c46d62014-01-23 12:11:56777 print('Attempting %s onto %s...' % (action, revision))
778
779 if merge:
780 merge_output = self._Capture(['merge', revision])
781 if options.verbose:
782 print(merge_output)
783 return
[email protected]d90ba3f2010-02-23 14:42:57784
785 # Build the rebase command here using the args
786 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
787 rebase_cmd = ['rebase']
[email protected]f5d37bf2010-09-02 00:50:34788 if options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57789 rebase_cmd.append('--verbose')
790 if newbase:
791 rebase_cmd.extend(['--onto', newbase])
792 rebase_cmd.append(upstream)
793 if branch:
794 rebase_cmd.append(branch)
795
796 try:
[email protected]ad80e3b2010-09-09 14:18:28797 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22798 except subprocess2.CalledProcessError, e:
[email protected]ad80e3b2010-09-09 14:18:28799 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
800 re.match(r'cannot rebase: your index contains uncommitted changes',
801 e.stderr)):
[email protected]d90ba3f2010-02-23 14:42:57802 while True:
[email protected]30c46d62014-01-23 12:11:56803 rebase_action = self._AskForData(
[email protected]90541732011-04-01 17:54:18804 'Cannot rebase because of unstaged changes.\n'
805 '\'git reset --hard HEAD\' ?\n'
806 'WARNING: destroys any uncommitted work in your current branch!'
[email protected]18fa4542013-05-21 13:30:46807 ' (y)es / (q)uit / (s)how : ', options)
[email protected]d90ba3f2010-02-23 14:42:57808 if re.match(r'yes|y', rebase_action, re.I):
[email protected]37e89872010-09-07 16:11:33809 self._Run(['reset', '--hard', 'HEAD'], options)
[email protected]d90ba3f2010-02-23 14:42:57810 # Should this be recursive?
[email protected]ad80e3b2010-09-09 14:18:28811 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
[email protected]d90ba3f2010-02-23 14:42:57812 break
813 elif re.match(r'quit|q', rebase_action, re.I):
814 raise gclient_utils.Error("Please merge or rebase manually\n"
815 "cd %s && git " % self.checkout_path
816 + "%s" % ' '.join(rebase_cmd))
817 elif re.match(r'show|s', rebase_action, re.I):
[email protected]77e4eca2010-09-21 13:23:07818 print('\n%s' % e.stderr.strip())
[email protected]d90ba3f2010-02-23 14:42:57819 continue
820 else:
821 gclient_utils.Error("Input not recognized")
822 continue
823 elif re.search(r'^CONFLICT', e.stdout, re.M):
824 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
825 "Fix the conflict and run gclient again.\n"
826 "See 'man git-rebase' for details.\n")
827 else:
[email protected]77e4eca2010-09-21 13:23:07828 print(e.stdout.strip())
829 print('Rebase produced error output:\n%s' % e.stderr.strip())
[email protected]d90ba3f2010-02-23 14:42:57830 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
831 "manually.\ncd %s && git " %
832 self.checkout_path
833 + "%s" % ' '.join(rebase_cmd))
834
[email protected]77e4eca2010-09-21 13:23:07835 print(rebase_output.strip())
[email protected]f5d37bf2010-09-02 00:50:34836 if not options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57837 # Make the output a little prettier. It's nice to have some
838 # whitespace between projects when syncing.
[email protected]77e4eca2010-09-21 13:23:07839 print('')
[email protected]d90ba3f2010-02-23 14:42:57840
[email protected]6e29d572010-06-04 17:32:20841 @staticmethod
842 def _CheckMinVersion(min_version):
[email protected]d0f854a2010-03-11 19:35:53843 (ok, current_version) = scm.GIT.AssertVersion(min_version)
844 if not ok:
845 raise gclient_utils.Error('git version %s < minimum required %s' %
846 (current_version, min_version))
[email protected]923a0372009-12-11 20:42:43847
[email protected]786fb682010-06-02 15:16:23848 def _IsRebasing(self):
849 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
850 # have a plumbing command to determine whether a rebase is in progress, so
851 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
852 g = os.path.join(self.checkout_path, '.git')
853 return (
854 os.path.isdir(os.path.join(g, "rebase-merge")) or
855 os.path.isdir(os.path.join(g, "rebase-apply")))
856
857 def _CheckClean(self, rev_str):
858 # Make sure the tree is clean; see git-rebase.sh for reference
859 try:
860 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
[email protected]ad80e3b2010-09-09 14:18:28861 cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22862 except subprocess2.CalledProcessError:
[email protected]6e29d572010-06-04 17:32:20863 raise gclient_utils.Error('\n____ %s%s\n'
864 '\tYou have unstaged changes.\n'
865 '\tPlease commit, stash, or reset.\n'
866 % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23867 try:
868 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
[email protected]ad80e3b2010-09-09 14:18:28869 '--ignore-submodules', 'HEAD', '--'],
870 cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22871 except subprocess2.CalledProcessError:
[email protected]6e29d572010-06-04 17:32:20872 raise gclient_utils.Error('\n____ %s%s\n'
873 '\tYour index contains uncommitted changes\n'
874 '\tPlease commit, stash, or reset.\n'
875 % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23876
[email protected]396e1a62013-07-03 19:41:04877 def _CheckDetachedHead(self, rev_str, _options):
[email protected]786fb682010-06-02 15:16:23878 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
879 # reference by a commit). If not, error out -- most likely a rebase is
880 # in progress, try to detect so we can give a better error.
881 try:
[email protected]ad80e3b2010-09-09 14:18:28882 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
883 cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22884 except subprocess2.CalledProcessError:
[email protected]786fb682010-06-02 15:16:23885 # Commit is not contained by any rev. See if the user is rebasing:
886 if self._IsRebasing():
887 # Punt to the user
888 raise gclient_utils.Error('\n____ %s%s\n'
889 '\tAlready in a conflict, i.e. (no branch).\n'
890 '\tFix the conflict and run gclient again.\n'
891 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
892 '\tSee man git-rebase for details.\n'
893 % (self.relpath, rev_str))
894 # Let's just save off the commit so we can proceed.
[email protected]6cafa132010-09-07 14:17:26895 name = ('saved-by-gclient-' +
896 self._Capture(['rev-parse', '--short', 'HEAD']))
[email protected]77bd7362013-09-25 23:46:14897 self._Capture(['branch', '-f', name])
[email protected]77e4eca2010-09-21 13:23:07898 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
[email protected]f5d37bf2010-09-02 00:50:34899 name)
[email protected]786fb682010-06-02 15:16:23900
[email protected]5bde4852009-12-14 16:47:12901 def _GetCurrentBranch(self):
[email protected]786fb682010-06-02 15:16:23902 # Returns name of current branch or None for detached HEAD
[email protected]6cafa132010-09-07 14:17:26903 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
[email protected]786fb682010-06-02 15:16:23904 if branch == 'HEAD':
[email protected]5bde4852009-12-14 16:47:12905 return None
906 return branch
907
[email protected]53456aa2013-07-03 19:38:34908 def _Capture(self, args, cwd=None):
[email protected]bffad372011-09-08 17:54:22909 return subprocess2.check_output(
[email protected]87e6d332011-09-09 19:01:28910 ['git'] + args,
[email protected]f6f58402013-05-22 00:14:32911 stderr=subprocess2.VOID,
[email protected]53456aa2013-07-03 19:38:34912 cwd=cwd or self.checkout_path).strip()
[email protected]6cafa132010-09-07 14:17:26913
[email protected]e409df62013-04-16 17:28:57914 def _UpdateBranchHeads(self, options, fetch=False):
915 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
916 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
[email protected]1a60dca2013-11-26 14:06:26917 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
[email protected]f2d7d6b2013-10-17 20:41:43918 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
919 '^\\+refs/branch-heads/\\*:.*$']
920 self._Run(config_cmd, options)
921 if fetch:
[email protected]1a60dca2013-11-26 14:06:26922 fetch_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'fetch', self.remote]
[email protected]f2d7d6b2013-10-17 20:41:43923 if options.verbose:
924 fetch_cmd.append('--verbose')
925 self._Run(fetch_cmd, options, retry=True)
[email protected]e409df62013-04-16 17:28:57926
[email protected]fd5b6382013-10-25 20:54:34927 def _Run(self, args, options, **kwargs):
[email protected]6cafa132010-09-07 14:17:26928 kwargs.setdefault('cwd', self.checkout_path)
[email protected]fd5b6382013-10-25 20:54:34929 git_filter = not options.verbose
[email protected]53456aa2013-07-03 19:38:34930 if git_filter:
[email protected]5a306a22014-02-24 22:13:59931 kwargs['filter_fn'] = gclient_utils.GitFilter(kwargs.get('filter_fn'))
[email protected]53456aa2013-07-03 19:38:34932 kwargs.setdefault('print_stdout', False)
[email protected]7f834ad2013-07-10 00:22:17933 # Don't prompt for passwords; just fail quickly and noisily.
[email protected]3ce41842013-07-11 17:38:57934 # By default, git will use an interactive terminal prompt when a username/
935 # password is needed. That shouldn't happen in the chromium workflow,
936 # and if it does, then gclient may hide the prompt in the midst of a flood
937 # of terminal spew. The only indication that something has gone wrong
938 # will be when gclient hangs unresponsively. Instead, we disable the
939 # password prompt and simply allow git to fail noisily. The error
940 # message produced by git will be copied to gclient's output.
[email protected]7f834ad2013-07-10 00:22:17941 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
942 env.setdefault('GIT_ASKPASS', 'true')
943 env.setdefault('SSH_ASKPASS', 'true')
[email protected]53456aa2013-07-03 19:38:34944 else:
945 kwargs.setdefault('print_stdout', True)
[email protected]85d3e3a2011-10-07 17:12:00946 stdout = kwargs.get('stdout', sys.stdout)
947 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
948 ' '.join(args), kwargs['cwd']))
[email protected]267f33e2014-02-28 22:02:32949 return gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
[email protected]e28e4982009-09-25 20:51:45950
951
[email protected]55e724e2010-03-11 19:36:49952class SVNWrapper(SCMWrapper):
[email protected]cb5442b2009-09-22 16:51:24953 """ Wrapper for SVN """
[email protected]2702bcd2013-09-24 19:10:07954 name = 'svn'
[email protected]5f3eee32009-09-17 00:34:30955
[email protected]9e3e82c2012-04-18 12:55:43956 @staticmethod
957 def BinaryExists():
958 """Returns true if the command exists."""
959 try:
960 result, version = scm.SVN.AssertVersion('1.4')
961 if not result:
962 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
963 return result
964 except OSError:
965 return False
966
[email protected]885a9602013-05-31 09:54:40967 def GetCheckoutRoot(self):
968 return scm.SVN.GetCheckoutRoot(self.checkout_path)
969
[email protected]eaab7842011-04-28 09:07:58970 def GetRevisionDate(self, revision):
971 """Returns the given revision's date in ISO-8601 format (which contains the
972 time zone)."""
[email protected]d579fcf2011-12-13 20:36:03973 date = scm.SVN.Capture(
974 ['propget', '--revprop', 'svn:date', '-r', revision],
975 os.path.join(self.checkout_path, '.'))
[email protected]eaab7842011-04-28 09:07:58976 return date.strip()
977
[email protected]396e1a62013-07-03 19:41:04978 def cleanup(self, options, args, _file_list):
[email protected]5f3eee32009-09-17 00:34:30979 """Cleanup working copy."""
[email protected]669600d2010-09-01 19:06:31980 self._Run(['cleanup'] + args, options)
[email protected]5f3eee32009-09-17 00:34:30981
[email protected]396e1a62013-07-03 19:41:04982 def diff(self, options, args, _file_list):
[email protected]5f3eee32009-09-17 00:34:30983 # NOTE: This function does not currently modify file_list.
[email protected]8469bf92010-09-03 19:03:15984 if not os.path.isdir(self.checkout_path):
985 raise gclient_utils.Error('Directory %s is not present.' %
986 self.checkout_path)
[email protected]669600d2010-09-01 19:06:31987 self._Run(['diff'] + args, options)
[email protected]5f3eee32009-09-17 00:34:30988
[email protected]396e1a62013-07-03 19:41:04989 def pack(self, _options, args, _file_list):
[email protected]ee4071d2009-12-22 22:25:37990 """Generates a patch file which can be applied to the root of the
991 repository."""
[email protected]8469bf92010-09-03 19:03:15992 if not os.path.isdir(self.checkout_path):
993 raise gclient_utils.Error('Directory %s is not present.' %
994 self.checkout_path)
995 gclient_utils.CheckCallAndFilter(
996 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
997 cwd=self.checkout_path,
998 print_stdout=False,
[email protected]306080c2012-05-04 13:11:29999 filter_fn=SvnDiffFilterer(self.relpath).Filter)
[email protected]ee4071d2009-12-22 22:25:371000
[email protected]5f3eee32009-09-17 00:34:301001 def update(self, options, args, file_list):
[email protected]d6504212010-01-13 17:34:311002 """Runs svn to update or transparently checkout the working copy.
[email protected]5f3eee32009-09-17 00:34:301003
1004 All updated files will be appended to file_list.
1005
1006 Raises:
1007 Error: if can't get URL for relative path.
1008 """
[email protected]7ff04292014-03-10 12:57:251009 # Only update if hg is not controlling the directory.
[email protected]6c2b49d2014-02-26 23:57:381010 hg_path = os.path.join(self.checkout_path, '.hg')
1011 if os.path.exists(hg_path):
1012 print('________ found .hg directory; skipping %s' % self.relpath)
1013 return
1014
[email protected]5f3eee32009-09-17 00:34:301015 if args:
1016 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1017
[email protected]8e0e9262010-08-17 19:20:271018 # revision is the revision to match. It is None if no revision is specified,
1019 # i.e. the 'deps ain't pinned'.
[email protected]ac915bb2009-11-13 17:03:011020 url, revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]50fd47f2014-02-13 01:03:191021 # Keep the original unpinned url for reference in case the repo is switched.
1022 base_url = url
[email protected]eb2756d2011-09-20 20:17:511023 managed = True
[email protected]5f3eee32009-09-17 00:34:301024 if options.revision:
1025 # Override the revision number.
[email protected]ac915bb2009-11-13 17:03:011026 revision = str(options.revision)
[email protected]5f3eee32009-09-17 00:34:301027 if revision:
[email protected]eb2756d2011-09-20 20:17:511028 if revision != 'unmanaged':
1029 forced_revision = True
1030 # Reconstruct the url.
1031 url = '%s@%s' % (url, revision)
1032 rev_str = ' at %s' % revision
1033 else:
1034 managed = False
1035 revision = None
[email protected]8e0e9262010-08-17 19:20:271036 else:
1037 forced_revision = False
1038 rev_str = ''
[email protected]5f3eee32009-09-17 00:34:301039
[email protected]50fd47f2014-02-13 01:03:191040 exists = os.path.exists(self.checkout_path)
[email protected]6c2b49d2014-02-26 23:57:381041 if exists and managed:
[email protected]7ff04292014-03-10 12:57:251042 # Git is only okay if it's a git-svn checkout of the right repo.
1043 if scm.GIT.IsGitSvn(self.checkout_path):
1044 remote_url = scm.GIT.Capture(['config', '--local', '--get',
1045 'svn-remote.svn.url'],
1046 cwd=self.checkout_path).rstrip()
1047 if remote_url.rstrip('/') == base_url.rstrip('/'):
1048 print('\n_____ %s looks like a git-svn checkout. Skipping.'
1049 % self.relpath)
1050 return # TODO(borenet): Get the svn revision number?
1051
1052 # Get the existing scm url and the revision number of the current checkout.
1053 if exists and managed:
[email protected]13349e22012-11-15 17:11:281054 try:
1055 from_info = scm.SVN.CaptureLocalInfo(
1056 [], os.path.join(self.checkout_path, '.'))
1057 except (gclient_utils.Error, subprocess2.CalledProcessError):
[email protected]7ff04292014-03-10 12:57:251058 if (options.force or
1059 (options.reset and options.delete_unversioned_trees)):
[email protected]6c2b49d2014-02-26 23:57:381060 print 'Removing troublesome path %s' % self.checkout_path
1061 gclient_utils.rmtree(self.checkout_path)
1062 exists = False
1063 else:
1064 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1065 'present. Delete the directory and try again.')
1066 raise gclient_utils.Error(msg % self.checkout_path)
[email protected]13349e22012-11-15 17:11:281067
[email protected]2f2ca142014-01-07 03:59:181068 BASE_URLS = {
1069 '/chrome/trunk/src': 'gs://chromium-svn-checkout/chrome/',
1070 '/blink/trunk': 'gs://chromium-svn-checkout/blink/',
1071 }
[email protected]ca35be32014-01-17 01:48:181072 WHITELISTED_ROOTS = [
1073 'svn://svn.chromium.org',
1074 'svn://svn-mirror.golo.chromium.org',
1075 ]
[email protected]13349e22012-11-15 17:11:281076 if not exists:
[email protected]2f2ca142014-01-07 03:59:181077 try:
1078 # Split out the revision number since it's not useful for us.
1079 base_path = urlparse.urlparse(url).path.split('@')[0]
[email protected]ca35be32014-01-17 01:48:181080 # Check to see if we're on a whitelisted root. We do this because
1081 # only some svn servers have matching UUIDs.
1082 local_parsed = urlparse.urlparse(url)
1083 local_root = '%s://%s' % (local_parsed.scheme, local_parsed.netloc)
[email protected]2f2ca142014-01-07 03:59:181084 if ('CHROME_HEADLESS' in os.environ
1085 and sys.platform == 'linux2' # TODO(hinoka): Enable for win/mac.
[email protected]ca35be32014-01-17 01:48:181086 and base_path in BASE_URLS
1087 and local_root in WHITELISTED_ROOTS):
1088
[email protected]2f2ca142014-01-07 03:59:181089 # Use a tarball for initial sync if we are on a bot.
1090 # Get an unauthenticated gsutil instance.
1091 gsutil = download_from_google_storage.Gsutil(
1092 GSUTIL_DEFAULT_PATH, boto_path=os.devnull)
1093
1094 gs_path = BASE_URLS[base_path]
1095 _, out, _ = gsutil.check_call('ls', gs_path)
1096 # So that we can get the most recent revision.
1097 sorted_items = sorted(out.splitlines())
1098 latest_checkout = sorted_items[-1]
1099
1100 tempdir = tempfile.mkdtemp()
1101 print 'Downloading %s...' % latest_checkout
1102 code, out, err = gsutil.check_call('cp', latest_checkout, tempdir)
1103 if code:
1104 print '%s\n%s' % (out, err)
1105 raise Exception()
1106 filename = latest_checkout.split('/')[-1]
1107 tarball = os.path.join(tempdir, filename)
1108 print 'Unpacking into %s...' % self.checkout_path
1109 gclient_utils.safe_makedirs(self.checkout_path)
1110 # TODO(hinoka): Use 7z for windows.
1111 cmd = ['tar', '--extract', '--ungzip',
1112 '--directory', self.checkout_path,
1113 '--file', tarball]
1114 gclient_utils.CheckCallAndFilter(
1115 cmd, stdout=sys.stdout, print_stdout=True)
1116
1117 print 'Deleting temp file'
1118 gclient_utils.rmtree(tempdir)
1119
1120 # Rewrite the repository root to match.
1121 tarball_url = scm.SVN.CaptureLocalInfo(
1122 ['.'], self.checkout_path)['Repository Root']
1123 tarball_parsed = urlparse.urlparse(tarball_url)
1124 tarball_root = '%s://%s' % (tarball_parsed.scheme,
1125 tarball_parsed.netloc)
[email protected]2f2ca142014-01-07 03:59:181126
1127 if tarball_root != local_root:
1128 print 'Switching repository root to %s' % local_root
1129 self._Run(['switch', '--relocate', tarball_root,
1130 local_root, self.checkout_path],
1131 options)
1132 except Exception as e:
1133 print 'We tried to get a source tarball but failed.'
1134 print 'Resuming normal operations.'
1135 print str(e)
1136
[email protected]6c48a302011-10-20 23:44:201137 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
[email protected]5f3eee32009-09-17 00:34:301138 # We need to checkout.
[email protected]8469bf92010-09-03 19:03:151139 command = ['checkout', url, self.checkout_path]
[email protected]8e0e9262010-08-17 19:20:271140 command = self._AddAdditionalUpdateFlags(command, options, revision)
[email protected]669600d2010-09-01 19:06:311141 self._RunAndGetFileList(command, options, file_list, self._root_dir)
[email protected]2702bcd2013-09-24 19:10:071142 return self.Svnversion()
[email protected]5f3eee32009-09-17 00:34:301143
[email protected]6c2b49d2014-02-26 23:57:381144 if not managed:
1145 print ('________ unmanaged solution; skipping %s' % self.relpath)
[email protected]7ff04292014-03-10 12:57:251146 if not scm.GIT.IsGitSvn(self.checkout_path):
1147 return self.Svnversion()
1148 return
[email protected]6c2b49d2014-02-26 23:57:381149
[email protected]49fcb0c2011-09-23 14:34:381150 if 'URL' not in from_info:
1151 raise gclient_utils.Error(
1152 ('gclient is confused. Couldn\'t get the url for %s.\n'
1153 'Try using @unmanaged.\n%s') % (
1154 self.checkout_path, from_info))
1155
[email protected]e407c9a2010-08-09 19:11:371156 # Look for locked directories.
[email protected]d579fcf2011-12-13 20:36:031157 dir_info = scm.SVN.CaptureStatus(
1158 None, os.path.join(self.checkout_path, '.'))
[email protected]d558c4b2011-09-22 18:56:241159 if any(d[0][2] == 'L' for d in dir_info):
1160 try:
1161 self._Run(['cleanup', self.checkout_path], options)
1162 except subprocess2.CalledProcessError, e:
1163 # Get the status again, svn cleanup may have cleaned up at least
1164 # something.
[email protected]d579fcf2011-12-13 20:36:031165 dir_info = scm.SVN.CaptureStatus(
1166 None, os.path.join(self.checkout_path, '.'))
[email protected]d558c4b2011-09-22 18:56:241167
1168 # Try to fix the failures by removing troublesome files.
1169 for d in dir_info:
1170 if d[0][2] == 'L':
1171 if d[0][0] == '!' and options.force:
[email protected]1580d952013-08-19 07:31:401172 # We don't pass any files/directories to CaptureStatus and set
1173 # cwd=self.checkout_path, so we should get relative paths here.
1174 assert not os.path.isabs(d[1])
1175 path_to_remove = os.path.normpath(
1176 os.path.join(self.checkout_path, d[1]))
1177 print 'Removing troublesome path %s' % path_to_remove
1178 gclient_utils.rmtree(path_to_remove)
[email protected]d558c4b2011-09-22 18:56:241179 else:
1180 print 'Not removing troublesome path %s automatically.' % d[1]
1181 if d[0][0] == '!':
1182 print 'You can pass --force to enable automatic removal.'
1183 raise e
[email protected]e407c9a2010-08-09 19:11:371184
[email protected]8e0e9262010-08-17 19:20:271185 # Retrieve the current HEAD version because svn is slow at null updates.
1186 if options.manually_grab_svn_rev and not revision:
[email protected]d579fcf2011-12-13 20:36:031187 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
[email protected]8e0e9262010-08-17 19:20:271188 revision = str(from_info_live['Revision'])
1189 rev_str = ' at %s' % revision
[email protected]5f3eee32009-09-17 00:34:301190
[email protected]7ff04292014-03-10 12:57:251191 if from_info['URL'].rstrip('/') != base_url.rstrip('/'):
[email protected]6c2b49d2014-02-26 23:57:381192 # The repository url changed, need to switch.
1193 try:
1194 to_info = scm.SVN.CaptureRemoteInfo(url)
1195 except (gclient_utils.Error, subprocess2.CalledProcessError):
1196 # The url is invalid or the server is not accessible, it's safer to bail
1197 # out right now.
1198 raise gclient_utils.Error('This url is unreachable: %s' % url)
1199 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1200 and (from_info['UUID'] == to_info['UUID']))
1201 if can_switch:
1202 print('\n_____ relocating %s to a new checkout' % self.relpath)
1203 # We have different roots, so check if we can switch --relocate.
1204 # Subversion only permits this if the repository UUIDs match.
1205 # Perform the switch --relocate, then rewrite the from_url
1206 # to reflect where we "are now." (This is the same way that
1207 # Subversion itself handles the metadata when switch --relocate
1208 # is used.) This makes the checks below for whether we
1209 # can update to a revision or have to switch to a different
1210 # branch work as expected.
1211 # TODO(maruel): TEST ME !
1212 command = ['switch', '--relocate',
1213 from_info['Repository Root'],
1214 to_info['Repository Root'],
1215 self.relpath]
1216 self._Run(command, options, cwd=self._root_dir)
1217 from_info['URL'] = from_info['URL'].replace(
1218 from_info['Repository Root'],
1219 to_info['Repository Root'])
1220 else:
1221 if not options.force and not options.reset:
1222 # Look for local modifications but ignore unversioned files.
1223 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1224 if status[0][0] != '?':
1225 raise gclient_utils.Error(
1226 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1227 'there is local changes in %s. Delete the directory and '
1228 'try again.') % (url, self.checkout_path))
1229 # Ok delete it.
1230 print('\n_____ switching %s to a new checkout' % self.relpath)
1231 gclient_utils.rmtree(self.checkout_path)
1232 # We need to checkout.
1233 command = ['checkout', url, self.checkout_path]
1234 command = self._AddAdditionalUpdateFlags(command, options, revision)
1235 self._RunAndGetFileList(command, options, file_list, self._root_dir)
1236 return self.Svnversion()
1237
[email protected]5f3eee32009-09-17 00:34:301238 # If the provided url has a revision number that matches the revision
1239 # number of the existing directory, then we don't need to bother updating.
[email protected]2e0c6852009-09-24 00:02:071240 if not options.force and str(from_info['Revision']) == revision:
[email protected]5f3eee32009-09-17 00:34:301241 if options.verbose or not forced_revision:
[email protected]77e4eca2010-09-21 13:23:071242 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]98e69452012-02-16 16:36:431243 else:
1244 command = ['update', self.checkout_path]
1245 command = self._AddAdditionalUpdateFlags(command, options, revision)
1246 self._RunAndGetFileList(command, options, file_list, self._root_dir)
[email protected]5f3eee32009-09-17 00:34:301247
[email protected]98e69452012-02-16 16:36:431248 # If --reset and --delete_unversioned_trees are specified, remove any
1249 # untracked files and directories.
1250 if options.reset and options.delete_unversioned_trees:
1251 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1252 full_path = os.path.join(self.checkout_path, status[1])
1253 if (status[0][0] == '?'
1254 and os.path.isdir(full_path)
1255 and not os.path.islink(full_path)):
1256 print('\n_____ removing unversioned directory %s' % status[1])
[email protected]dc112ac2013-04-24 13:00:191257 gclient_utils.rmtree(full_path)
[email protected]2702bcd2013-09-24 19:10:071258 return self.Svnversion()
[email protected]5f3eee32009-09-17 00:34:301259
[email protected]4b5b1772010-04-08 01:52:561260 def updatesingle(self, options, args, file_list):
[email protected]4b5b1772010-04-08 01:52:561261 filename = args.pop()
[email protected]57564662010-04-14 02:35:121262 if scm.SVN.AssertVersion("1.5")[0]:
[email protected]8469bf92010-09-03 19:03:151263 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
[email protected]57564662010-04-14 02:35:121264 # Create an empty checkout and then update the one file we want. Future
1265 # operations will only apply to the one file we checked out.
[email protected]8469bf92010-09-03 19:03:151266 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
[email protected]669600d2010-09-01 19:06:311267 self._Run(command, options, cwd=self._root_dir)
[email protected]8469bf92010-09-03 19:03:151268 if os.path.exists(os.path.join(self.checkout_path, filename)):
1269 os.remove(os.path.join(self.checkout_path, filename))
[email protected]57564662010-04-14 02:35:121270 command = ["update", filename]
[email protected]669600d2010-09-01 19:06:311271 self._RunAndGetFileList(command, options, file_list)
[email protected]57564662010-04-14 02:35:121272 # After the initial checkout, we can use update as if it were any other
1273 # dep.
1274 self.update(options, args, file_list)
1275 else:
1276 # If the installed version of SVN doesn't support --depth, fallback to
1277 # just exporting the file. This has the downside that revision
1278 # information is not stored next to the file, so we will have to
1279 # re-export the file every time we sync.
[email protected]8469bf92010-09-03 19:03:151280 if not os.path.exists(self.checkout_path):
[email protected]6c48a302011-10-20 23:44:201281 gclient_utils.safe_makedirs(self.checkout_path)
[email protected]57564662010-04-14 02:35:121282 command = ["export", os.path.join(self.url, filename),
[email protected]8469bf92010-09-03 19:03:151283 os.path.join(self.checkout_path, filename)]
[email protected]8e0e9262010-08-17 19:20:271284 command = self._AddAdditionalUpdateFlags(command, options,
1285 options.revision)
[email protected]669600d2010-09-01 19:06:311286 self._Run(command, options, cwd=self._root_dir)
[email protected]4b5b1772010-04-08 01:52:561287
[email protected]396e1a62013-07-03 19:41:041288 def revert(self, options, _args, file_list):
[email protected]5f3eee32009-09-17 00:34:301289 """Reverts local modifications. Subversion specific.
1290
1291 All reverted files will be appended to file_list, even if Subversion
1292 doesn't know about them.
1293 """
[email protected]8469bf92010-09-03 19:03:151294 if not os.path.isdir(self.checkout_path):
[email protected]c0cc0872011-10-12 17:02:411295 if os.path.exists(self.checkout_path):
1296 gclient_utils.rmtree(self.checkout_path)
[email protected]5f3eee32009-09-17 00:34:301297 # svn revert won't work if the directory doesn't exist. It needs to
1298 # checkout instead.
[email protected]77e4eca2010-09-21 13:23:071299 print('\n_____ %s is missing, synching instead' % self.relpath)
[email protected]5f3eee32009-09-17 00:34:301300 # Don't reuse the args.
1301 return self.update(options, [], file_list)
1302
[email protected]c0cc0872011-10-12 17:02:411303 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
[email protected]50fd47f2014-02-13 01:03:191304 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1305 print('________ found .git directory; skipping %s' % self.relpath)
1306 return
[email protected]6c2b49d2014-02-26 23:57:381307 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1308 print('________ found .hg directory; skipping %s' % self.relpath)
1309 return
[email protected]c0cc0872011-10-12 17:02:411310 if not options.force:
1311 raise gclient_utils.Error('Invalid checkout path, aborting')
1312 print(
1313 '\n_____ %s is not a valid svn checkout, synching instead' %
1314 self.relpath)
1315 gclient_utils.rmtree(self.checkout_path)
1316 # Don't reuse the args.
1317 return self.update(options, [], file_list)
1318
[email protected]07ab60e2011-02-08 21:54:001319 def printcb(file_status):
[email protected]396e1a62013-07-03 19:41:041320 if file_list is not None:
1321 file_list.append(file_status[1])
[email protected]aa3dd472009-09-21 19:02:481322 if logging.getLogger().isEnabledFor(logging.INFO):
[email protected]07ab60e2011-02-08 21:54:001323 logging.info('%s%s' % (file_status[0], file_status[1]))
[email protected]aa3dd472009-09-21 19:02:481324 else:
[email protected]07ab60e2011-02-08 21:54:001325 print(os.path.join(self.checkout_path, file_status[1]))
1326 scm.SVN.Revert(self.checkout_path, callback=printcb)
[email protected]aa3dd472009-09-21 19:02:481327
[email protected]8b322b32011-11-01 19:05:501328 # Revert() may delete the directory altogether.
1329 if not os.path.isdir(self.checkout_path):
1330 # Don't reuse the args.
1331 return self.update(options, [], file_list)
1332
[email protected]810a50b2009-10-05 23:03:181333 try:
1334 # svn revert is so broken we don't even use it. Using
1335 # "svn up --revision BASE" achieve the same effect.
[email protected]07ab60e2011-02-08 21:54:001336 # file_list will contain duplicates.
[email protected]669600d2010-09-01 19:06:311337 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1338 file_list)
[email protected]810a50b2009-10-05 23:03:181339 except OSError, e:
[email protected]07ab60e2011-02-08 21:54:001340 # Maybe the directory disapeared meanwhile. Do not throw an exception.
[email protected]810a50b2009-10-05 23:03:181341 logging.error('Failed to update:\n%s' % str(e))
[email protected]5f3eee32009-09-17 00:34:301342
[email protected]396e1a62013-07-03 19:41:041343 def revinfo(self, _options, _args, _file_list):
[email protected]0f282062009-11-06 20:14:021344 """Display revision"""
[email protected]54019f32010-09-09 13:50:111345 try:
1346 return scm.SVN.CaptureRevision(self.checkout_path)
[email protected]31cb48a2011-04-04 18:01:361347 except (gclient_utils.Error, subprocess2.CalledProcessError):
[email protected]54019f32010-09-09 13:50:111348 return None
[email protected]0f282062009-11-06 20:14:021349
[email protected]cb5442b2009-09-22 16:51:241350 def runhooks(self, options, args, file_list):
1351 self.status(options, args, file_list)
1352
[email protected]5f3eee32009-09-17 00:34:301353 def status(self, options, args, file_list):
1354 """Display status information."""
[email protected]669600d2010-09-01 19:06:311355 command = ['status'] + args
[email protected]8469bf92010-09-03 19:03:151356 if not os.path.isdir(self.checkout_path):
[email protected]5f3eee32009-09-17 00:34:301357 # svn status won't work if the directory doesn't exist.
[email protected]77e4eca2010-09-21 13:23:071358 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1359 'The directory does not exist.') %
1360 (' '.join(command), self.checkout_path))
[email protected]5f3eee32009-09-17 00:34:301361 # There's no file list to retrieve.
1362 else:
[email protected]669600d2010-09-01 19:06:311363 self._RunAndGetFileList(command, options, file_list)
[email protected]e6f78352010-01-13 17:05:331364
[email protected]396e1a62013-07-03 19:41:041365 def GetUsableRev(self, rev, _options):
[email protected]e5d1e612011-12-19 19:49:191366 """Verifies the validity of the revision for this repository."""
1367 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1368 raise gclient_utils.Error(
1369 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1370 'correct.') % rev)
1371 return rev
1372
[email protected]e6f78352010-01-13 17:05:331373 def FullUrlForRelativeUrl(self, url):
1374 # Find the forth '/' and strip from there. A bit hackish.
1375 return '/'.join(self.url.split('/')[:4]) + url
[email protected]99828122010-06-04 01:41:021376
[email protected]669600d2010-09-01 19:06:311377 def _Run(self, args, options, **kwargs):
1378 """Runs a commands that goes to stdout."""
[email protected]8469bf92010-09-03 19:03:151379 kwargs.setdefault('cwd', self.checkout_path)
[email protected]669600d2010-09-01 19:06:311380 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
[email protected]77e4eca2010-09-21 13:23:071381 always=options.verbose, **kwargs)
[email protected]669600d2010-09-01 19:06:311382
[email protected]2702bcd2013-09-24 19:10:071383 def Svnversion(self):
1384 """Runs the lowest checked out revision in the current project."""
1385 info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1386 return info['Revision']
1387
[email protected]669600d2010-09-01 19:06:311388 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1389 """Runs a commands that goes to stdout and grabs the file listed."""
[email protected]8469bf92010-09-03 19:03:151390 cwd = cwd or self.checkout_path
[email protected]ce117f62011-01-17 20:04:251391 scm.SVN.RunAndGetFileList(
1392 options.verbose,
1393 args + ['--ignore-externals'],
1394 cwd=cwd,
[email protected]77e4eca2010-09-21 13:23:071395 file_list=file_list)
[email protected]669600d2010-09-01 19:06:311396
[email protected]6e29d572010-06-04 17:32:201397 @staticmethod
[email protected]8e0e9262010-08-17 19:20:271398 def _AddAdditionalUpdateFlags(command, options, revision):
[email protected]99828122010-06-04 01:41:021399 """Add additional flags to command depending on what options are set.
1400 command should be a list of strings that represents an svn command.
1401
1402 This method returns a new list to be used as a command."""
1403 new_command = command[:]
1404 if revision:
1405 new_command.extend(['--revision', str(revision).strip()])
[email protected]36ac2392011-10-12 16:36:111406 # We don't want interaction when jobs are used.
1407 if options.jobs > 1:
1408 new_command.append('--non-interactive')
[email protected]99828122010-06-04 01:41:021409 # --force was added to 'svn update' in svn 1.5.
[email protected]36ac2392011-10-12 16:36:111410 # --accept was added to 'svn update' in svn 1.6.
1411 if not scm.SVN.AssertVersion('1.5')[0]:
1412 return new_command
1413
1414 # It's annoying to have it block in the middle of a sync, just sensible
1415 # defaults.
1416 if options.force:
[email protected]99828122010-06-04 01:41:021417 new_command.append('--force')
[email protected]36ac2392011-10-12 16:36:111418 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1419 new_command.extend(('--accept', 'theirs-conflict'))
1420 elif options.manually_grab_svn_rev:
1421 new_command.append('--force')
1422 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1423 new_command.extend(('--accept', 'postpone'))
1424 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1425 new_command.extend(('--accept', 'postpone'))
[email protected]99828122010-06-04 01:41:021426 return new_command