blob: 82947e451426eb22c845dc6455c424c43336b67f [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',
201 'submodule.$name.ignore', 'dirty']
202 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:
282 print ('________ unmanaged solution; skipping %s' % self.relpath)
283 return
284
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000285 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
286 raise gclient_utils.Error('\n____ %s%s\n'
287 '\tPath is not a git repo. No .git dir.\n'
288 '\tTo resolve:\n'
289 '\t\trm -rf %s\n'
290 '\tAnd run gclient sync again\n'
291 % (self.relpath, rev_str, self.relpath))
292
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000293 # See if the url has changed (the unittests use git://foo for the url, let
294 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000295 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000296 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
297 # unit test pass. (and update the comment above)
298 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000299 print('_____ switching %s to a new upstream' % self.relpath)
300 # Make sure it's clean
301 self._CheckClean(rev_str)
302 # Switch over to the new upstream
303 self._Run(['remote', 'set-url', 'origin', url], options)
304 quiet = []
305 if not options.verbose:
306 quiet = ['--quiet']
307 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
308 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000309 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000310 files = self._Capture(['ls-files']).splitlines()
311 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
312 return
313
msb@chromium.org5bde4852009-12-14 16:47:12 +0000314 cur_branch = self._GetCurrentBranch()
315
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000316 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000317 # 0) HEAD is detached. Probably from our initial clone.
318 # - make sure HEAD is contained by a named ref, then update.
319 # Cases 1-4. HEAD is a branch.
320 # 1) current branch is not tracking a remote branch (could be git-svn)
321 # - try to rebase onto the new hash or branch
322 # 2) current branch is tracking a remote branch with local committed
323 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000324 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000325 # 3) current branch is tracking a remote branch w/or w/out changes,
326 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000327 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000328 # 4) current branch is tracking a remote branch, switches to a different
329 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000330 # - exit
331
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000332 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
333 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000334 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
335 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000336 if cur_branch is None:
337 upstream_branch = None
338 current_type = "detached"
339 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000340 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000341 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
342 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
343 current_type = "hash"
344 logging.debug("Current branch is not tracking an upstream (remote)"
345 " branch.")
346 elif upstream_branch.startswith('refs/remotes'):
347 current_type = "branch"
348 else:
349 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000350
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000351 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000352 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000353 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000354 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000355 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000356 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000357 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000358 break
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000359 except subprocess2.CalledProcessError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000360 # Hackish but at that point, git is known to work so just checking for
361 # 502 in stderr should be fine.
362 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000363 print(str(e))
364 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000365 time.sleep(backoff_time)
366 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000367 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000368 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000369
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000370 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000371 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000372
373 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000374 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000375 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000376
msb@chromium.org786fb682010-06-02 15:16:23 +0000377 if current_type == 'detached':
378 # case 0
379 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000380 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000381 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000382 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000383 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000384 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000385 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000386 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000387 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000388 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000389 newbase=revision, printed_path=printed_path)
390 printed_path = True
391 else:
392 # Can't find a merge-base since we don't know our upstream. That makes
393 # this command VERY likely to produce a rebase failure. For now we
394 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000395 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000396 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000397 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000398 self._AttemptRebase(upstream_branch, files, options,
399 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000400 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000401 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000402 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000403 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000404 newbase=revision, printed_path=printed_path)
405 printed_path = True
406 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
407 # case 4
408 new_base = revision.replace('heads', 'remotes/origin')
409 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000410 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000411 switch_error = ("Switching upstream branch from %s to %s\n"
412 % (upstream_branch, new_base) +
413 "Please merge or rebase manually:\n" +
414 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
415 "OR git checkout -b <some new branch> %s" % new_base)
416 raise gclient_utils.Error(switch_error)
417 else:
418 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000419 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000420 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000421 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000422 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000423 merge_args = ['merge']
424 if not options.merge:
425 merge_args.append('--ff-only')
426 merge_args.append(upstream_branch)
427 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000428 except subprocess2.CalledProcessError, e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000429 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
430 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000431 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000432 printed_path = True
433 while True:
434 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000435 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000436 action = ask_for_data(
437 'Cannot fast-forward merge, attempt to rebase? '
438 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000439 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000440 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000441 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000442 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000443 printed_path=printed_path)
444 printed_path = True
445 break
446 elif re.match(r'quit|q', action, re.I):
447 raise gclient_utils.Error("Can't fast-forward, please merge or "
448 "rebase manually.\n"
449 "cd %s && git " % self.checkout_path
450 + "rebase %s" % upstream_branch)
451 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000452 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000453 return
454 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000455 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000456 elif re.match("error: Your local changes to '.*' would be "
457 "overwritten by merge. Aborting.\nPlease, commit your "
458 "changes or stash them before you can merge.\n",
459 e.stderr):
460 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000461 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000462 printed_path = True
463 raise gclient_utils.Error(e.stderr)
464 else:
465 # Some other problem happened with the merge
466 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000467 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000468 raise
469 else:
470 # Fast-forward merge was successful
471 if not re.match('Already up-to-date.', merge_output) or verbose:
472 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000473 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000474 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000475 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000476 if not verbose:
477 # Make the output a little prettier. It's nice to have some
478 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000479 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000480
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000481 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000482 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000483
484 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000485 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000486 raise gclient_utils.Error('\n____ %s%s\n'
487 '\nConflict while rebasing this branch.\n'
488 'Fix the conflict and run gclient again.\n'
489 'See man git-rebase for details.\n'
490 % (self.relpath, rev_str))
491
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000492 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000493 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000494
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000495 # If --reset and --delete_unversioned_trees are specified, remove any
496 # untracked directories.
497 if options.reset and options.delete_unversioned_trees:
498 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
499 # merge-base by default), so doesn't include untracked files. So we use
500 # 'git ls-files --directory --others --exclude-standard' here directly.
501 paths = scm.GIT.Capture(
502 ['ls-files', '--directory', '--others', '--exclude-standard'],
503 self.checkout_path)
504 for path in (p for p in paths.splitlines() if p.endswith('/')):
505 full_path = os.path.join(self.checkout_path, path)
506 if not os.path.islink(full_path):
507 print('\n_____ removing unversioned directory %s' % path)
508 gclient_utils.RemoveDirectory(full_path)
509
510
msb@chromium.orge28e4982009-09-25 20:51:45 +0000511 def revert(self, options, args, file_list):
512 """Reverts local modifications.
513
514 All reverted files will be appended to file_list.
515 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000516 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000517 # revert won't work if the directory doesn't exist. It needs to
518 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000519 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000520 # Don't reuse the args.
521 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000522
523 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000524 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000525 if not deps_revision:
526 deps_revision = default_rev
527 if deps_revision.startswith('refs/heads/'):
528 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
529
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000530 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000531 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000532 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
533
msb@chromium.org0f282062009-11-06 20:14:02 +0000534 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000535 """Returns revision"""
536 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000537
msb@chromium.orge28e4982009-09-25 20:51:45 +0000538 def runhooks(self, options, args, file_list):
539 self.status(options, args, file_list)
540
541 def status(self, options, args, file_list):
542 """Display status information."""
543 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000544 print(('\n________ couldn\'t run status in %s:\n'
545 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000546 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000547 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000548 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000549 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000550 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
551
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000552 def GetUsableRev(self, rev, options):
553 """Finds a useful revision for this repository.
554
555 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
556 will be called on the source."""
557 sha1 = None
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000558 # Handles an SVN rev. As an optimization, only verify an SVN revision as
559 # [0-9]{1,6} for now to avoid making a network request.
560 if rev.isdigit() and len(rev) < 7:
561 # If the content of the safesync_url appears to be an SVN rev and the
562 # URL of the source appears to be git, we can only attempt to find out
563 # if a revision is useful after we've cloned the original URL, so just
564 # ignore for now.
565 if (os.path.isdir(self.checkout_path) and
566 scm.GIT.IsGitSvn(cwd=self.checkout_path)):
567 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
568 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000569 try:
570 logging.debug('Looking for git-svn configuration optimizations.')
571 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
572 cwd=self.checkout_path):
573 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
574 except subprocess2.CalledProcessError:
575 logging.debug('git config --get svn-remote.svn.fetch failed, '
576 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000577 if options.verbose:
578 print('Running git svn fetch. This might take a while.\n')
579 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
580 sha1 = scm.GIT.GetSha1ForSvnRev(cwd=self.checkout_path, rev=rev)
581 if not sha1:
582 raise gclient_utils.Error(
583 ( 'It appears that either your git-svn remote is incorrectly\n'
584 'configured or the revision in your safesync_url is\n'
585 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
586 'corresponding git hash for SVN rev %s.' ) % rev)
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000587 elif scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
588 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000589
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000590 if not sha1:
591 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000592 ( 'We could not find a valid hash for safesync_url response "%s".\n'
593 'Safesync URLs with a git checkout currently require a git-svn\n'
594 'remote or a safesync_url that provides git sha1s. Please add a\n'
595 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000596 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000597 '#Initial_checkout' ) % rev)
598
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000599 return sha1
600
msb@chromium.orge6f78352010-01-13 17:05:33 +0000601 def FullUrlForRelativeUrl(self, url):
602 # Strip from last '/'
603 # Equivalent to unix basename
604 base_url = self.url
605 return base_url[:base_url.rfind('/')] + url
606
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000607 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000608 """Clone a git repository from the given URL.
609
msb@chromium.org786fb682010-06-02 15:16:23 +0000610 Once we've cloned the repo, we checkout a working branch if the specified
611 revision is a branch head. If it is a tag or a specific commit, then we
612 leave HEAD detached as it makes future updates simpler -- in this case the
613 user should first create a new branch or switch to an existing branch before
614 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000615 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000616 # git clone doesn't seem to insert a newline properly before printing
617 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000618 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000619
szager@google.com85d3e3a2011-10-07 17:12:00 +0000620 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000621 if revision.startswith('refs/heads/'):
622 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
623 detach_head = False
624 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000625 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000626 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000627 clone_cmd.append('--verbose')
628 clone_cmd.extend([url, self.checkout_path])
629
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000630 # If the parent directory does not exist, Git clone on Windows will not
631 # create it, so we need to do it manually.
632 parent_dir = os.path.dirname(self.checkout_path)
633 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000634 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000635
szager@google.com85d3e3a2011-10-07 17:12:00 +0000636 percent_re = re.compile('.* ([0-9]{1,2})% .*')
637 def _GitFilter(line):
638 # git uses an escape sequence to clear the line; elide it.
639 esc = line.find(unichr(033))
640 if esc > -1:
641 line = line[:esc]
642 match = percent_re.match(line)
643 if not match or not int(match.group(1)) % 10:
644 print '%s' % line
645
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000646 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000647 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000648 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
649 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000650 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000651 except subprocess2.CalledProcessError, e:
652 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000653 # We should check for "transfer closed with NNN bytes remaining to
654 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000655 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000656 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000657 print(str(e))
658 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000659 continue
660 raise e
661
msb@chromium.org786fb682010-06-02 15:16:23 +0000662 if detach_head:
663 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000664 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000665 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000666 ('Checked out %s to a detached HEAD. Before making any commits\n'
667 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
668 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
669 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000670
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000671 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000672 branch=None, printed_path=False):
673 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000674 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000675 revision = upstream
676 if newbase:
677 revision = newbase
678 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000679 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000680 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000681 printed_path = True
682 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000683 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000684
685 # Build the rebase command here using the args
686 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
687 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000688 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000689 rebase_cmd.append('--verbose')
690 if newbase:
691 rebase_cmd.extend(['--onto', newbase])
692 rebase_cmd.append(upstream)
693 if branch:
694 rebase_cmd.append(branch)
695
696 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000697 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000698 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000699 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
700 re.match(r'cannot rebase: your index contains uncommitted changes',
701 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000702 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000703 rebase_action = ask_for_data(
704 'Cannot rebase because of unstaged changes.\n'
705 '\'git reset --hard HEAD\' ?\n'
706 'WARNING: destroys any uncommitted work in your current branch!'
707 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000708 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000709 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000710 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000711 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000712 break
713 elif re.match(r'quit|q', rebase_action, re.I):
714 raise gclient_utils.Error("Please merge or rebase manually\n"
715 "cd %s && git " % self.checkout_path
716 + "%s" % ' '.join(rebase_cmd))
717 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000718 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000719 continue
720 else:
721 gclient_utils.Error("Input not recognized")
722 continue
723 elif re.search(r'^CONFLICT', e.stdout, re.M):
724 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
725 "Fix the conflict and run gclient again.\n"
726 "See 'man git-rebase' for details.\n")
727 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000728 print(e.stdout.strip())
729 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000730 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
731 "manually.\ncd %s && git " %
732 self.checkout_path
733 + "%s" % ' '.join(rebase_cmd))
734
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000735 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000736 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000737 # Make the output a little prettier. It's nice to have some
738 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000739 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000740
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000741 @staticmethod
742 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000743 (ok, current_version) = scm.GIT.AssertVersion(min_version)
744 if not ok:
745 raise gclient_utils.Error('git version %s < minimum required %s' %
746 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000747
msb@chromium.org786fb682010-06-02 15:16:23 +0000748 def _IsRebasing(self):
749 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
750 # have a plumbing command to determine whether a rebase is in progress, so
751 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
752 g = os.path.join(self.checkout_path, '.git')
753 return (
754 os.path.isdir(os.path.join(g, "rebase-merge")) or
755 os.path.isdir(os.path.join(g, "rebase-apply")))
756
757 def _CheckClean(self, rev_str):
758 # Make sure the tree is clean; see git-rebase.sh for reference
759 try:
760 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000761 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000762 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000763 raise gclient_utils.Error('\n____ %s%s\n'
764 '\tYou have unstaged changes.\n'
765 '\tPlease commit, stash, or reset.\n'
766 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000767 try:
768 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000769 '--ignore-submodules', 'HEAD', '--'],
770 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000771 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000772 raise gclient_utils.Error('\n____ %s%s\n'
773 '\tYour index contains uncommitted changes\n'
774 '\tPlease commit, stash, or reset.\n'
775 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000776
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000777 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000778 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
779 # reference by a commit). If not, error out -- most likely a rebase is
780 # in progress, try to detect so we can give a better error.
781 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000782 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
783 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000784 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000785 # Commit is not contained by any rev. See if the user is rebasing:
786 if self._IsRebasing():
787 # Punt to the user
788 raise gclient_utils.Error('\n____ %s%s\n'
789 '\tAlready in a conflict, i.e. (no branch).\n'
790 '\tFix the conflict and run gclient again.\n'
791 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
792 '\tSee man git-rebase for details.\n'
793 % (self.relpath, rev_str))
794 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000795 name = ('saved-by-gclient-' +
796 self._Capture(['rev-parse', '--short', 'HEAD']))
797 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000798 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000799 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000800
msb@chromium.org5bde4852009-12-14 16:47:12 +0000801 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000802 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000803 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000804 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000805 return None
806 return branch
807
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000808 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000809 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000810 ['git'] + args,
811 stderr=subprocess2.PIPE,
812 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000813
maruel@chromium.org37e89872010-09-07 16:11:33 +0000814 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000815 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000816 kwargs.setdefault('print_stdout', True)
817 stdout = kwargs.get('stdout', sys.stdout)
818 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
819 ' '.join(args), kwargs['cwd']))
820 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000821
822
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000823class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000824 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000825
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000826 @staticmethod
827 def BinaryExists():
828 """Returns true if the command exists."""
829 try:
830 result, version = scm.SVN.AssertVersion('1.4')
831 if not result:
832 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
833 return result
834 except OSError:
835 return False
836
floitsch@google.comeaab7842011-04-28 09:07:58 +0000837 def GetRevisionDate(self, revision):
838 """Returns the given revision's date in ISO-8601 format (which contains the
839 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000840 date = scm.SVN.Capture(
841 ['propget', '--revprop', 'svn:date', '-r', revision],
842 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000843 return date.strip()
844
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000845 def cleanup(self, options, args, file_list):
846 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000847 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000848
849 def diff(self, options, args, file_list):
850 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000851 if not os.path.isdir(self.checkout_path):
852 raise gclient_utils.Error('Directory %s is not present.' %
853 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000854 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000855
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000856 def pack(self, options, args, file_list):
857 """Generates a patch file which can be applied to the root of the
858 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000859 if not os.path.isdir(self.checkout_path):
860 raise gclient_utils.Error('Directory %s is not present.' %
861 self.checkout_path)
862 gclient_utils.CheckCallAndFilter(
863 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
864 cwd=self.checkout_path,
865 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000866 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000867
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000868 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000869 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000870
871 All updated files will be appended to file_list.
872
873 Raises:
874 Error: if can't get URL for relative path.
875 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000876 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000877 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000878 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000879 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000880 return
881
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000882 hg_path = os.path.join(self.checkout_path, '.hg')
883 if os.path.exists(hg_path):
884 print('________ found .hg directory; skipping %s' % self.relpath)
885 return
886
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000887 if args:
888 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
889
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000890 # revision is the revision to match. It is None if no revision is specified,
891 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000892 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000893 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000894 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000895 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000896 if options.revision:
897 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000898 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000899 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000900 if revision != 'unmanaged':
901 forced_revision = True
902 # Reconstruct the url.
903 url = '%s@%s' % (url, revision)
904 rev_str = ' at %s' % revision
905 else:
906 managed = False
907 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000908 else:
909 forced_revision = False
910 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000911
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000912 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000913 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000914 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000915 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000916 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000917 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000918 return
919
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000920 if not managed:
921 print ('________ unmanaged solution; skipping %s' % self.relpath)
922 return
923
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000924 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000925 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000926 from_info = scm.SVN.CaptureLocalInfo(
927 [], os.path.join(self.checkout_path, '.'))
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000928 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000929 raise gclient_utils.Error(
930 ('Can\'t update/checkout %s if an unversioned directory is present. '
931 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000932
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +0000933 if 'URL' not in from_info:
934 raise gclient_utils.Error(
935 ('gclient is confused. Couldn\'t get the url for %s.\n'
936 'Try using @unmanaged.\n%s') % (
937 self.checkout_path, from_info))
938
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000939 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000940 dir_info = scm.SVN.CaptureStatus(
941 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000942 if any(d[0][2] == 'L' for d in dir_info):
943 try:
944 self._Run(['cleanup', self.checkout_path], options)
945 except subprocess2.CalledProcessError, e:
946 # Get the status again, svn cleanup may have cleaned up at least
947 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000948 dir_info = scm.SVN.CaptureStatus(
949 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000950
951 # Try to fix the failures by removing troublesome files.
952 for d in dir_info:
953 if d[0][2] == 'L':
954 if d[0][0] == '!' and options.force:
955 print 'Removing troublesome path %s' % d[1]
956 gclient_utils.rmtree(d[1])
957 else:
958 print 'Not removing troublesome path %s automatically.' % d[1]
959 if d[0][0] == '!':
960 print 'You can pass --force to enable automatic removal.'
961 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000962
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000963 # Retrieve the current HEAD version because svn is slow at null updates.
964 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000965 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000966 revision = str(from_info_live['Revision'])
967 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000968
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000969 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000970 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000971 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000972 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000973 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000974 # The url is invalid or the server is not accessible, it's safer to bail
975 # out right now.
976 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000977 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
978 and (from_info['UUID'] == to_info['UUID']))
979 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000980 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000981 # We have different roots, so check if we can switch --relocate.
982 # Subversion only permits this if the repository UUIDs match.
983 # Perform the switch --relocate, then rewrite the from_url
984 # to reflect where we "are now." (This is the same way that
985 # Subversion itself handles the metadata when switch --relocate
986 # is used.) This makes the checks below for whether we
987 # can update to a revision or have to switch to a different
988 # branch work as expected.
989 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000990 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000991 from_info['Repository Root'],
992 to_info['Repository Root'],
993 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000994 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000995 from_info['URL'] = from_info['URL'].replace(
996 from_info['Repository Root'],
997 to_info['Repository Root'])
998 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000999 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001000 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001001 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001002 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001003 raise gclient_utils.Error(
1004 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1005 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001006 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001007 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001008 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001009 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001010 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001011 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001012 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001013 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001014 return
1015
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001016 # If the provided url has a revision number that matches the revision
1017 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001018 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001019 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001020 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001021 else:
1022 command = ['update', self.checkout_path]
1023 command = self._AddAdditionalUpdateFlags(command, options, revision)
1024 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001025
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001026 # If --reset and --delete_unversioned_trees are specified, remove any
1027 # untracked files and directories.
1028 if options.reset and options.delete_unversioned_trees:
1029 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1030 full_path = os.path.join(self.checkout_path, status[1])
1031 if (status[0][0] == '?'
1032 and os.path.isdir(full_path)
1033 and not os.path.islink(full_path)):
1034 print('\n_____ removing unversioned directory %s' % status[1])
1035 gclient_utils.RemoveDirectory(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001036
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001037 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001038 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001039 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001040 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001041 # Create an empty checkout and then update the one file we want. Future
1042 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001043 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001044 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001045 if os.path.exists(os.path.join(self.checkout_path, filename)):
1046 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001047 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001048 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001049 # After the initial checkout, we can use update as if it were any other
1050 # dep.
1051 self.update(options, args, file_list)
1052 else:
1053 # If the installed version of SVN doesn't support --depth, fallback to
1054 # just exporting the file. This has the downside that revision
1055 # information is not stored next to the file, so we will have to
1056 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001057 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001058 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001059 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001060 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001061 command = self._AddAdditionalUpdateFlags(command, options,
1062 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001063 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001064
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001065 def revert(self, options, args, file_list):
1066 """Reverts local modifications. Subversion specific.
1067
1068 All reverted files will be appended to file_list, even if Subversion
1069 doesn't know about them.
1070 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001071 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001072 if os.path.exists(self.checkout_path):
1073 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001074 # svn revert won't work if the directory doesn't exist. It needs to
1075 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001076 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001077 # Don't reuse the args.
1078 return self.update(options, [], file_list)
1079
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001080 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1081 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1082 print('________ found .git directory; skipping %s' % self.relpath)
1083 return
1084 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1085 print('________ found .hg directory; skipping %s' % self.relpath)
1086 return
1087 if not options.force:
1088 raise gclient_utils.Error('Invalid checkout path, aborting')
1089 print(
1090 '\n_____ %s is not a valid svn checkout, synching instead' %
1091 self.relpath)
1092 gclient_utils.rmtree(self.checkout_path)
1093 # Don't reuse the args.
1094 return self.update(options, [], file_list)
1095
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001096 def printcb(file_status):
1097 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001098 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001099 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001100 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001101 print(os.path.join(self.checkout_path, file_status[1]))
1102 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001103
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001104 # Revert() may delete the directory altogether.
1105 if not os.path.isdir(self.checkout_path):
1106 # Don't reuse the args.
1107 return self.update(options, [], file_list)
1108
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001109 try:
1110 # svn revert is so broken we don't even use it. Using
1111 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001112 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001113 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1114 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001115 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001116 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001117 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001118
msb@chromium.org0f282062009-11-06 20:14:02 +00001119 def revinfo(self, options, args, file_list):
1120 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001121 try:
1122 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001123 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001124 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001125
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001126 def runhooks(self, options, args, file_list):
1127 self.status(options, args, file_list)
1128
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001129 def status(self, options, args, file_list):
1130 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001131 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001132 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001133 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001134 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1135 'The directory does not exist.') %
1136 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001137 # There's no file list to retrieve.
1138 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001139 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001140
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001141 def GetUsableRev(self, rev, options):
1142 """Verifies the validity of the revision for this repository."""
1143 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1144 raise gclient_utils.Error(
1145 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1146 'correct.') % rev)
1147 return rev
1148
msb@chromium.orge6f78352010-01-13 17:05:33 +00001149 def FullUrlForRelativeUrl(self, url):
1150 # Find the forth '/' and strip from there. A bit hackish.
1151 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001152
maruel@chromium.org669600d2010-09-01 19:06:31 +00001153 def _Run(self, args, options, **kwargs):
1154 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001155 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001156 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001157 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001158
1159 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1160 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001161 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001162 scm.SVN.RunAndGetFileList(
1163 options.verbose,
1164 args + ['--ignore-externals'],
1165 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001166 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001167
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001168 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001169 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001170 """Add additional flags to command depending on what options are set.
1171 command should be a list of strings that represents an svn command.
1172
1173 This method returns a new list to be used as a command."""
1174 new_command = command[:]
1175 if revision:
1176 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001177 # We don't want interaction when jobs are used.
1178 if options.jobs > 1:
1179 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001180 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001181 # --accept was added to 'svn update' in svn 1.6.
1182 if not scm.SVN.AssertVersion('1.5')[0]:
1183 return new_command
1184
1185 # It's annoying to have it block in the middle of a sync, just sensible
1186 # defaults.
1187 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001188 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001189 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1190 new_command.extend(('--accept', 'theirs-conflict'))
1191 elif options.manually_grab_svn_rev:
1192 new_command.append('--force')
1193 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1194 new_command.extend(('--accept', 'postpone'))
1195 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1196 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001197 return new_command