blob: 374c9780a77efeef78fc6332acaff8a03627b374 [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)]
203 try:
204 gclient_utils.CheckCallAndFilter(
205 cmd, cwd=self.checkout_path, print_stdout=False,
206 filter_fn=lambda x: None)
207 except subprocess2.CalledProcessError:
208 # Not a fatal error, or even very interesting in a non-git-submodule
209 # world. So just keep it quiet.
210 pass
211
msb@chromium.orge28e4982009-09-25 20:51:45 +0000212 def update(self, options, args, file_list):
213 """Runs git to update or transparently checkout the working copy.
214
215 All updated files will be appended to file_list.
216
217 Raises:
218 Error: if can't get URL for relative path.
219 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000220 if args:
221 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
222
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000223 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000224
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000225 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000226 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000227 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000228 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000229 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000230 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000231 # Override the revision number.
232 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000233 if revision == 'unmanaged':
234 revision = None
235 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000236 if not revision:
237 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000238
floitsch@google.comeaab7842011-04-28 09:07:58 +0000239 if gclient_utils.IsDateRevision(revision):
240 # Date-revisions only work on git-repositories if the reflog hasn't
241 # expired yet. Use rev-list to get the corresponding revision.
242 # git rev-list -n 1 --before='time-stamp' branchname
243 if options.transitive:
244 print('Warning: --transitive only works for SVN repositories.')
245 revision = default_rev
246
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000247 rev_str = ' at %s' % revision
248 files = []
249
250 printed_path = False
251 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000252 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000253 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000254 verbose = ['--verbose']
255 printed_path = True
256
257 if revision.startswith('refs/heads/'):
258 rev_type = "branch"
259 elif revision.startswith('origin/'):
260 # For compatability with old naming, translate 'origin' to 'refs/heads'
261 revision = revision.replace('origin/', 'refs/heads/')
262 rev_type = "branch"
263 else:
264 # hash is also a tag, only make a distinction at checkout
265 rev_type = "hash"
266
szager@google.com873e6672012-03-13 18:53:36 +0000267 if not os.path.exists(self.checkout_path) or (
268 os.path.isdir(self.checkout_path) and
269 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000270 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000271 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000272 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000273 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000274 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000275 if not verbose:
276 # Make the output a little prettier. It's nice to have some whitespace
277 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000278 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000279 return
280
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000281 if not managed:
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000282 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000283 print ('________ unmanaged solution; skipping %s' % self.relpath)
284 return
285
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000286 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
287 raise gclient_utils.Error('\n____ %s%s\n'
288 '\tPath is not a git repo. No .git dir.\n'
289 '\tTo resolve:\n'
290 '\t\trm -rf %s\n'
291 '\tAnd run gclient sync again\n'
292 % (self.relpath, rev_str, self.relpath))
293
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000294 # See if the url has changed (the unittests use git://foo for the url, let
295 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000296 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000297 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
298 # unit test pass. (and update the comment above)
299 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000300 print('_____ switching %s to a new upstream' % self.relpath)
301 # Make sure it's clean
302 self._CheckClean(rev_str)
303 # Switch over to the new upstream
304 self._Run(['remote', 'set-url', 'origin', url], options)
305 quiet = []
306 if not options.verbose:
307 quiet = ['--quiet']
308 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
309 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000310 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000311 files = self._Capture(['ls-files']).splitlines()
312 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
313 return
314
msb@chromium.org5bde4852009-12-14 16:47:12 +0000315 cur_branch = self._GetCurrentBranch()
316
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000317 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000318 # 0) HEAD is detached. Probably from our initial clone.
319 # - make sure HEAD is contained by a named ref, then update.
320 # Cases 1-4. HEAD is a branch.
321 # 1) current branch is not tracking a remote branch (could be git-svn)
322 # - try to rebase onto the new hash or branch
323 # 2) current branch is tracking a remote branch with local committed
324 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000325 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000326 # 3) current branch is tracking a remote branch w/or w/out changes,
327 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000328 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000329 # 4) current branch is tracking a remote branch, switches to a different
330 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000331 # - exit
332
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000333 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
334 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000335 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
336 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000337 if cur_branch is None:
338 upstream_branch = None
339 current_type = "detached"
340 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000341 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000342 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
343 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
344 current_type = "hash"
345 logging.debug("Current branch is not tracking an upstream (remote)"
346 " branch.")
347 elif upstream_branch.startswith('refs/remotes'):
348 current_type = "branch"
349 else:
350 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000351
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000352 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000353 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000354 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000355 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000356 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000357 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000358 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000359 break
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000360 except subprocess2.CalledProcessError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000361 # Hackish but at that point, git is known to work so just checking for
362 # 502 in stderr should be fine.
363 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000364 print(str(e))
365 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000366 time.sleep(backoff_time)
367 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000368 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000369 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000370
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000371 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000372 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000373
374 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000375 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000376 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000377
msb@chromium.org786fb682010-06-02 15:16:23 +0000378 if current_type == 'detached':
379 # case 0
380 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000381 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000382 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000383 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000384 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000385 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000386 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000387 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000388 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000389 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000390 newbase=revision, printed_path=printed_path)
391 printed_path = True
392 else:
393 # Can't find a merge-base since we don't know our upstream. That makes
394 # this command VERY likely to produce a rebase failure. For now we
395 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000396 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000397 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000398 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000399 self._AttemptRebase(upstream_branch, files, options,
400 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000401 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000402 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000403 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000404 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000405 newbase=revision, printed_path=printed_path)
406 printed_path = True
407 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
408 # case 4
409 new_base = revision.replace('heads', 'remotes/origin')
410 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000411 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000412 switch_error = ("Switching upstream branch from %s to %s\n"
413 % (upstream_branch, new_base) +
414 "Please merge or rebase manually:\n" +
415 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
416 "OR git checkout -b <some new branch> %s" % new_base)
417 raise gclient_utils.Error(switch_error)
418 else:
419 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000420 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000421 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000422 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000423 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000424 merge_args = ['merge']
425 if not options.merge:
426 merge_args.append('--ff-only')
427 merge_args.append(upstream_branch)
428 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000429 except subprocess2.CalledProcessError, e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000430 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
431 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000432 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000433 printed_path = True
434 while True:
435 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000436 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000437 action = ask_for_data(
438 'Cannot fast-forward merge, attempt to rebase? '
439 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000440 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000441 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000442 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000443 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000444 printed_path=printed_path)
445 printed_path = True
446 break
447 elif re.match(r'quit|q', action, re.I):
448 raise gclient_utils.Error("Can't fast-forward, please merge or "
449 "rebase manually.\n"
450 "cd %s && git " % self.checkout_path
451 + "rebase %s" % upstream_branch)
452 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000453 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000454 return
455 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000456 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000457 elif re.match("error: Your local changes to '.*' would be "
458 "overwritten by merge. Aborting.\nPlease, commit your "
459 "changes or stash them before you can merge.\n",
460 e.stderr):
461 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000462 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000463 printed_path = True
464 raise gclient_utils.Error(e.stderr)
465 else:
466 # Some other problem happened with the merge
467 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000468 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000469 raise
470 else:
471 # Fast-forward merge was successful
472 if not re.match('Already up-to-date.', merge_output) or verbose:
473 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000474 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000475 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000476 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000477 if not verbose:
478 # Make the output a little prettier. It's nice to have some
479 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000480 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000481
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000482 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000484
485 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000486 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000487 raise gclient_utils.Error('\n____ %s%s\n'
488 '\nConflict while rebasing this branch.\n'
489 'Fix the conflict and run gclient again.\n'
490 'See man git-rebase for details.\n'
491 % (self.relpath, rev_str))
492
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000493 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000494 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000495
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000496 # If --reset and --delete_unversioned_trees are specified, remove any
497 # untracked directories.
498 if options.reset and options.delete_unversioned_trees:
499 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
500 # merge-base by default), so doesn't include untracked files. So we use
501 # 'git ls-files --directory --others --exclude-standard' here directly.
502 paths = scm.GIT.Capture(
503 ['ls-files', '--directory', '--others', '--exclude-standard'],
504 self.checkout_path)
505 for path in (p for p in paths.splitlines() if p.endswith('/')):
506 full_path = os.path.join(self.checkout_path, path)
507 if not os.path.islink(full_path):
508 print('\n_____ removing unversioned directory %s' % path)
509 gclient_utils.RemoveDirectory(full_path)
510
511
msb@chromium.orge28e4982009-09-25 20:51:45 +0000512 def revert(self, options, args, file_list):
513 """Reverts local modifications.
514
515 All reverted files will be appended to file_list.
516 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000517 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000518 # revert won't work if the directory doesn't exist. It needs to
519 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000520 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000521 # Don't reuse the args.
522 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000523
524 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000525 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000526 if not deps_revision:
527 deps_revision = default_rev
528 if deps_revision.startswith('refs/heads/'):
529 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
530
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000531 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000532 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000533 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
534
msb@chromium.org0f282062009-11-06 20:14:02 +0000535 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000536 """Returns revision"""
537 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000538
msb@chromium.orge28e4982009-09-25 20:51:45 +0000539 def runhooks(self, options, args, file_list):
540 self.status(options, args, file_list)
541
542 def status(self, options, args, file_list):
543 """Display status information."""
544 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000545 print(('\n________ couldn\'t run status in %s:\n'
546 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000547 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000548 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000549 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000550 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000551 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
552
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000553 def GetUsableRev(self, rev, options):
554 """Finds a useful revision for this repository.
555
556 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
557 will be called on the source."""
558 sha1 = None
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000559 # Handles an SVN rev. As an optimization, only verify an SVN revision as
560 # [0-9]{1,6} for now to avoid making a network request.
561 if rev.isdigit() and len(rev) < 7:
562 # If the content of the safesync_url appears to be an SVN rev and the
563 # URL of the source appears to be git, we can only attempt to find out
564 # if a revision is useful after we've cloned the original URL, so just
565 # ignore for now.
566 if (os.path.isdir(self.checkout_path) and
567 scm.GIT.IsGitSvn(cwd=self.checkout_path)):
568 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
569 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000570 try:
571 logging.debug('Looking for git-svn configuration optimizations.')
572 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
573 cwd=self.checkout_path):
574 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
575 except subprocess2.CalledProcessError:
576 logging.debug('git config --get svn-remote.svn.fetch failed, '
577 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000578 if options.verbose:
579 print('Running git svn fetch. This might take a while.\n')
580 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
581 sha1 = scm.GIT.GetSha1ForSvnRev(cwd=self.checkout_path, rev=rev)
582 if not sha1:
583 raise gclient_utils.Error(
584 ( 'It appears that either your git-svn remote is incorrectly\n'
585 'configured or the revision in your safesync_url is\n'
586 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
587 'corresponding git hash for SVN rev %s.' ) % rev)
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000588 elif scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
589 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000590
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000591 if not sha1:
592 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000593 ( 'We could not find a valid hash for safesync_url response "%s".\n'
594 'Safesync URLs with a git checkout currently require a git-svn\n'
595 'remote or a safesync_url that provides git sha1s. Please add a\n'
596 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000597 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000598 '#Initial_checkout' ) % rev)
599
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000600 return sha1
601
msb@chromium.orge6f78352010-01-13 17:05:33 +0000602 def FullUrlForRelativeUrl(self, url):
603 # Strip from last '/'
604 # Equivalent to unix basename
605 base_url = self.url
606 return base_url[:base_url.rfind('/')] + url
607
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000608 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000609 """Clone a git repository from the given URL.
610
msb@chromium.org786fb682010-06-02 15:16:23 +0000611 Once we've cloned the repo, we checkout a working branch if the specified
612 revision is a branch head. If it is a tag or a specific commit, then we
613 leave HEAD detached as it makes future updates simpler -- in this case the
614 user should first create a new branch or switch to an existing branch before
615 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000616 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000617 # git clone doesn't seem to insert a newline properly before printing
618 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000619 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000620
szager@google.com85d3e3a2011-10-07 17:12:00 +0000621 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000622 if revision.startswith('refs/heads/'):
623 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
624 detach_head = False
625 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000626 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000627 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000628 clone_cmd.append('--verbose')
629 clone_cmd.extend([url, self.checkout_path])
630
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000631 # If the parent directory does not exist, Git clone on Windows will not
632 # create it, so we need to do it manually.
633 parent_dir = os.path.dirname(self.checkout_path)
634 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000635 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000636
szager@google.com85d3e3a2011-10-07 17:12:00 +0000637 percent_re = re.compile('.* ([0-9]{1,2})% .*')
638 def _GitFilter(line):
639 # git uses an escape sequence to clear the line; elide it.
640 esc = line.find(unichr(033))
641 if esc > -1:
642 line = line[:esc]
643 match = percent_re.match(line)
644 if not match or not int(match.group(1)) % 10:
645 print '%s' % line
646
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000647 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000648 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000649 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
650 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000651 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000652 except subprocess2.CalledProcessError, e:
653 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000654 # We should check for "transfer closed with NNN bytes remaining to
655 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000656 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000657 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000658 print(str(e))
659 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000660 continue
661 raise e
662
msb@chromium.org786fb682010-06-02 15:16:23 +0000663 if detach_head:
664 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000665 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000666 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000667 ('Checked out %s to a detached HEAD. Before making any commits\n'
668 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
669 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
670 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000671
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000672 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000673 branch=None, printed_path=False):
674 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000675 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000676 revision = upstream
677 if newbase:
678 revision = newbase
679 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000680 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000681 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000682 printed_path = True
683 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000684 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000685
686 # Build the rebase command here using the args
687 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
688 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000689 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000690 rebase_cmd.append('--verbose')
691 if newbase:
692 rebase_cmd.extend(['--onto', newbase])
693 rebase_cmd.append(upstream)
694 if branch:
695 rebase_cmd.append(branch)
696
697 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000698 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000699 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000700 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
701 re.match(r'cannot rebase: your index contains uncommitted changes',
702 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000703 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000704 rebase_action = ask_for_data(
705 'Cannot rebase because of unstaged changes.\n'
706 '\'git reset --hard HEAD\' ?\n'
707 'WARNING: destroys any uncommitted work in your current branch!'
708 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000709 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000710 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000711 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000712 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000713 break
714 elif re.match(r'quit|q', rebase_action, re.I):
715 raise gclient_utils.Error("Please merge or rebase manually\n"
716 "cd %s && git " % self.checkout_path
717 + "%s" % ' '.join(rebase_cmd))
718 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000719 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000720 continue
721 else:
722 gclient_utils.Error("Input not recognized")
723 continue
724 elif re.search(r'^CONFLICT', e.stdout, re.M):
725 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
726 "Fix the conflict and run gclient again.\n"
727 "See 'man git-rebase' for details.\n")
728 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000729 print(e.stdout.strip())
730 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000731 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
732 "manually.\ncd %s && git " %
733 self.checkout_path
734 + "%s" % ' '.join(rebase_cmd))
735
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000736 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000737 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000738 # Make the output a little prettier. It's nice to have some
739 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000740 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000741
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000742 @staticmethod
743 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000744 (ok, current_version) = scm.GIT.AssertVersion(min_version)
745 if not ok:
746 raise gclient_utils.Error('git version %s < minimum required %s' %
747 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000748
msb@chromium.org786fb682010-06-02 15:16:23 +0000749 def _IsRebasing(self):
750 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
751 # have a plumbing command to determine whether a rebase is in progress, so
752 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
753 g = os.path.join(self.checkout_path, '.git')
754 return (
755 os.path.isdir(os.path.join(g, "rebase-merge")) or
756 os.path.isdir(os.path.join(g, "rebase-apply")))
757
758 def _CheckClean(self, rev_str):
759 # Make sure the tree is clean; see git-rebase.sh for reference
760 try:
761 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000762 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000763 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000764 raise gclient_utils.Error('\n____ %s%s\n'
765 '\tYou have unstaged changes.\n'
766 '\tPlease commit, stash, or reset.\n'
767 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000768 try:
769 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000770 '--ignore-submodules', 'HEAD', '--'],
771 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000772 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000773 raise gclient_utils.Error('\n____ %s%s\n'
774 '\tYour index contains uncommitted changes\n'
775 '\tPlease commit, stash, or reset.\n'
776 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000777
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000778 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000779 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
780 # reference by a commit). If not, error out -- most likely a rebase is
781 # in progress, try to detect so we can give a better error.
782 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000783 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
784 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000785 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000786 # Commit is not contained by any rev. See if the user is rebasing:
787 if self._IsRebasing():
788 # Punt to the user
789 raise gclient_utils.Error('\n____ %s%s\n'
790 '\tAlready in a conflict, i.e. (no branch).\n'
791 '\tFix the conflict and run gclient again.\n'
792 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
793 '\tSee man git-rebase for details.\n'
794 % (self.relpath, rev_str))
795 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000796 name = ('saved-by-gclient-' +
797 self._Capture(['rev-parse', '--short', 'HEAD']))
798 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000799 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000800 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000801
msb@chromium.org5bde4852009-12-14 16:47:12 +0000802 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000803 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000804 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000805 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000806 return None
807 return branch
808
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000809 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000810 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000811 ['git'] + args,
812 stderr=subprocess2.PIPE,
813 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000814
maruel@chromium.org37e89872010-09-07 16:11:33 +0000815 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000816 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000817 kwargs.setdefault('print_stdout', True)
818 stdout = kwargs.get('stdout', sys.stdout)
819 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
820 ' '.join(args), kwargs['cwd']))
821 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000822
823
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000824class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000825 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000826
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000827 @staticmethod
828 def BinaryExists():
829 """Returns true if the command exists."""
830 try:
831 result, version = scm.SVN.AssertVersion('1.4')
832 if not result:
833 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
834 return result
835 except OSError:
836 return False
837
floitsch@google.comeaab7842011-04-28 09:07:58 +0000838 def GetRevisionDate(self, revision):
839 """Returns the given revision's date in ISO-8601 format (which contains the
840 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000841 date = scm.SVN.Capture(
842 ['propget', '--revprop', 'svn:date', '-r', revision],
843 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000844 return date.strip()
845
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000846 def cleanup(self, options, args, file_list):
847 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000848 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000849
850 def diff(self, options, args, file_list):
851 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000852 if not os.path.isdir(self.checkout_path):
853 raise gclient_utils.Error('Directory %s is not present.' %
854 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000855 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000856
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000857 def pack(self, options, args, file_list):
858 """Generates a patch file which can be applied to the root of the
859 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000860 if not os.path.isdir(self.checkout_path):
861 raise gclient_utils.Error('Directory %s is not present.' %
862 self.checkout_path)
863 gclient_utils.CheckCallAndFilter(
864 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
865 cwd=self.checkout_path,
866 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000867 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000868
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000869 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000870 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000871
872 All updated files will be appended to file_list.
873
874 Raises:
875 Error: if can't get URL for relative path.
876 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000877 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000878 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000879 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000880 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000881 return
882
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000883 hg_path = os.path.join(self.checkout_path, '.hg')
884 if os.path.exists(hg_path):
885 print('________ found .hg directory; skipping %s' % self.relpath)
886 return
887
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000888 if args:
889 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
890
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000891 # revision is the revision to match. It is None if no revision is specified,
892 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000893 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000894 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000895 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000896 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000897 if options.revision:
898 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000899 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000900 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000901 if revision != 'unmanaged':
902 forced_revision = True
903 # Reconstruct the url.
904 url = '%s@%s' % (url, revision)
905 rev_str = ' at %s' % revision
906 else:
907 managed = False
908 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000909 else:
910 forced_revision = False
911 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000912
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000913 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000914 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000915 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000916 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000917 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000918 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000919 return
920
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000921 if not managed:
922 print ('________ unmanaged solution; skipping %s' % self.relpath)
923 return
924
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000925 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000926 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000927 from_info = scm.SVN.CaptureLocalInfo(
928 [], os.path.join(self.checkout_path, '.'))
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000929 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000930 raise gclient_utils.Error(
931 ('Can\'t update/checkout %s if an unversioned directory is present. '
932 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000933
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +0000934 if 'URL' not in from_info:
935 raise gclient_utils.Error(
936 ('gclient is confused. Couldn\'t get the url for %s.\n'
937 'Try using @unmanaged.\n%s') % (
938 self.checkout_path, from_info))
939
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000940 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000941 dir_info = scm.SVN.CaptureStatus(
942 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000943 if any(d[0][2] == 'L' for d in dir_info):
944 try:
945 self._Run(['cleanup', self.checkout_path], options)
946 except subprocess2.CalledProcessError, e:
947 # Get the status again, svn cleanup may have cleaned up at least
948 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000949 dir_info = scm.SVN.CaptureStatus(
950 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000951
952 # Try to fix the failures by removing troublesome files.
953 for d in dir_info:
954 if d[0][2] == 'L':
955 if d[0][0] == '!' and options.force:
956 print 'Removing troublesome path %s' % d[1]
957 gclient_utils.rmtree(d[1])
958 else:
959 print 'Not removing troublesome path %s automatically.' % d[1]
960 if d[0][0] == '!':
961 print 'You can pass --force to enable automatic removal.'
962 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000963
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000964 # Retrieve the current HEAD version because svn is slow at null updates.
965 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000966 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000967 revision = str(from_info_live['Revision'])
968 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000969
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000970 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000971 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000972 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000973 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000974 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000975 # The url is invalid or the server is not accessible, it's safer to bail
976 # out right now.
977 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000978 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
979 and (from_info['UUID'] == to_info['UUID']))
980 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000981 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000982 # We have different roots, so check if we can switch --relocate.
983 # Subversion only permits this if the repository UUIDs match.
984 # Perform the switch --relocate, then rewrite the from_url
985 # to reflect where we "are now." (This is the same way that
986 # Subversion itself handles the metadata when switch --relocate
987 # is used.) This makes the checks below for whether we
988 # can update to a revision or have to switch to a different
989 # branch work as expected.
990 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000991 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000992 from_info['Repository Root'],
993 to_info['Repository Root'],
994 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000995 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000996 from_info['URL'] = from_info['URL'].replace(
997 from_info['Repository Root'],
998 to_info['Repository Root'])
999 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001000 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001001 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001002 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001003 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001004 raise gclient_utils.Error(
1005 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1006 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001007 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001008 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001009 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001010 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001011 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001012 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001013 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001014 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001015 return
1016
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001017 # If the provided url has a revision number that matches the revision
1018 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001019 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001020 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001021 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001022 else:
1023 command = ['update', self.checkout_path]
1024 command = self._AddAdditionalUpdateFlags(command, options, revision)
1025 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001026
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001027 # If --reset and --delete_unversioned_trees are specified, remove any
1028 # untracked files and directories.
1029 if options.reset and options.delete_unversioned_trees:
1030 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1031 full_path = os.path.join(self.checkout_path, status[1])
1032 if (status[0][0] == '?'
1033 and os.path.isdir(full_path)
1034 and not os.path.islink(full_path)):
1035 print('\n_____ removing unversioned directory %s' % status[1])
1036 gclient_utils.RemoveDirectory(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001037
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001038 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001039 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001040 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001041 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001042 # Create an empty checkout and then update the one file we want. Future
1043 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001044 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001045 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001046 if os.path.exists(os.path.join(self.checkout_path, filename)):
1047 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001048 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001049 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001050 # After the initial checkout, we can use update as if it were any other
1051 # dep.
1052 self.update(options, args, file_list)
1053 else:
1054 # If the installed version of SVN doesn't support --depth, fallback to
1055 # just exporting the file. This has the downside that revision
1056 # information is not stored next to the file, so we will have to
1057 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001058 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001059 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001060 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001061 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001062 command = self._AddAdditionalUpdateFlags(command, options,
1063 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001064 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001065
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001066 def revert(self, options, args, file_list):
1067 """Reverts local modifications. Subversion specific.
1068
1069 All reverted files will be appended to file_list, even if Subversion
1070 doesn't know about them.
1071 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001072 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001073 if os.path.exists(self.checkout_path):
1074 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001075 # svn revert won't work if the directory doesn't exist. It needs to
1076 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001077 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001078 # Don't reuse the args.
1079 return self.update(options, [], file_list)
1080
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001081 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1082 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1083 print('________ found .git directory; skipping %s' % self.relpath)
1084 return
1085 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1086 print('________ found .hg directory; skipping %s' % self.relpath)
1087 return
1088 if not options.force:
1089 raise gclient_utils.Error('Invalid checkout path, aborting')
1090 print(
1091 '\n_____ %s is not a valid svn checkout, synching instead' %
1092 self.relpath)
1093 gclient_utils.rmtree(self.checkout_path)
1094 # Don't reuse the args.
1095 return self.update(options, [], file_list)
1096
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001097 def printcb(file_status):
1098 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001099 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001100 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001101 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001102 print(os.path.join(self.checkout_path, file_status[1]))
1103 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001104
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001105 # Revert() may delete the directory altogether.
1106 if not os.path.isdir(self.checkout_path):
1107 # Don't reuse the args.
1108 return self.update(options, [], file_list)
1109
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001110 try:
1111 # svn revert is so broken we don't even use it. Using
1112 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001113 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001114 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1115 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001116 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001117 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001118 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001119
msb@chromium.org0f282062009-11-06 20:14:02 +00001120 def revinfo(self, options, args, file_list):
1121 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001122 try:
1123 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001124 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001125 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001126
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001127 def runhooks(self, options, args, file_list):
1128 self.status(options, args, file_list)
1129
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001130 def status(self, options, args, file_list):
1131 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001132 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001133 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001134 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001135 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1136 'The directory does not exist.') %
1137 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001138 # There's no file list to retrieve.
1139 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001140 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001141
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001142 def GetUsableRev(self, rev, options):
1143 """Verifies the validity of the revision for this repository."""
1144 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1145 raise gclient_utils.Error(
1146 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1147 'correct.') % rev)
1148 return rev
1149
msb@chromium.orge6f78352010-01-13 17:05:33 +00001150 def FullUrlForRelativeUrl(self, url):
1151 # Find the forth '/' and strip from there. A bit hackish.
1152 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001153
maruel@chromium.org669600d2010-09-01 19:06:31 +00001154 def _Run(self, args, options, **kwargs):
1155 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001156 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001157 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001158 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001159
1160 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1161 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001162 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001163 scm.SVN.RunAndGetFileList(
1164 options.verbose,
1165 args + ['--ignore-externals'],
1166 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001167 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001168
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001169 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001170 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001171 """Add additional flags to command depending on what options are set.
1172 command should be a list of strings that represents an svn command.
1173
1174 This method returns a new list to be used as a command."""
1175 new_command = command[:]
1176 if revision:
1177 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001178 # We don't want interaction when jobs are used.
1179 if options.jobs > 1:
1180 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001181 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001182 # --accept was added to 'svn update' in svn 1.6.
1183 if not scm.SVN.AssertVersion('1.5')[0]:
1184 return new_command
1185
1186 # It's annoying to have it block in the middle of a sync, just sensible
1187 # defaults.
1188 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001189 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001190 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1191 new_command.extend(('--accept', 'theirs-conflict'))
1192 elif options.manually_grab_svn_rev:
1193 new_command.append('--force')
1194 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1195 new_command.extend(('--accept', 'postpone'))
1196 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1197 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001198 return new_command