blob: a466e3f7239d464ed8c258fb0ea5d7f13211a6e7 [file] [log] [blame]
steveblock@chromium.org93567042012-02-15 01:02:26 +00001# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00004
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00005"""Gclient-specific SCM-specific operations."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00006
maruel@chromium.org754960e2009-09-21 12:31:05 +00007import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00008import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00009import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000010import re
maruel@chromium.org90541732011-04-01 17:54:18 +000011import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000012import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013
14import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000015import scm
16import subprocess2
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000017
18
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000019class DiffFiltererWrapper(object):
20 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000021 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000022 working copy lines of the svn/git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000023 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000024 original_prefix = "--- "
25 working_prefix = "+++ "
26
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000027 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000028 # Note that we always use '/' as the path separator to be
29 # consistent with svn's cygwin-style output on Windows
30 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000031 self._current_file = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000032
maruel@chromium.org6e29d572010-06-04 17:32:20 +000033 def SetCurrentFile(self, current_file):
34 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000035
36 @property
37 def _replacement_file(self):
38 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000039
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000040 def _Replace(self, line):
41 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000042
43 def Filter(self, line):
44 if (line.startswith(self.index_string)):
45 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000046 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000047 else:
48 if (line.startswith(self.original_prefix) or
49 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000050 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000051 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000052
53
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000054class SvnDiffFilterer(DiffFiltererWrapper):
55 index_string = "Index: "
56
57
58class GitDiffFilterer(DiffFiltererWrapper):
59 index_string = "diff --git "
60
61 def SetCurrentFile(self, current_file):
62 # Get filename by parsing "a/<filename> b/<filename>"
63 self._current_file = current_file[:(len(current_file)/2)][2:]
64
65 def _Replace(self, line):
66 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
67
68
maruel@chromium.org90541732011-04-01 17:54:18 +000069def ask_for_data(prompt):
70 try:
71 return raw_input(prompt)
72 except KeyboardInterrupt:
73 # Hide the exception.
74 sys.exit(1)
75
76
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000077### SCM abstraction layer
78
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000079# Factory Method for SCM wrapper creation
80
maruel@chromium.org9eda4112010-06-11 18:56:10 +000081def GetScmName(url):
82 if url:
83 url, _ = gclient_utils.SplitUrlRevision(url)
84 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000085 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000086 url.endswith('.git')):
87 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000088 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000089 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000090 return 'svn'
91 return None
92
93
94def CreateSCM(url, root_dir=None, relpath=None):
95 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000096 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000097 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000098 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000099
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000100 scm_name = GetScmName(url)
101 if not scm_name in SCM_MAP:
102 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000103 scm_class = SCM_MAP[scm_name]
104 if not scm_class.BinaryExists():
105 raise gclient_utils.Error('%s command not found' % scm_name)
106 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000107
108
109# SCMWrapper base class
110
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000111class SCMWrapper(object):
112 """Add necessary glue between all the supported SCM.
113
msb@chromium.orgd6504212010-01-13 17:34:31 +0000114 This is the abstraction layer to bind to different SCM.
115 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000116 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000117 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000118 self._root_dir = root_dir
119 if self._root_dir:
120 self._root_dir = self._root_dir.replace('/', os.sep)
121 self.relpath = relpath
122 if self.relpath:
123 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000124 if self.relpath and self._root_dir:
125 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000126
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000127 def RunCommand(self, command, options, args, file_list=None):
128 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000129 if file_list is None:
130 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000131
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000132 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000133 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000134
135 if not command in commands:
136 raise gclient_utils.Error('Unknown command %s' % command)
137
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000138 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000139 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000140 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000141
142 return getattr(self, command)(options, args, file_list)
143
144
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000145class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000146 """Wrapper for Git"""
147
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000148 def __init__(self, url=None, root_dir=None, relpath=None):
149 """Removes 'git+' fake prefix from git URL."""
150 if url.startswith('git+http://') or url.startswith('git+https://'):
151 url = url[4:]
152 SCMWrapper.__init__(self, url, root_dir, relpath)
153
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000154 @staticmethod
155 def BinaryExists():
156 """Returns true if the command exists."""
157 try:
158 # We assume git is newer than 1.7. See: crbug.com/114483
159 result, version = scm.GIT.AssertVersion('1.7')
160 if not result:
161 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
162 return result
163 except OSError:
164 return False
165
floitsch@google.comeaab7842011-04-28 09:07:58 +0000166 def GetRevisionDate(self, revision):
167 """Returns the given revision's date in ISO-8601 format (which contains the
168 time zone)."""
169 # TODO(floitsch): get the time-stamp of the given revision and not just the
170 # time-stamp of the currently checked out revision.
171 return self._Capture(['log', '-n', '1', '--format=%ai'])
172
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000173 @staticmethod
174 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000175 """'Cleanup' the repo.
176
177 There's no real git equivalent for the svn cleanup command, do a no-op.
178 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000179
180 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000181 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000182 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000183
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000184 def pack(self, options, args, file_list):
185 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000186 repository.
187
188 The patch file is generated from a diff of the merge base of HEAD and
189 its upstream branch.
190 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000191 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000192 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000193 ['git', 'diff', merge_base],
194 cwd=self.checkout_path,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000195 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000196
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000197 def UpdateSubmoduleConfig(self):
198 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
199 'submodule.$name.ignore', '||',
200 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000201 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000202 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000203 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000204 try:
205 gclient_utils.CheckCallAndFilter(
206 cmd, cwd=self.checkout_path, print_stdout=False,
207 filter_fn=lambda x: None)
szager@chromium.org78f5c162012-06-22 22:34:25 +0000208 gclient_utils.CheckCallAndFilter(
209 cmd2, cwd=self.checkout_path, print_stdout=False,
210 filter_fn=lambda x: None)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000211 except subprocess2.CalledProcessError:
212 # Not a fatal error, or even very interesting in a non-git-submodule
213 # world. So just keep it quiet.
214 pass
215
msb@chromium.orge28e4982009-09-25 20:51:45 +0000216 def update(self, options, args, file_list):
217 """Runs git to update or transparently checkout the working copy.
218
219 All updated files will be appended to file_list.
220
221 Raises:
222 Error: if can't get URL for relative path.
223 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000224 if args:
225 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
226
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000227 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000228
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000229 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000230 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000231 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000232 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000233 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000234 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000235 # Override the revision number.
236 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000237 if revision == 'unmanaged':
238 revision = None
239 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000240 if not revision:
241 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000242
floitsch@google.comeaab7842011-04-28 09:07:58 +0000243 if gclient_utils.IsDateRevision(revision):
244 # Date-revisions only work on git-repositories if the reflog hasn't
245 # expired yet. Use rev-list to get the corresponding revision.
246 # git rev-list -n 1 --before='time-stamp' branchname
247 if options.transitive:
248 print('Warning: --transitive only works for SVN repositories.')
249 revision = default_rev
250
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000251 rev_str = ' at %s' % revision
252 files = []
253
254 printed_path = False
255 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000256 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000257 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000258 verbose = ['--verbose']
259 printed_path = True
260
261 if revision.startswith('refs/heads/'):
262 rev_type = "branch"
263 elif revision.startswith('origin/'):
264 # For compatability with old naming, translate 'origin' to 'refs/heads'
265 revision = revision.replace('origin/', 'refs/heads/')
266 rev_type = "branch"
267 else:
268 # hash is also a tag, only make a distinction at checkout
269 rev_type = "hash"
270
szager@google.com873e6672012-03-13 18:53:36 +0000271 if not os.path.exists(self.checkout_path) or (
272 os.path.isdir(self.checkout_path) and
273 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000274 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000275 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000276 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000277 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000278 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000279 if not verbose:
280 # Make the output a little prettier. It's nice to have some whitespace
281 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000282 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000283 return
284
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000285 if not managed:
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000286 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000287 print ('________ unmanaged solution; skipping %s' % self.relpath)
288 return
289
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000290 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
291 raise gclient_utils.Error('\n____ %s%s\n'
292 '\tPath is not a git repo. No .git dir.\n'
293 '\tTo resolve:\n'
294 '\t\trm -rf %s\n'
295 '\tAnd run gclient sync again\n'
296 % (self.relpath, rev_str, self.relpath))
297
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000298 # See if the url has changed (the unittests use git://foo for the url, let
299 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000300 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000301 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
302 # unit test pass. (and update the comment above)
303 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000304 print('_____ switching %s to a new upstream' % self.relpath)
305 # Make sure it's clean
306 self._CheckClean(rev_str)
307 # Switch over to the new upstream
308 self._Run(['remote', 'set-url', 'origin', url], options)
309 quiet = []
310 if not options.verbose:
311 quiet = ['--quiet']
312 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
313 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000314 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000315 files = self._Capture(['ls-files']).splitlines()
316 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
317 return
318
msb@chromium.org5bde4852009-12-14 16:47:12 +0000319 cur_branch = self._GetCurrentBranch()
320
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000321 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000322 # 0) HEAD is detached. Probably from our initial clone.
323 # - make sure HEAD is contained by a named ref, then update.
324 # Cases 1-4. HEAD is a branch.
325 # 1) current branch is not tracking a remote branch (could be git-svn)
326 # - try to rebase onto the new hash or branch
327 # 2) current branch is tracking a remote branch with local committed
328 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000329 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000330 # 3) current branch is tracking a remote branch w/or w/out changes,
331 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000332 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000333 # 4) current branch is tracking a remote branch, switches to a different
334 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000335 # - exit
336
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000337 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
338 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000339 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
340 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000341 if cur_branch is None:
342 upstream_branch = None
343 current_type = "detached"
344 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000345 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000346 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
347 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
348 current_type = "hash"
349 logging.debug("Current branch is not tracking an upstream (remote)"
350 " branch.")
351 elif upstream_branch.startswith('refs/remotes'):
352 current_type = "branch"
353 else:
354 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000355
maruel@chromium.org92067382012-06-28 19:58:41 +0000356 if (not re.match(r'^[0-9a-fA-F]{40}$', revision) or
357 not scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=revision)):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000358 # Update the remotes first so we have all the refs.
359 backoff_time = 5
360 for _ in range(10):
361 try:
362 remote_output = scm.GIT.Capture(
363 ['remote'] + verbose + ['update'],
364 cwd=self.checkout_path)
365 break
366 except subprocess2.CalledProcessError, e:
367 # Hackish but at that point, git is known to work so just checking for
368 # 502 in stderr should be fine.
369 if '502' in e.stderr:
370 print(str(e))
371 print('Sleeping %.1f seconds and retrying...' % backoff_time)
372 time.sleep(backoff_time)
373 backoff_time *= 1.3
374 continue
375 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000376
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000377 if verbose:
378 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000379
380 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000381 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000382 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000383
msb@chromium.org786fb682010-06-02 15:16:23 +0000384 if current_type == 'detached':
385 # case 0
386 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000387 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000388 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000389 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000390 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000391 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000392 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000393 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000394 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000395 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000396 newbase=revision, printed_path=printed_path)
397 printed_path = True
398 else:
399 # Can't find a merge-base since we don't know our upstream. That makes
400 # this command VERY likely to produce a rebase failure. For now we
401 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000402 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000403 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000404 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000405 self._AttemptRebase(upstream_branch, files, options,
406 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000407 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000408 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000409 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000410 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000411 newbase=revision, printed_path=printed_path)
412 printed_path = True
413 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
414 # case 4
415 new_base = revision.replace('heads', 'remotes/origin')
416 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000417 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000418 switch_error = ("Switching upstream branch from %s to %s\n"
419 % (upstream_branch, new_base) +
420 "Please merge or rebase manually:\n" +
421 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
422 "OR git checkout -b <some new branch> %s" % new_base)
423 raise gclient_utils.Error(switch_error)
424 else:
425 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000426 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000427 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000428 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000429 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000430 merge_args = ['merge']
431 if not options.merge:
432 merge_args.append('--ff-only')
433 merge_args.append(upstream_branch)
434 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000435 except subprocess2.CalledProcessError, e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000436 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
437 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000438 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000439 printed_path = True
440 while True:
441 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000442 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000443 action = ask_for_data(
444 'Cannot fast-forward merge, attempt to rebase? '
445 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000446 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000447 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000448 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000449 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000450 printed_path=printed_path)
451 printed_path = True
452 break
453 elif re.match(r'quit|q', action, re.I):
454 raise gclient_utils.Error("Can't fast-forward, please merge or "
455 "rebase manually.\n"
456 "cd %s && git " % self.checkout_path
457 + "rebase %s" % upstream_branch)
458 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000459 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000460 return
461 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000462 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000463 elif re.match("error: Your local changes to '.*' would be "
464 "overwritten by merge. Aborting.\nPlease, commit your "
465 "changes or stash them before you can merge.\n",
466 e.stderr):
467 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000468 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000469 printed_path = True
470 raise gclient_utils.Error(e.stderr)
471 else:
472 # Some other problem happened with the merge
473 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000474 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000475 raise
476 else:
477 # Fast-forward merge was successful
478 if not re.match('Already up-to-date.', merge_output) or verbose:
479 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000480 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000481 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000482 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 if not verbose:
484 # Make the output a little prettier. It's nice to have some
485 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000486 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000487
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000488 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000489 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000490
491 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000492 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000493 raise gclient_utils.Error('\n____ %s%s\n'
494 '\nConflict while rebasing this branch.\n'
495 'Fix the conflict and run gclient again.\n'
496 'See man git-rebase for details.\n'
497 % (self.relpath, rev_str))
498
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000499 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000500 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000501
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000502 # If --reset and --delete_unversioned_trees are specified, remove any
503 # untracked directories.
504 if options.reset and options.delete_unversioned_trees:
505 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
506 # merge-base by default), so doesn't include untracked files. So we use
507 # 'git ls-files --directory --others --exclude-standard' here directly.
508 paths = scm.GIT.Capture(
509 ['ls-files', '--directory', '--others', '--exclude-standard'],
510 self.checkout_path)
511 for path in (p for p in paths.splitlines() if p.endswith('/')):
512 full_path = os.path.join(self.checkout_path, path)
513 if not os.path.islink(full_path):
514 print('\n_____ removing unversioned directory %s' % path)
515 gclient_utils.RemoveDirectory(full_path)
516
517
msb@chromium.orge28e4982009-09-25 20:51:45 +0000518 def revert(self, options, args, file_list):
519 """Reverts local modifications.
520
521 All reverted files will be appended to file_list.
522 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000523 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000524 # revert won't work if the directory doesn't exist. It needs to
525 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000526 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000527 # Don't reuse the args.
528 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000529
530 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000531 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000532 if not deps_revision:
533 deps_revision = default_rev
534 if deps_revision.startswith('refs/heads/'):
535 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
536
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000537 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000538 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000539 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
540
msb@chromium.org0f282062009-11-06 20:14:02 +0000541 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000542 """Returns revision"""
543 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000544
msb@chromium.orge28e4982009-09-25 20:51:45 +0000545 def runhooks(self, options, args, file_list):
546 self.status(options, args, file_list)
547
548 def status(self, options, args, file_list):
549 """Display status information."""
550 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000551 print(('\n________ couldn\'t run status in %s:\n'
552 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000553 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000554 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000555 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000556 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000557 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
558
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000559 def GetUsableRev(self, rev, options):
560 """Finds a useful revision for this repository.
561
562 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
563 will be called on the source."""
564 sha1 = None
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000565 # Handles an SVN rev. As an optimization, only verify an SVN revision as
566 # [0-9]{1,6} for now to avoid making a network request.
567 if rev.isdigit() and len(rev) < 7:
568 # If the content of the safesync_url appears to be an SVN rev and the
569 # URL of the source appears to be git, we can only attempt to find out
570 # if a revision is useful after we've cloned the original URL, so just
571 # ignore for now.
572 if (os.path.isdir(self.checkout_path) and
573 scm.GIT.IsGitSvn(cwd=self.checkout_path)):
574 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
575 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000576 try:
577 logging.debug('Looking for git-svn configuration optimizations.')
578 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
579 cwd=self.checkout_path):
580 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
581 except subprocess2.CalledProcessError:
582 logging.debug('git config --get svn-remote.svn.fetch failed, '
583 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000584 if options.verbose:
585 print('Running git svn fetch. This might take a while.\n')
586 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
587 sha1 = scm.GIT.GetSha1ForSvnRev(cwd=self.checkout_path, rev=rev)
588 if not sha1:
589 raise gclient_utils.Error(
590 ( 'It appears that either your git-svn remote is incorrectly\n'
591 'configured or the revision in your safesync_url is\n'
592 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
593 'corresponding git hash for SVN rev %s.' ) % rev)
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000594 elif scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
595 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000596
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000597 if not sha1:
598 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000599 ( 'We could not find a valid hash for safesync_url response "%s".\n'
600 'Safesync URLs with a git checkout currently require a git-svn\n'
601 'remote or a safesync_url that provides git sha1s. Please add a\n'
602 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000603 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000604 '#Initial_checkout' ) % rev)
605
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000606 return sha1
607
msb@chromium.orge6f78352010-01-13 17:05:33 +0000608 def FullUrlForRelativeUrl(self, url):
609 # Strip from last '/'
610 # Equivalent to unix basename
611 base_url = self.url
612 return base_url[:base_url.rfind('/')] + url
613
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000614 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000615 """Clone a git repository from the given URL.
616
msb@chromium.org786fb682010-06-02 15:16:23 +0000617 Once we've cloned the repo, we checkout a working branch if the specified
618 revision is a branch head. If it is a tag or a specific commit, then we
619 leave HEAD detached as it makes future updates simpler -- in this case the
620 user should first create a new branch or switch to an existing branch before
621 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000622 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000623 # git clone doesn't seem to insert a newline properly before printing
624 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000625 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000626
szager@google.com85d3e3a2011-10-07 17:12:00 +0000627 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000628 if revision.startswith('refs/heads/'):
629 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
630 detach_head = False
631 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000632 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000633 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000634 clone_cmd.append('--verbose')
635 clone_cmd.extend([url, self.checkout_path])
636
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000637 # If the parent directory does not exist, Git clone on Windows will not
638 # create it, so we need to do it manually.
639 parent_dir = os.path.dirname(self.checkout_path)
640 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000641 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000642
szager@google.com85d3e3a2011-10-07 17:12:00 +0000643 percent_re = re.compile('.* ([0-9]{1,2})% .*')
644 def _GitFilter(line):
645 # git uses an escape sequence to clear the line; elide it.
646 esc = line.find(unichr(033))
647 if esc > -1:
648 line = line[:esc]
649 match = percent_re.match(line)
650 if not match or not int(match.group(1)) % 10:
651 print '%s' % line
652
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000653 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000654 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000655 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
656 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000657 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000658 except subprocess2.CalledProcessError, e:
659 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000660 # We should check for "transfer closed with NNN bytes remaining to
661 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000662 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000663 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000664 print(str(e))
665 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000666 continue
667 raise e
668
msb@chromium.org786fb682010-06-02 15:16:23 +0000669 if detach_head:
670 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000671 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000672 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000673 ('Checked out %s to a detached HEAD. Before making any commits\n'
674 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
675 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
676 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000677
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000678 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000679 branch=None, printed_path=False):
680 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000681 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000682 revision = upstream
683 if newbase:
684 revision = newbase
685 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000686 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000687 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000688 printed_path = True
689 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000690 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000691
692 # Build the rebase command here using the args
693 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
694 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000695 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000696 rebase_cmd.append('--verbose')
697 if newbase:
698 rebase_cmd.extend(['--onto', newbase])
699 rebase_cmd.append(upstream)
700 if branch:
701 rebase_cmd.append(branch)
702
703 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000704 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000705 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000706 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
707 re.match(r'cannot rebase: your index contains uncommitted changes',
708 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000709 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000710 rebase_action = ask_for_data(
711 'Cannot rebase because of unstaged changes.\n'
712 '\'git reset --hard HEAD\' ?\n'
713 'WARNING: destroys any uncommitted work in your current branch!'
714 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000715 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000716 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000717 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000718 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000719 break
720 elif re.match(r'quit|q', rebase_action, re.I):
721 raise gclient_utils.Error("Please merge or rebase manually\n"
722 "cd %s && git " % self.checkout_path
723 + "%s" % ' '.join(rebase_cmd))
724 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000725 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000726 continue
727 else:
728 gclient_utils.Error("Input not recognized")
729 continue
730 elif re.search(r'^CONFLICT', e.stdout, re.M):
731 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
732 "Fix the conflict and run gclient again.\n"
733 "See 'man git-rebase' for details.\n")
734 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000735 print(e.stdout.strip())
736 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000737 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
738 "manually.\ncd %s && git " %
739 self.checkout_path
740 + "%s" % ' '.join(rebase_cmd))
741
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000742 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000743 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000744 # Make the output a little prettier. It's nice to have some
745 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000746 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000747
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000748 @staticmethod
749 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000750 (ok, current_version) = scm.GIT.AssertVersion(min_version)
751 if not ok:
752 raise gclient_utils.Error('git version %s < minimum required %s' %
753 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000754
msb@chromium.org786fb682010-06-02 15:16:23 +0000755 def _IsRebasing(self):
756 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
757 # have a plumbing command to determine whether a rebase is in progress, so
758 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
759 g = os.path.join(self.checkout_path, '.git')
760 return (
761 os.path.isdir(os.path.join(g, "rebase-merge")) or
762 os.path.isdir(os.path.join(g, "rebase-apply")))
763
764 def _CheckClean(self, rev_str):
765 # Make sure the tree is clean; see git-rebase.sh for reference
766 try:
767 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000768 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000769 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000770 raise gclient_utils.Error('\n____ %s%s\n'
771 '\tYou have unstaged changes.\n'
772 '\tPlease commit, stash, or reset.\n'
773 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000774 try:
775 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000776 '--ignore-submodules', 'HEAD', '--'],
777 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000778 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000779 raise gclient_utils.Error('\n____ %s%s\n'
780 '\tYour index contains uncommitted changes\n'
781 '\tPlease commit, stash, or reset.\n'
782 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000783
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000784 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000785 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
786 # reference by a commit). If not, error out -- most likely a rebase is
787 # in progress, try to detect so we can give a better error.
788 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000789 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
790 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000791 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000792 # Commit is not contained by any rev. See if the user is rebasing:
793 if self._IsRebasing():
794 # Punt to the user
795 raise gclient_utils.Error('\n____ %s%s\n'
796 '\tAlready in a conflict, i.e. (no branch).\n'
797 '\tFix the conflict and run gclient again.\n'
798 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
799 '\tSee man git-rebase for details.\n'
800 % (self.relpath, rev_str))
801 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000802 name = ('saved-by-gclient-' +
803 self._Capture(['rev-parse', '--short', 'HEAD']))
804 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000805 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000806 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000807
msb@chromium.org5bde4852009-12-14 16:47:12 +0000808 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000809 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000810 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000811 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000812 return None
813 return branch
814
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000815 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000816 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000817 ['git'] + args,
818 stderr=subprocess2.PIPE,
819 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000820
maruel@chromium.org37e89872010-09-07 16:11:33 +0000821 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000822 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000823 kwargs.setdefault('print_stdout', True)
824 stdout = kwargs.get('stdout', sys.stdout)
825 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
826 ' '.join(args), kwargs['cwd']))
827 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000828
829
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000830class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000831 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000832
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000833 @staticmethod
834 def BinaryExists():
835 """Returns true if the command exists."""
836 try:
837 result, version = scm.SVN.AssertVersion('1.4')
838 if not result:
839 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
840 return result
841 except OSError:
842 return False
843
floitsch@google.comeaab7842011-04-28 09:07:58 +0000844 def GetRevisionDate(self, revision):
845 """Returns the given revision's date in ISO-8601 format (which contains the
846 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000847 date = scm.SVN.Capture(
848 ['propget', '--revprop', 'svn:date', '-r', revision],
849 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000850 return date.strip()
851
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000852 def cleanup(self, options, args, file_list):
853 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000854 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000855
856 def diff(self, options, args, file_list):
857 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000858 if not os.path.isdir(self.checkout_path):
859 raise gclient_utils.Error('Directory %s is not present.' %
860 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000861 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000862
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000863 def pack(self, options, args, file_list):
864 """Generates a patch file which can be applied to the root of the
865 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000866 if not os.path.isdir(self.checkout_path):
867 raise gclient_utils.Error('Directory %s is not present.' %
868 self.checkout_path)
869 gclient_utils.CheckCallAndFilter(
870 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
871 cwd=self.checkout_path,
872 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000873 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000874
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000875 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000876 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000877
878 All updated files will be appended to file_list.
879
880 Raises:
881 Error: if can't get URL for relative path.
882 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000883 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000884 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000885 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000886 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000887 return
888
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000889 hg_path = os.path.join(self.checkout_path, '.hg')
890 if os.path.exists(hg_path):
891 print('________ found .hg directory; skipping %s' % self.relpath)
892 return
893
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000894 if args:
895 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
896
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000897 # revision is the revision to match. It is None if no revision is specified,
898 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000899 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000900 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000901 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000902 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000903 if options.revision:
904 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000905 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000906 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000907 if revision != 'unmanaged':
908 forced_revision = True
909 # Reconstruct the url.
910 url = '%s@%s' % (url, revision)
911 rev_str = ' at %s' % revision
912 else:
913 managed = False
914 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000915 else:
916 forced_revision = False
917 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000918
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000919 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000920 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000921 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000922 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000923 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000924 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000925 return
926
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000927 if not managed:
928 print ('________ unmanaged solution; skipping %s' % self.relpath)
929 return
930
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000931 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000932 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000933 from_info = scm.SVN.CaptureLocalInfo(
934 [], os.path.join(self.checkout_path, '.'))
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000935 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000936 raise gclient_utils.Error(
937 ('Can\'t update/checkout %s if an unversioned directory is present. '
938 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000939
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +0000940 if 'URL' not in from_info:
941 raise gclient_utils.Error(
942 ('gclient is confused. Couldn\'t get the url for %s.\n'
943 'Try using @unmanaged.\n%s') % (
944 self.checkout_path, from_info))
945
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000946 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000947 dir_info = scm.SVN.CaptureStatus(
948 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000949 if any(d[0][2] == 'L' for d in dir_info):
950 try:
951 self._Run(['cleanup', self.checkout_path], options)
952 except subprocess2.CalledProcessError, e:
953 # Get the status again, svn cleanup may have cleaned up at least
954 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000955 dir_info = scm.SVN.CaptureStatus(
956 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000957
958 # Try to fix the failures by removing troublesome files.
959 for d in dir_info:
960 if d[0][2] == 'L':
961 if d[0][0] == '!' and options.force:
962 print 'Removing troublesome path %s' % d[1]
963 gclient_utils.rmtree(d[1])
964 else:
965 print 'Not removing troublesome path %s automatically.' % d[1]
966 if d[0][0] == '!':
967 print 'You can pass --force to enable automatic removal.'
968 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000969
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000970 # Retrieve the current HEAD version because svn is slow at null updates.
971 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000972 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000973 revision = str(from_info_live['Revision'])
974 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000975
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000976 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000977 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000978 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000979 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000980 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000981 # The url is invalid or the server is not accessible, it's safer to bail
982 # out right now.
983 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000984 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
985 and (from_info['UUID'] == to_info['UUID']))
986 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000987 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000988 # We have different roots, so check if we can switch --relocate.
989 # Subversion only permits this if the repository UUIDs match.
990 # Perform the switch --relocate, then rewrite the from_url
991 # to reflect where we "are now." (This is the same way that
992 # Subversion itself handles the metadata when switch --relocate
993 # is used.) This makes the checks below for whether we
994 # can update to a revision or have to switch to a different
995 # branch work as expected.
996 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000997 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000998 from_info['Repository Root'],
999 to_info['Repository Root'],
1000 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001001 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001002 from_info['URL'] = from_info['URL'].replace(
1003 from_info['Repository Root'],
1004 to_info['Repository Root'])
1005 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001006 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001007 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001008 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001009 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001010 raise gclient_utils.Error(
1011 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1012 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001013 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001014 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001015 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001016 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001017 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001018 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001019 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001020 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001021 return
1022
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001023 # If the provided url has a revision number that matches the revision
1024 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001025 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001026 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001027 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001028 else:
1029 command = ['update', self.checkout_path]
1030 command = self._AddAdditionalUpdateFlags(command, options, revision)
1031 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001032
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001033 # If --reset and --delete_unversioned_trees are specified, remove any
1034 # untracked files and directories.
1035 if options.reset and options.delete_unversioned_trees:
1036 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1037 full_path = os.path.join(self.checkout_path, status[1])
1038 if (status[0][0] == '?'
1039 and os.path.isdir(full_path)
1040 and not os.path.islink(full_path)):
1041 print('\n_____ removing unversioned directory %s' % status[1])
1042 gclient_utils.RemoveDirectory(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001043
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001044 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001045 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001046 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001047 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001048 # Create an empty checkout and then update the one file we want. Future
1049 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001050 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001051 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001052 if os.path.exists(os.path.join(self.checkout_path, filename)):
1053 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001054 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001055 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001056 # After the initial checkout, we can use update as if it were any other
1057 # dep.
1058 self.update(options, args, file_list)
1059 else:
1060 # If the installed version of SVN doesn't support --depth, fallback to
1061 # just exporting the file. This has the downside that revision
1062 # information is not stored next to the file, so we will have to
1063 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001064 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001065 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001066 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001067 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001068 command = self._AddAdditionalUpdateFlags(command, options,
1069 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001070 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001071
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001072 def revert(self, options, args, file_list):
1073 """Reverts local modifications. Subversion specific.
1074
1075 All reverted files will be appended to file_list, even if Subversion
1076 doesn't know about them.
1077 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001078 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001079 if os.path.exists(self.checkout_path):
1080 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001081 # svn revert won't work if the directory doesn't exist. It needs to
1082 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001083 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001084 # Don't reuse the args.
1085 return self.update(options, [], file_list)
1086
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001087 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1088 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1089 print('________ found .git directory; skipping %s' % self.relpath)
1090 return
1091 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1092 print('________ found .hg directory; skipping %s' % self.relpath)
1093 return
1094 if not options.force:
1095 raise gclient_utils.Error('Invalid checkout path, aborting')
1096 print(
1097 '\n_____ %s is not a valid svn checkout, synching instead' %
1098 self.relpath)
1099 gclient_utils.rmtree(self.checkout_path)
1100 # Don't reuse the args.
1101 return self.update(options, [], file_list)
1102
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001103 def printcb(file_status):
1104 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001105 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001106 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001107 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001108 print(os.path.join(self.checkout_path, file_status[1]))
1109 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001110
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001111 # Revert() may delete the directory altogether.
1112 if not os.path.isdir(self.checkout_path):
1113 # Don't reuse the args.
1114 return self.update(options, [], file_list)
1115
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001116 try:
1117 # svn revert is so broken we don't even use it. Using
1118 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001119 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001120 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1121 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001122 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001123 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001124 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001125
msb@chromium.org0f282062009-11-06 20:14:02 +00001126 def revinfo(self, options, args, file_list):
1127 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001128 try:
1129 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001130 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001131 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001132
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001133 def runhooks(self, options, args, file_list):
1134 self.status(options, args, file_list)
1135
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001136 def status(self, options, args, file_list):
1137 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001138 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001139 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001140 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001141 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1142 'The directory does not exist.') %
1143 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001144 # There's no file list to retrieve.
1145 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001146 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001147
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001148 def GetUsableRev(self, rev, options):
1149 """Verifies the validity of the revision for this repository."""
1150 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1151 raise gclient_utils.Error(
1152 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1153 'correct.') % rev)
1154 return rev
1155
msb@chromium.orge6f78352010-01-13 17:05:33 +00001156 def FullUrlForRelativeUrl(self, url):
1157 # Find the forth '/' and strip from there. A bit hackish.
1158 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001159
maruel@chromium.org669600d2010-09-01 19:06:31 +00001160 def _Run(self, args, options, **kwargs):
1161 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001162 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001163 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001164 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001165
1166 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1167 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001168 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001169 scm.SVN.RunAndGetFileList(
1170 options.verbose,
1171 args + ['--ignore-externals'],
1172 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001173 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001174
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001175 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001176 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001177 """Add additional flags to command depending on what options are set.
1178 command should be a list of strings that represents an svn command.
1179
1180 This method returns a new list to be used as a command."""
1181 new_command = command[:]
1182 if revision:
1183 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001184 # We don't want interaction when jobs are used.
1185 if options.jobs > 1:
1186 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001187 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001188 # --accept was added to 'svn update' in svn 1.6.
1189 if not scm.SVN.AssertVersion('1.5')[0]:
1190 return new_command
1191
1192 # It's annoying to have it block in the middle of a sync, just sensible
1193 # defaults.
1194 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001195 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001196 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1197 new_command.extend(('--accept', 'theirs-conflict'))
1198 elif options.manually_grab_svn_rev:
1199 new_command.append('--force')
1200 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1201 new_command.extend(('--accept', 'postpone'))
1202 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1203 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001204 return new_command