blob: e8c1711f89ece3feb5d59addf473ff1d21de7e22 [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
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000019class DiffFilterer(object):
20 """Simple class which tracks which file is being diffed and
21 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."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000023 index_string = "Index: "
24 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("\\", "/")
31 self._current_file = ""
32 self._replacement_file = ""
33
maruel@chromium.org6e29d572010-06-04 17:32:20 +000034 def SetCurrentFile(self, current_file):
35 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000036 # Note that we always use '/' as the path separator to be
37 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000038 self._replacement_file = posixpath.join(self._relpath, 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
maruel@chromium.org90541732011-04-01 17:54:18 +000054def ask_for_data(prompt):
55 try:
56 return raw_input(prompt)
57 except KeyboardInterrupt:
58 # Hide the exception.
59 sys.exit(1)
60
61
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000062### SCM abstraction layer
63
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000064# Factory Method for SCM wrapper creation
65
maruel@chromium.org9eda4112010-06-11 18:56:10 +000066def GetScmName(url):
67 if url:
68 url, _ = gclient_utils.SplitUrlRevision(url)
69 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000070 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000071 url.endswith('.git')):
72 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000073 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000074 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000075 return 'svn'
76 return None
77
78
79def CreateSCM(url, root_dir=None, relpath=None):
80 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000081 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000082 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000083 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000084
maruel@chromium.org9eda4112010-06-11 18:56:10 +000085 scm_name = GetScmName(url)
86 if not scm_name in SCM_MAP:
87 raise gclient_utils.Error('No SCM found for url %s' % url)
88 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000089
90
91# SCMWrapper base class
92
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000093class SCMWrapper(object):
94 """Add necessary glue between all the supported SCM.
95
msb@chromium.orgd6504212010-01-13 17:34:31 +000096 This is the abstraction layer to bind to different SCM.
97 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000098 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000099 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000100 self._root_dir = root_dir
101 if self._root_dir:
102 self._root_dir = self._root_dir.replace('/', os.sep)
103 self.relpath = relpath
104 if self.relpath:
105 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000106 if self.relpath and self._root_dir:
107 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000108
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000109 def RunCommand(self, command, options, args, file_list=None):
110 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000111 if file_list is None:
112 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000113
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000114 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000115 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000116
117 if not command in commands:
118 raise gclient_utils.Error('Unknown command %s' % command)
119
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000120 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000121 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000122 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000123
124 return getattr(self, command)(options, args, file_list)
125
126
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000127class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000128 """Wrapper for Git"""
129
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000130 def __init__(self, url=None, root_dir=None, relpath=None):
131 """Removes 'git+' fake prefix from git URL."""
132 if url.startswith('git+http://') or url.startswith('git+https://'):
133 url = url[4:]
134 SCMWrapper.__init__(self, url, root_dir, relpath)
135
floitsch@google.comeaab7842011-04-28 09:07:58 +0000136 def GetRevisionDate(self, revision):
137 """Returns the given revision's date in ISO-8601 format (which contains the
138 time zone)."""
139 # TODO(floitsch): get the time-stamp of the given revision and not just the
140 # time-stamp of the currently checked out revision.
141 return self._Capture(['log', '-n', '1', '--format=%ai'])
142
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000143 @staticmethod
144 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000145 """'Cleanup' the repo.
146
147 There's no real git equivalent for the svn cleanup command, do a no-op.
148 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000149
150 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000151 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000152 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000153
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000154 def pack(self, options, args, file_list):
155 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000156 repository.
157
158 The patch file is generated from a diff of the merge base of HEAD and
159 its upstream branch.
160 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000161 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000162 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000163 ['git', 'diff', merge_base],
164 cwd=self.checkout_path,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000165 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000166
msb@chromium.orge28e4982009-09-25 20:51:45 +0000167 def update(self, options, args, file_list):
168 """Runs git to update or transparently checkout the working copy.
169
170 All updated files will be appended to file_list.
171
172 Raises:
173 Error: if can't get URL for relative path.
174 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000175 if args:
176 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
177
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000178 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000179
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000180 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000181 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000182 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000183 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000184 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000185 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000186 # Override the revision number.
187 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000188 if revision == 'unmanaged':
189 revision = None
190 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000191 if not revision:
192 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000193
floitsch@google.comeaab7842011-04-28 09:07:58 +0000194 if gclient_utils.IsDateRevision(revision):
195 # Date-revisions only work on git-repositories if the reflog hasn't
196 # expired yet. Use rev-list to get the corresponding revision.
197 # git rev-list -n 1 --before='time-stamp' branchname
198 if options.transitive:
199 print('Warning: --transitive only works for SVN repositories.')
200 revision = default_rev
201
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000202 rev_str = ' at %s' % revision
203 files = []
204
205 printed_path = False
206 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000207 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000208 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000209 verbose = ['--verbose']
210 printed_path = True
211
212 if revision.startswith('refs/heads/'):
213 rev_type = "branch"
214 elif revision.startswith('origin/'):
215 # For compatability with old naming, translate 'origin' to 'refs/heads'
216 revision = revision.replace('origin/', 'refs/heads/')
217 rev_type = "branch"
218 else:
219 # hash is also a tag, only make a distinction at checkout
220 rev_type = "hash"
221
szager@google.com873e6672012-03-13 18:53:36 +0000222 if not os.path.exists(self.checkout_path) or (
223 os.path.isdir(self.checkout_path) and
224 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000225 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000226 self._Clone(revision, url, options)
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000227 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000228 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000229 if not verbose:
230 # Make the output a little prettier. It's nice to have some whitespace
231 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000232 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000233 return
234
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000235 if not managed:
236 print ('________ unmanaged solution; skipping %s' % self.relpath)
237 return
238
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000239 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
240 raise gclient_utils.Error('\n____ %s%s\n'
241 '\tPath is not a git repo. No .git dir.\n'
242 '\tTo resolve:\n'
243 '\t\trm -rf %s\n'
244 '\tAnd run gclient sync again\n'
245 % (self.relpath, rev_str, self.relpath))
246
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000247 # See if the url has changed (the unittests use git://foo for the url, let
248 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000249 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000250 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
251 # unit test pass. (and update the comment above)
252 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000253 print('_____ switching %s to a new upstream' % self.relpath)
254 # Make sure it's clean
255 self._CheckClean(rev_str)
256 # Switch over to the new upstream
257 self._Run(['remote', 'set-url', 'origin', url], options)
258 quiet = []
259 if not options.verbose:
260 quiet = ['--quiet']
261 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
262 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
263 files = self._Capture(['ls-files']).splitlines()
264 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
265 return
266
msb@chromium.org5bde4852009-12-14 16:47:12 +0000267 cur_branch = self._GetCurrentBranch()
268
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000269 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000270 # 0) HEAD is detached. Probably from our initial clone.
271 # - make sure HEAD is contained by a named ref, then update.
272 # Cases 1-4. HEAD is a branch.
273 # 1) current branch is not tracking a remote branch (could be git-svn)
274 # - try to rebase onto the new hash or branch
275 # 2) current branch is tracking a remote branch with local committed
276 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000277 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000278 # 3) current branch is tracking a remote branch w/or w/out changes,
279 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000280 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000281 # 4) current branch is tracking a remote branch, switches to a different
282 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000283 # - exit
284
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000285 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
286 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000287 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
288 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000289 if cur_branch is None:
290 upstream_branch = None
291 current_type = "detached"
292 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000293 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000294 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
295 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
296 current_type = "hash"
297 logging.debug("Current branch is not tracking an upstream (remote)"
298 " branch.")
299 elif upstream_branch.startswith('refs/remotes'):
300 current_type = "branch"
301 else:
302 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000303
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000304 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000305 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000306 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000307 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000308 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000309 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000310 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000311 break
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000312 except subprocess2.CalledProcessError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000313 # Hackish but at that point, git is known to work so just checking for
314 # 502 in stderr should be fine.
315 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000316 print(str(e))
317 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000318 time.sleep(backoff_time)
319 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000320 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000321 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000322
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000323 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000324 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000325
326 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000327 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000328 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000329
msb@chromium.org786fb682010-06-02 15:16:23 +0000330 if current_type == 'detached':
331 # case 0
332 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000333 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000334 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000335 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000336 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000337 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000338 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000339 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000340 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000341 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000342 newbase=revision, printed_path=printed_path)
343 printed_path = True
344 else:
345 # Can't find a merge-base since we don't know our upstream. That makes
346 # this command VERY likely to produce a rebase failure. For now we
347 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000348 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000349 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000350 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000351 self._AttemptRebase(upstream_branch, files, options,
352 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000353 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000354 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000355 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000356 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000357 newbase=revision, printed_path=printed_path)
358 printed_path = True
359 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
360 # case 4
361 new_base = revision.replace('heads', 'remotes/origin')
362 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000363 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000364 switch_error = ("Switching upstream branch from %s to %s\n"
365 % (upstream_branch, new_base) +
366 "Please merge or rebase manually:\n" +
367 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
368 "OR git checkout -b <some new branch> %s" % new_base)
369 raise gclient_utils.Error(switch_error)
370 else:
371 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000372 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000373 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000374 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000375 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000376 merge_args = ['merge']
377 if not options.merge:
378 merge_args.append('--ff-only')
379 merge_args.append(upstream_branch)
380 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000381 except subprocess2.CalledProcessError, e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000382 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
383 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000384 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000385 printed_path = True
386 while True:
387 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000388 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000389 action = ask_for_data(
390 'Cannot fast-forward merge, attempt to rebase? '
391 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000392 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000393 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000394 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000395 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000396 printed_path=printed_path)
397 printed_path = True
398 break
399 elif re.match(r'quit|q', action, re.I):
400 raise gclient_utils.Error("Can't fast-forward, please merge or "
401 "rebase manually.\n"
402 "cd %s && git " % self.checkout_path
403 + "rebase %s" % upstream_branch)
404 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000405 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000406 return
407 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000408 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000409 elif re.match("error: Your local changes to '.*' would be "
410 "overwritten by merge. Aborting.\nPlease, commit your "
411 "changes or stash them before you can merge.\n",
412 e.stderr):
413 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000414 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000415 printed_path = True
416 raise gclient_utils.Error(e.stderr)
417 else:
418 # Some other problem happened with the merge
419 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000420 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000421 raise
422 else:
423 # Fast-forward merge was successful
424 if not re.match('Already up-to-date.', merge_output) or verbose:
425 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000426 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000427 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000428 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000429 if not verbose:
430 # Make the output a little prettier. It's nice to have some
431 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000432 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000433
434 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000435
436 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000437 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000438 raise gclient_utils.Error('\n____ %s%s\n'
439 '\nConflict while rebasing this branch.\n'
440 'Fix the conflict and run gclient again.\n'
441 'See man git-rebase for details.\n'
442 % (self.relpath, rev_str))
443
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000444 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000445 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000446
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000447 # If --reset and --delete_unversioned_trees are specified, remove any
448 # untracked directories.
449 if options.reset and options.delete_unversioned_trees:
450 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
451 # merge-base by default), so doesn't include untracked files. So we use
452 # 'git ls-files --directory --others --exclude-standard' here directly.
453 paths = scm.GIT.Capture(
454 ['ls-files', '--directory', '--others', '--exclude-standard'],
455 self.checkout_path)
456 for path in (p for p in paths.splitlines() if p.endswith('/')):
457 full_path = os.path.join(self.checkout_path, path)
458 if not os.path.islink(full_path):
459 print('\n_____ removing unversioned directory %s' % path)
460 gclient_utils.RemoveDirectory(full_path)
461
462
msb@chromium.orge28e4982009-09-25 20:51:45 +0000463 def revert(self, options, args, file_list):
464 """Reverts local modifications.
465
466 All reverted files will be appended to file_list.
467 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000468 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000469 # revert won't work if the directory doesn't exist. It needs to
470 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000471 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000472 # Don't reuse the args.
473 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000474
475 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000476 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000477 if not deps_revision:
478 deps_revision = default_rev
479 if deps_revision.startswith('refs/heads/'):
480 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
481
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000482 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000483 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000484 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
485
msb@chromium.org0f282062009-11-06 20:14:02 +0000486 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000487 """Returns revision"""
488 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000489
msb@chromium.orge28e4982009-09-25 20:51:45 +0000490 def runhooks(self, options, args, file_list):
491 self.status(options, args, file_list)
492
493 def status(self, options, args, file_list):
494 """Display status information."""
495 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000496 print(('\n________ couldn\'t run status in %s:\n'
497 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000498 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000499 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000500 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000501 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000502 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
503
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000504 def GetUsableRev(self, rev, options):
505 """Finds a useful revision for this repository.
506
507 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
508 will be called on the source."""
509 sha1 = None
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000510 # Handles an SVN rev. As an optimization, only verify an SVN revision as
511 # [0-9]{1,6} for now to avoid making a network request.
512 if rev.isdigit() and len(rev) < 7:
513 # If the content of the safesync_url appears to be an SVN rev and the
514 # URL of the source appears to be git, we can only attempt to find out
515 # if a revision is useful after we've cloned the original URL, so just
516 # ignore for now.
517 if (os.path.isdir(self.checkout_path) and
518 scm.GIT.IsGitSvn(cwd=self.checkout_path)):
519 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
520 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000521 try:
522 logging.debug('Looking for git-svn configuration optimizations.')
523 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
524 cwd=self.checkout_path):
525 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
526 except subprocess2.CalledProcessError:
527 logging.debug('git config --get svn-remote.svn.fetch failed, '
528 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000529 if options.verbose:
530 print('Running git svn fetch. This might take a while.\n')
531 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
532 sha1 = scm.GIT.GetSha1ForSvnRev(cwd=self.checkout_path, rev=rev)
533 if not sha1:
534 raise gclient_utils.Error(
535 ( 'It appears that either your git-svn remote is incorrectly\n'
536 'configured or the revision in your safesync_url is\n'
537 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
538 'corresponding git hash for SVN rev %s.' ) % rev)
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000539 elif scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
540 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000541
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000542 if not sha1:
543 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000544 ( 'We could not find a valid hash for safesync_url response "%s".\n'
545 'Safesync URLs with a git checkout currently require a git-svn\n'
546 'remote or a safesync_url that provides git sha1s. Please add a\n'
547 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000548 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000549 '#Initial_checkout' ) % rev)
550
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000551 return sha1
552
msb@chromium.orge6f78352010-01-13 17:05:33 +0000553 def FullUrlForRelativeUrl(self, url):
554 # Strip from last '/'
555 # Equivalent to unix basename
556 base_url = self.url
557 return base_url[:base_url.rfind('/')] + url
558
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000559 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000560 """Clone a git repository from the given URL.
561
msb@chromium.org786fb682010-06-02 15:16:23 +0000562 Once we've cloned the repo, we checkout a working branch if the specified
563 revision is a branch head. If it is a tag or a specific commit, then we
564 leave HEAD detached as it makes future updates simpler -- in this case the
565 user should first create a new branch or switch to an existing branch before
566 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000567 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000568 # git clone doesn't seem to insert a newline properly before printing
569 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000570 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000571
szager@google.com85d3e3a2011-10-07 17:12:00 +0000572 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000573 if revision.startswith('refs/heads/'):
574 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
575 detach_head = False
576 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000577 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000578 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000579 clone_cmd.append('--verbose')
580 clone_cmd.extend([url, self.checkout_path])
581
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000582 # If the parent directory does not exist, Git clone on Windows will not
583 # create it, so we need to do it manually.
584 parent_dir = os.path.dirname(self.checkout_path)
585 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000586 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000587
szager@google.com85d3e3a2011-10-07 17:12:00 +0000588 percent_re = re.compile('.* ([0-9]{1,2})% .*')
589 def _GitFilter(line):
590 # git uses an escape sequence to clear the line; elide it.
591 esc = line.find(unichr(033))
592 if esc > -1:
593 line = line[:esc]
594 match = percent_re.match(line)
595 if not match or not int(match.group(1)) % 10:
596 print '%s' % line
597
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000598 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000599 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000600 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
601 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000602 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000603 except subprocess2.CalledProcessError, e:
604 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000605 # We should check for "transfer closed with NNN bytes remaining to
606 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000607 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000608 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000609 print(str(e))
610 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000611 continue
612 raise e
613
msb@chromium.org786fb682010-06-02 15:16:23 +0000614 if detach_head:
615 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000616 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000617 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000618 ('Checked out %s to a detached HEAD. Before making any commits\n'
619 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
620 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
621 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000622
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000623 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000624 branch=None, printed_path=False):
625 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000626 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000627 revision = upstream
628 if newbase:
629 revision = newbase
630 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000631 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000632 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000633 printed_path = True
634 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000635 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000636
637 # Build the rebase command here using the args
638 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
639 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000640 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000641 rebase_cmd.append('--verbose')
642 if newbase:
643 rebase_cmd.extend(['--onto', newbase])
644 rebase_cmd.append(upstream)
645 if branch:
646 rebase_cmd.append(branch)
647
648 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000649 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000650 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000651 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
652 re.match(r'cannot rebase: your index contains uncommitted changes',
653 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000654 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000655 rebase_action = ask_for_data(
656 'Cannot rebase because of unstaged changes.\n'
657 '\'git reset --hard HEAD\' ?\n'
658 'WARNING: destroys any uncommitted work in your current branch!'
659 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000660 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000661 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000662 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000663 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000664 break
665 elif re.match(r'quit|q', rebase_action, re.I):
666 raise gclient_utils.Error("Please merge or rebase manually\n"
667 "cd %s && git " % self.checkout_path
668 + "%s" % ' '.join(rebase_cmd))
669 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000670 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000671 continue
672 else:
673 gclient_utils.Error("Input not recognized")
674 continue
675 elif re.search(r'^CONFLICT', e.stdout, re.M):
676 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
677 "Fix the conflict and run gclient again.\n"
678 "See 'man git-rebase' for details.\n")
679 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000680 print(e.stdout.strip())
681 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000682 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
683 "manually.\ncd %s && git " %
684 self.checkout_path
685 + "%s" % ' '.join(rebase_cmd))
686
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000687 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000688 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000689 # Make the output a little prettier. It's nice to have some
690 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000691 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000692
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000693 @staticmethod
694 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000695 (ok, current_version) = scm.GIT.AssertVersion(min_version)
696 if not ok:
697 raise gclient_utils.Error('git version %s < minimum required %s' %
698 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000699
msb@chromium.org786fb682010-06-02 15:16:23 +0000700 def _IsRebasing(self):
701 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
702 # have a plumbing command to determine whether a rebase is in progress, so
703 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
704 g = os.path.join(self.checkout_path, '.git')
705 return (
706 os.path.isdir(os.path.join(g, "rebase-merge")) or
707 os.path.isdir(os.path.join(g, "rebase-apply")))
708
709 def _CheckClean(self, rev_str):
710 # Make sure the tree is clean; see git-rebase.sh for reference
711 try:
712 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000713 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000714 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000715 raise gclient_utils.Error('\n____ %s%s\n'
716 '\tYou have unstaged changes.\n'
717 '\tPlease commit, stash, or reset.\n'
718 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000719 try:
720 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000721 '--ignore-submodules', 'HEAD', '--'],
722 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000723 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000724 raise gclient_utils.Error('\n____ %s%s\n'
725 '\tYour index contains uncommitted changes\n'
726 '\tPlease commit, stash, or reset.\n'
727 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000728
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000729 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000730 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
731 # reference by a commit). If not, error out -- most likely a rebase is
732 # in progress, try to detect so we can give a better error.
733 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000734 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
735 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000736 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000737 # Commit is not contained by any rev. See if the user is rebasing:
738 if self._IsRebasing():
739 # Punt to the user
740 raise gclient_utils.Error('\n____ %s%s\n'
741 '\tAlready in a conflict, i.e. (no branch).\n'
742 '\tFix the conflict and run gclient again.\n'
743 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
744 '\tSee man git-rebase for details.\n'
745 % (self.relpath, rev_str))
746 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000747 name = ('saved-by-gclient-' +
748 self._Capture(['rev-parse', '--short', 'HEAD']))
749 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000750 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000751 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000752
msb@chromium.org5bde4852009-12-14 16:47:12 +0000753 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000754 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000755 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000756 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000757 return None
758 return branch
759
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000760 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000761 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000762 ['git'] + args,
763 stderr=subprocess2.PIPE,
764 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000765
maruel@chromium.org37e89872010-09-07 16:11:33 +0000766 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000767 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000768 kwargs.setdefault('print_stdout', True)
769 stdout = kwargs.get('stdout', sys.stdout)
770 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
771 ' '.join(args), kwargs['cwd']))
772 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000773
774
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000775class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000776 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000777
floitsch@google.comeaab7842011-04-28 09:07:58 +0000778 def GetRevisionDate(self, revision):
779 """Returns the given revision's date in ISO-8601 format (which contains the
780 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000781 date = scm.SVN.Capture(
782 ['propget', '--revprop', 'svn:date', '-r', revision],
783 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000784 return date.strip()
785
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000786 def cleanup(self, options, args, file_list):
787 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000788 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000789
790 def diff(self, options, args, file_list):
791 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000792 if not os.path.isdir(self.checkout_path):
793 raise gclient_utils.Error('Directory %s is not present.' %
794 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000795 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000796
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000797 def pack(self, options, args, file_list):
798 """Generates a patch file which can be applied to the root of the
799 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000800 if not os.path.isdir(self.checkout_path):
801 raise gclient_utils.Error('Directory %s is not present.' %
802 self.checkout_path)
803 gclient_utils.CheckCallAndFilter(
804 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
805 cwd=self.checkout_path,
806 print_stdout=False,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000807 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000808
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000809 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000810 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000811
812 All updated files will be appended to file_list.
813
814 Raises:
815 Error: if can't get URL for relative path.
816 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000817 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000818 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000819 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000820 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000821 return
822
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000823 hg_path = os.path.join(self.checkout_path, '.hg')
824 if os.path.exists(hg_path):
825 print('________ found .hg directory; skipping %s' % self.relpath)
826 return
827
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000828 if args:
829 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
830
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000831 # revision is the revision to match. It is None if no revision is specified,
832 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000833 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000834 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000835 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000836 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000837 if options.revision:
838 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000839 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000840 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000841 if revision != 'unmanaged':
842 forced_revision = True
843 # Reconstruct the url.
844 url = '%s@%s' % (url, revision)
845 rev_str = ' at %s' % revision
846 else:
847 managed = False
848 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000849 else:
850 forced_revision = False
851 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000852
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000853 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000854 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000855 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000856 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000857 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000858 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000859 return
860
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000861 if not managed:
862 print ('________ unmanaged solution; skipping %s' % self.relpath)
863 return
864
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000865 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000866 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000867 from_info = scm.SVN.CaptureLocalInfo(
868 [], os.path.join(self.checkout_path, '.'))
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000869 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000870 raise gclient_utils.Error(
871 ('Can\'t update/checkout %s if an unversioned directory is present. '
872 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000873
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +0000874 if 'URL' not in from_info:
875 raise gclient_utils.Error(
876 ('gclient is confused. Couldn\'t get the url for %s.\n'
877 'Try using @unmanaged.\n%s') % (
878 self.checkout_path, from_info))
879
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000880 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000881 dir_info = scm.SVN.CaptureStatus(
882 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000883 if any(d[0][2] == 'L' for d in dir_info):
884 try:
885 self._Run(['cleanup', self.checkout_path], options)
886 except subprocess2.CalledProcessError, e:
887 # Get the status again, svn cleanup may have cleaned up at least
888 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000889 dir_info = scm.SVN.CaptureStatus(
890 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +0000891
892 # Try to fix the failures by removing troublesome files.
893 for d in dir_info:
894 if d[0][2] == 'L':
895 if d[0][0] == '!' and options.force:
896 print 'Removing troublesome path %s' % d[1]
897 gclient_utils.rmtree(d[1])
898 else:
899 print 'Not removing troublesome path %s automatically.' % d[1]
900 if d[0][0] == '!':
901 print 'You can pass --force to enable automatic removal.'
902 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000903
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000904 # Retrieve the current HEAD version because svn is slow at null updates.
905 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000906 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000907 revision = str(from_info_live['Revision'])
908 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000909
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000910 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000911 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000912 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000913 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000914 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000915 # The url is invalid or the server is not accessible, it's safer to bail
916 # out right now.
917 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000918 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
919 and (from_info['UUID'] == to_info['UUID']))
920 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000921 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000922 # We have different roots, so check if we can switch --relocate.
923 # Subversion only permits this if the repository UUIDs match.
924 # Perform the switch --relocate, then rewrite the from_url
925 # to reflect where we "are now." (This is the same way that
926 # Subversion itself handles the metadata when switch --relocate
927 # is used.) This makes the checks below for whether we
928 # can update to a revision or have to switch to a different
929 # branch work as expected.
930 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000931 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000932 from_info['Repository Root'],
933 to_info['Repository Root'],
934 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000935 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000936 from_info['URL'] = from_info['URL'].replace(
937 from_info['Repository Root'],
938 to_info['Repository Root'])
939 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000940 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000941 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000942 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000943 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000944 raise gclient_utils.Error(
945 ('Can\'t switch the checkout to %s; UUID don\'t match and '
946 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000947 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000948 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000949 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000950 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000951 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000952 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000953 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000954 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000955 return
956
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000957 # If the provided url has a revision number that matches the revision
958 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000959 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000960 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000961 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000962 else:
963 command = ['update', self.checkout_path]
964 command = self._AddAdditionalUpdateFlags(command, options, revision)
965 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000966
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000967 # If --reset and --delete_unversioned_trees are specified, remove any
968 # untracked files and directories.
969 if options.reset and options.delete_unversioned_trees:
970 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
971 full_path = os.path.join(self.checkout_path, status[1])
972 if (status[0][0] == '?'
973 and os.path.isdir(full_path)
974 and not os.path.islink(full_path)):
975 print('\n_____ removing unversioned directory %s' % status[1])
976 gclient_utils.RemoveDirectory(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000977
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000978 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000979 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000980 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000981 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000982 # Create an empty checkout and then update the one file we want. Future
983 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000984 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000985 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000986 if os.path.exists(os.path.join(self.checkout_path, filename)):
987 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000988 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000989 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000990 # After the initial checkout, we can use update as if it were any other
991 # dep.
992 self.update(options, args, file_list)
993 else:
994 # If the installed version of SVN doesn't support --depth, fallback to
995 # just exporting the file. This has the downside that revision
996 # information is not stored next to the file, so we will have to
997 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000998 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000999 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001000 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001001 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001002 command = self._AddAdditionalUpdateFlags(command, options,
1003 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001004 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001005
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001006 def revert(self, options, args, file_list):
1007 """Reverts local modifications. Subversion specific.
1008
1009 All reverted files will be appended to file_list, even if Subversion
1010 doesn't know about them.
1011 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001012 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001013 if os.path.exists(self.checkout_path):
1014 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001015 # svn revert won't work if the directory doesn't exist. It needs to
1016 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001017 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001018 # Don't reuse the args.
1019 return self.update(options, [], file_list)
1020
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001021 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1022 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1023 print('________ found .git directory; skipping %s' % self.relpath)
1024 return
1025 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1026 print('________ found .hg directory; skipping %s' % self.relpath)
1027 return
1028 if not options.force:
1029 raise gclient_utils.Error('Invalid checkout path, aborting')
1030 print(
1031 '\n_____ %s is not a valid svn checkout, synching instead' %
1032 self.relpath)
1033 gclient_utils.rmtree(self.checkout_path)
1034 # Don't reuse the args.
1035 return self.update(options, [], file_list)
1036
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001037 def printcb(file_status):
1038 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001039 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001040 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001041 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001042 print(os.path.join(self.checkout_path, file_status[1]))
1043 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001044
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001045 # Revert() may delete the directory altogether.
1046 if not os.path.isdir(self.checkout_path):
1047 # Don't reuse the args.
1048 return self.update(options, [], file_list)
1049
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001050 try:
1051 # svn revert is so broken we don't even use it. Using
1052 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001053 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001054 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1055 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001056 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001057 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001058 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001059
msb@chromium.org0f282062009-11-06 20:14:02 +00001060 def revinfo(self, options, args, file_list):
1061 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001062 try:
1063 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001064 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001065 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001066
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001067 def runhooks(self, options, args, file_list):
1068 self.status(options, args, file_list)
1069
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001070 def status(self, options, args, file_list):
1071 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001072 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001073 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001074 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001075 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1076 'The directory does not exist.') %
1077 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001078 # There's no file list to retrieve.
1079 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001080 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001081
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001082 def GetUsableRev(self, rev, options):
1083 """Verifies the validity of the revision for this repository."""
1084 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1085 raise gclient_utils.Error(
1086 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1087 'correct.') % rev)
1088 return rev
1089
msb@chromium.orge6f78352010-01-13 17:05:33 +00001090 def FullUrlForRelativeUrl(self, url):
1091 # Find the forth '/' and strip from there. A bit hackish.
1092 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001093
maruel@chromium.org669600d2010-09-01 19:06:31 +00001094 def _Run(self, args, options, **kwargs):
1095 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001096 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001097 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001098 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001099
1100 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1101 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001102 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001103 scm.SVN.RunAndGetFileList(
1104 options.verbose,
1105 args + ['--ignore-externals'],
1106 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001107 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001108
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001109 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001110 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001111 """Add additional flags to command depending on what options are set.
1112 command should be a list of strings that represents an svn command.
1113
1114 This method returns a new list to be used as a command."""
1115 new_command = command[:]
1116 if revision:
1117 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001118 # We don't want interaction when jobs are used.
1119 if options.jobs > 1:
1120 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001121 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001122 # --accept was added to 'svn update' in svn 1.6.
1123 if not scm.SVN.AssertVersion('1.5')[0]:
1124 return new_command
1125
1126 # It's annoying to have it block in the middle of a sync, just sensible
1127 # defaults.
1128 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001129 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001130 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1131 new_command.extend(('--accept', 'theirs-conflict'))
1132 elif options.manually_grab_svn_rev:
1133 new_command.append('--force')
1134 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1135 new_command.extend(('--accept', 'postpone'))
1136 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1137 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001138 return new_command