blob: 99461d13f97615f1b63b254af58f1afdac03f29a [file] [log] [blame]
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +00001# Copyright (c) 2010 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
70 url.endswith('.git')):
71 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000072 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000073 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000074 return 'svn'
75 return None
76
77
78def CreateSCM(url, root_dir=None, relpath=None):
79 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000080 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000081 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000082 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000083
maruel@chromium.org9eda4112010-06-11 18:56:10 +000084 scm_name = GetScmName(url)
85 if not scm_name in SCM_MAP:
86 raise gclient_utils.Error('No SCM found for url %s' % url)
87 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000088
89
90# SCMWrapper base class
91
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000092class SCMWrapper(object):
93 """Add necessary glue between all the supported SCM.
94
msb@chromium.orgd6504212010-01-13 17:34:31 +000095 This is the abstraction layer to bind to different SCM.
96 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000097 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000098 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000099 self._root_dir = root_dir
100 if self._root_dir:
101 self._root_dir = self._root_dir.replace('/', os.sep)
102 self.relpath = relpath
103 if self.relpath:
104 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000105 if self.relpath and self._root_dir:
106 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000107
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000108 def RunCommand(self, command, options, args, file_list=None):
109 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000110 if file_list is None:
111 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000112
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000113 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
114 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000115
116 if not command in commands:
117 raise gclient_utils.Error('Unknown command %s' % command)
118
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000119 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000120 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000121 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000122
123 return getattr(self, command)(options, args, file_list)
124
125
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000126class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000127 """Wrapper for Git"""
128
floitsch@google.comeaab7842011-04-28 09:07:58 +0000129 def GetRevisionDate(self, revision):
130 """Returns the given revision's date in ISO-8601 format (which contains the
131 time zone)."""
132 # TODO(floitsch): get the time-stamp of the given revision and not just the
133 # time-stamp of the currently checked out revision.
134 return self._Capture(['log', '-n', '1', '--format=%ai'])
135
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000136 @staticmethod
137 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000138 """'Cleanup' the repo.
139
140 There's no real git equivalent for the svn cleanup command, do a no-op.
141 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000142
143 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000144 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000145 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000146
147 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000148 """Export a clean directory tree into the given path.
149
150 Exports into the specified directory, creating the path if it does
151 already exist.
152 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000153 assert len(args) == 1
154 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
155 if not os.path.exists(export_path):
156 os.makedirs(export_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000157 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
158 options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000159
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000160 def pack(self, options, args, file_list):
161 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000162 repository.
163
164 The patch file is generated from a diff of the merge base of HEAD and
165 its upstream branch.
166 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000167 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000168 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000169 ['git', 'diff', merge_base],
170 cwd=self.checkout_path,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000171 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000172
msb@chromium.orge28e4982009-09-25 20:51:45 +0000173 def update(self, options, args, file_list):
174 """Runs git to update or transparently checkout the working copy.
175
176 All updated files will be appended to file_list.
177
178 Raises:
179 Error: if can't get URL for relative path.
180 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000181 if args:
182 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
183
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000184 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000185
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000186 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000187 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000188 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000189 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000190 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000191 # Override the revision number.
192 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000193 if not revision:
194 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000195
floitsch@google.comeaab7842011-04-28 09:07:58 +0000196 if gclient_utils.IsDateRevision(revision):
197 # Date-revisions only work on git-repositories if the reflog hasn't
198 # expired yet. Use rev-list to get the corresponding revision.
199 # git rev-list -n 1 --before='time-stamp' branchname
200 if options.transitive:
201 print('Warning: --transitive only works for SVN repositories.')
202 revision = default_rev
203
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000204 rev_str = ' at %s' % revision
205 files = []
206
207 printed_path = False
208 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000209 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000210 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000211 verbose = ['--verbose']
212 printed_path = True
213
214 if revision.startswith('refs/heads/'):
215 rev_type = "branch"
216 elif revision.startswith('origin/'):
217 # For compatability with old naming, translate 'origin' to 'refs/heads'
218 revision = revision.replace('origin/', 'refs/heads/')
219 rev_type = "branch"
220 else:
221 # hash is also a tag, only make a distinction at checkout
222 rev_type = "hash"
223
msb@chromium.orge28e4982009-09-25 20:51:45 +0000224 if not os.path.exists(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000225 self._Clone(revision, url, options)
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000226 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000227 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000228 if not verbose:
229 # Make the output a little prettier. It's nice to have some whitespace
230 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000231 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000232 return
233
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000234 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
235 raise gclient_utils.Error('\n____ %s%s\n'
236 '\tPath is not a git repo. No .git dir.\n'
237 '\tTo resolve:\n'
238 '\t\trm -rf %s\n'
239 '\tAnd run gclient sync again\n'
240 % (self.relpath, rev_str, self.relpath))
241
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000242 # See if the url has changed (the unittests use git://foo for the url, let
243 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000244 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000245 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
246 # unit test pass. (and update the comment above)
247 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000248 print('_____ switching %s to a new upstream' % self.relpath)
249 # Make sure it's clean
250 self._CheckClean(rev_str)
251 # Switch over to the new upstream
252 self._Run(['remote', 'set-url', 'origin', url], options)
253 quiet = []
254 if not options.verbose:
255 quiet = ['--quiet']
256 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
257 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
258 files = self._Capture(['ls-files']).splitlines()
259 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
260 return
261
msb@chromium.org5bde4852009-12-14 16:47:12 +0000262 cur_branch = self._GetCurrentBranch()
263
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000264 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000265 # 0) HEAD is detached. Probably from our initial clone.
266 # - make sure HEAD is contained by a named ref, then update.
267 # Cases 1-4. HEAD is a branch.
268 # 1) current branch is not tracking a remote branch (could be git-svn)
269 # - try to rebase onto the new hash or branch
270 # 2) current branch is tracking a remote branch with local committed
271 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000272 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000273 # 3) current branch is tracking a remote branch w/or w/out changes,
274 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000275 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000276 # 4) current branch is tracking a remote branch, switches to a different
277 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000278 # - exit
279
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000280 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
281 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000282 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
283 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000284 if cur_branch is None:
285 upstream_branch = None
286 current_type = "detached"
287 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000288 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000289 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
290 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
291 current_type = "hash"
292 logging.debug("Current branch is not tracking an upstream (remote)"
293 " branch.")
294 elif upstream_branch.startswith('refs/remotes'):
295 current_type = "branch"
296 else:
297 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000298
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000299 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000300 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000301 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000302 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000303 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000304 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000305 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000306 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000307 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000308 # Hackish but at that point, git is known to work so just checking for
309 # 502 in stderr should be fine.
310 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000311 print(str(e))
312 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000313 time.sleep(backoff_time)
314 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000315 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000316 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000317
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000318 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000319 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000320
321 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000322 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000323 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000324
msb@chromium.org786fb682010-06-02 15:16:23 +0000325 if current_type == 'detached':
326 # case 0
327 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000328 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000329 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000330 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000331 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000332 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000333 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000334 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000335 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000336 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000337 newbase=revision, printed_path=printed_path)
338 printed_path = True
339 else:
340 # Can't find a merge-base since we don't know our upstream. That makes
341 # this command VERY likely to produce a rebase failure. For now we
342 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000343 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000344 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000345 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000346 self._AttemptRebase(upstream_branch, files, options,
347 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000348 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000349 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000350 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000351 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000352 newbase=revision, printed_path=printed_path)
353 printed_path = True
354 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
355 # case 4
356 new_base = revision.replace('heads', 'remotes/origin')
357 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000358 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000359 switch_error = ("Switching upstream branch from %s to %s\n"
360 % (upstream_branch, new_base) +
361 "Please merge or rebase manually:\n" +
362 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
363 "OR git checkout -b <some new branch> %s" % new_base)
364 raise gclient_utils.Error(switch_error)
365 else:
366 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000367 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000368 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000369 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000370 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000371 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
372 cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000373 except gclient_utils.CheckCallError, e:
374 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
375 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000376 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000377 printed_path = True
378 while True:
379 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000380 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000381 action = ask_for_data(
382 'Cannot fast-forward merge, attempt to rebase? '
383 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000384 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000385 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000386 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000387 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000388 printed_path=printed_path)
389 printed_path = True
390 break
391 elif re.match(r'quit|q', action, re.I):
392 raise gclient_utils.Error("Can't fast-forward, please merge or "
393 "rebase manually.\n"
394 "cd %s && git " % self.checkout_path
395 + "rebase %s" % upstream_branch)
396 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000397 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000398 return
399 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000400 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000401 elif re.match("error: Your local changes to '.*' would be "
402 "overwritten by merge. Aborting.\nPlease, commit your "
403 "changes or stash them before you can merge.\n",
404 e.stderr):
405 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000406 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000407 printed_path = True
408 raise gclient_utils.Error(e.stderr)
409 else:
410 # Some other problem happened with the merge
411 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000412 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000413 raise
414 else:
415 # Fast-forward merge was successful
416 if not re.match('Already up-to-date.', merge_output) or verbose:
417 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000418 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000419 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000420 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000421 if not verbose:
422 # Make the output a little prettier. It's nice to have some
423 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000424 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000425
426 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000427
428 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000429 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000430 raise gclient_utils.Error('\n____ %s%s\n'
431 '\nConflict while rebasing this branch.\n'
432 'Fix the conflict and run gclient again.\n'
433 'See man git-rebase for details.\n'
434 % (self.relpath, rev_str))
435
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000436 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000437 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000438
439 def revert(self, options, args, file_list):
440 """Reverts local modifications.
441
442 All reverted files will be appended to file_list.
443 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000444 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000445 # revert won't work if the directory doesn't exist. It needs to
446 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000447 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000448 # Don't reuse the args.
449 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000450
451 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000452 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000453 if not deps_revision:
454 deps_revision = default_rev
455 if deps_revision.startswith('refs/heads/'):
456 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
457
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000458 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000459 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000460 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
461
msb@chromium.org0f282062009-11-06 20:14:02 +0000462 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000463 """Returns revision"""
464 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000465
msb@chromium.orge28e4982009-09-25 20:51:45 +0000466 def runhooks(self, options, args, file_list):
467 self.status(options, args, file_list)
468
469 def status(self, options, args, file_list):
470 """Display status information."""
471 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000472 print(('\n________ couldn\'t run status in %s:\n'
473 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000474 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000475 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000476 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000477 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000478 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
479
msb@chromium.orge6f78352010-01-13 17:05:33 +0000480 def FullUrlForRelativeUrl(self, url):
481 # Strip from last '/'
482 # Equivalent to unix basename
483 base_url = self.url
484 return base_url[:base_url.rfind('/')] + url
485
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000486 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000487 """Clone a git repository from the given URL.
488
msb@chromium.org786fb682010-06-02 15:16:23 +0000489 Once we've cloned the repo, we checkout a working branch if the specified
490 revision is a branch head. If it is a tag or a specific commit, then we
491 leave HEAD detached as it makes future updates simpler -- in this case the
492 user should first create a new branch or switch to an existing branch before
493 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000494 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000495 # git clone doesn't seem to insert a newline properly before printing
496 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000497 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000498
499 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000500 if revision.startswith('refs/heads/'):
501 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
502 detach_head = False
503 else:
504 clone_cmd.append('--no-checkout')
505 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000506 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000507 clone_cmd.append('--verbose')
508 clone_cmd.extend([url, self.checkout_path])
509
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000510 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000511 try:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000512 self._Run(clone_cmd, options, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000513 break
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000514 except (gclient_utils.Error, subprocess2.CalledProcessError), e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000515 # TODO(maruel): Hackish, should be fixed by moving _Run() to
516 # CheckCall().
517 # Too bad we don't have access to the actual output.
518 # We should check for "transfer closed with NNN bytes remaining to
519 # read". In the meantime, just make sure .git exists.
520 if (e.args[0] == 'git command clone returned 128' and
521 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000522 print(str(e))
523 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000524 continue
525 raise e
526
msb@chromium.org786fb682010-06-02 15:16:23 +0000527 if detach_head:
528 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000529 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000530 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000531 ('Checked out %s to a detached HEAD. Before making any commits\n'
532 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
533 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
534 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000535
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000536 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000537 branch=None, printed_path=False):
538 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000539 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000540 revision = upstream
541 if newbase:
542 revision = newbase
543 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000544 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000545 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000546 printed_path = True
547 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000548 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000549
550 # Build the rebase command here using the args
551 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
552 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000553 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000554 rebase_cmd.append('--verbose')
555 if newbase:
556 rebase_cmd.extend(['--onto', newbase])
557 rebase_cmd.append(upstream)
558 if branch:
559 rebase_cmd.append(branch)
560
561 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000562 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000563 except gclient_utils.CheckCallError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000564 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
565 re.match(r'cannot rebase: your index contains uncommitted changes',
566 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000567 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000568 rebase_action = ask_for_data(
569 'Cannot rebase because of unstaged changes.\n'
570 '\'git reset --hard HEAD\' ?\n'
571 'WARNING: destroys any uncommitted work in your current branch!'
572 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000573 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000574 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000575 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000576 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000577 break
578 elif re.match(r'quit|q', rebase_action, re.I):
579 raise gclient_utils.Error("Please merge or rebase manually\n"
580 "cd %s && git " % self.checkout_path
581 + "%s" % ' '.join(rebase_cmd))
582 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000583 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000584 continue
585 else:
586 gclient_utils.Error("Input not recognized")
587 continue
588 elif re.search(r'^CONFLICT', e.stdout, re.M):
589 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
590 "Fix the conflict and run gclient again.\n"
591 "See 'man git-rebase' for details.\n")
592 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000593 print(e.stdout.strip())
594 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000595 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
596 "manually.\ncd %s && git " %
597 self.checkout_path
598 + "%s" % ' '.join(rebase_cmd))
599
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000600 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000601 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000602 # Make the output a little prettier. It's nice to have some
603 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000604 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000605
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000606 @staticmethod
607 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000608 (ok, current_version) = scm.GIT.AssertVersion(min_version)
609 if not ok:
610 raise gclient_utils.Error('git version %s < minimum required %s' %
611 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000612
msb@chromium.org786fb682010-06-02 15:16:23 +0000613 def _IsRebasing(self):
614 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
615 # have a plumbing command to determine whether a rebase is in progress, so
616 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
617 g = os.path.join(self.checkout_path, '.git')
618 return (
619 os.path.isdir(os.path.join(g, "rebase-merge")) or
620 os.path.isdir(os.path.join(g, "rebase-apply")))
621
622 def _CheckClean(self, rev_str):
623 # Make sure the tree is clean; see git-rebase.sh for reference
624 try:
625 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000626 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000627 except gclient_utils.CheckCallError:
628 raise gclient_utils.Error('\n____ %s%s\n'
629 '\tYou have unstaged changes.\n'
630 '\tPlease commit, stash, or reset.\n'
631 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000632 try:
633 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000634 '--ignore-submodules', 'HEAD', '--'],
635 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000636 except gclient_utils.CheckCallError:
637 raise gclient_utils.Error('\n____ %s%s\n'
638 '\tYour index contains uncommitted changes\n'
639 '\tPlease commit, stash, or reset.\n'
640 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000641
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000642 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000643 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
644 # reference by a commit). If not, error out -- most likely a rebase is
645 # in progress, try to detect so we can give a better error.
646 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000647 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
648 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000649 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000650 # Commit is not contained by any rev. See if the user is rebasing:
651 if self._IsRebasing():
652 # Punt to the user
653 raise gclient_utils.Error('\n____ %s%s\n'
654 '\tAlready in a conflict, i.e. (no branch).\n'
655 '\tFix the conflict and run gclient again.\n'
656 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
657 '\tSee man git-rebase for details.\n'
658 % (self.relpath, rev_str))
659 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000660 name = ('saved-by-gclient-' +
661 self._Capture(['rev-parse', '--short', 'HEAD']))
662 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000663 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000664 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000665
msb@chromium.org5bde4852009-12-14 16:47:12 +0000666 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000667 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000668 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000669 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000670 return None
671 return branch
672
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000673 def _Capture(self, args):
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000674 return gclient_utils.CheckCall(
675 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000676
maruel@chromium.org37e89872010-09-07 16:11:33 +0000677 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000678 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000679 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000680 always=options.verbose, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000681
682
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000683class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000684 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000685
floitsch@google.comeaab7842011-04-28 09:07:58 +0000686 def GetRevisionDate(self, revision):
687 """Returns the given revision's date in ISO-8601 format (which contains the
688 time zone)."""
689 date = scm.SVN.Capture(['propget', '--revprop', 'svn:date', '-r', revision,
690 os.path.join(self.checkout_path, '.')])
691 return date.strip()
692
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000693 def cleanup(self, options, args, file_list):
694 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000695 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000696
697 def diff(self, options, args, file_list):
698 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000699 if not os.path.isdir(self.checkout_path):
700 raise gclient_utils.Error('Directory %s is not present.' %
701 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000702 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000703
704 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000705 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000706 assert len(args) == 1
707 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
708 try:
709 os.makedirs(export_path)
710 except OSError:
711 pass
712 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000713 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000714
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000715 def pack(self, options, args, file_list):
716 """Generates a patch file which can be applied to the root of the
717 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000718 if not os.path.isdir(self.checkout_path):
719 raise gclient_utils.Error('Directory %s is not present.' %
720 self.checkout_path)
721 gclient_utils.CheckCallAndFilter(
722 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
723 cwd=self.checkout_path,
724 print_stdout=False,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000725 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000726
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000727 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000728 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000729
730 All updated files will be appended to file_list.
731
732 Raises:
733 Error: if can't get URL for relative path.
734 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000735 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000736 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000737 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000738 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000739 return
740
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000741 hg_path = os.path.join(self.checkout_path, '.hg')
742 if os.path.exists(hg_path):
743 print('________ found .hg directory; skipping %s' % self.relpath)
744 return
745
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000746 if args:
747 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
748
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000749 # revision is the revision to match. It is None if no revision is specified,
750 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000751 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000752 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000753 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000754 if options.revision:
755 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000756 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000757 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000758 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000759 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000760 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000761 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000762 else:
763 forced_revision = False
764 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000765
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000766 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000767 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000768 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000769 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000770 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000771 return
772
773 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000774 try:
775 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000776 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000777 raise gclient_utils.Error(
778 ('Can\'t update/checkout %s if an unversioned directory is present. '
779 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000780
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000781 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000782 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
783 if [True for d in dir_info
784 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000785 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000786 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000787
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000788 # Retrieve the current HEAD version because svn is slow at null updates.
789 if options.manually_grab_svn_rev and not revision:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000790 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000791 revision = str(from_info_live['Revision'])
792 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000793
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000794 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000795 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000796 try:
797 to_info = scm.SVN.CaptureInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000798 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000799 # The url is invalid or the server is not accessible, it's safer to bail
800 # out right now.
801 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000802 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
803 and (from_info['UUID'] == to_info['UUID']))
804 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000805 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000806 # We have different roots, so check if we can switch --relocate.
807 # Subversion only permits this if the repository UUIDs match.
808 # Perform the switch --relocate, then rewrite the from_url
809 # to reflect where we "are now." (This is the same way that
810 # Subversion itself handles the metadata when switch --relocate
811 # is used.) This makes the checks below for whether we
812 # can update to a revision or have to switch to a different
813 # branch work as expected.
814 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000815 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000816 from_info['Repository Root'],
817 to_info['Repository Root'],
818 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000819 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000820 from_info['URL'] = from_info['URL'].replace(
821 from_info['Repository Root'],
822 to_info['Repository Root'])
823 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000824 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000825 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000826 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000827 if status[0] != '?':
828 raise gclient_utils.Error(
829 ('Can\'t switch the checkout to %s; UUID don\'t match and '
830 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000831 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000832 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000833 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000834 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000835 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000836 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000837 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000838 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000839 return
840
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000841 # If the provided url has a revision number that matches the revision
842 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000843 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000844 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000845 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000846 return
847
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000848 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000849 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000850 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000851
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000852 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000853 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000854 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000855 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000856 # Create an empty checkout and then update the one file we want. Future
857 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000858 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000859 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000860 if os.path.exists(os.path.join(self.checkout_path, filename)):
861 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000862 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000863 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000864 # After the initial checkout, we can use update as if it were any other
865 # dep.
866 self.update(options, args, file_list)
867 else:
868 # If the installed version of SVN doesn't support --depth, fallback to
869 # just exporting the file. This has the downside that revision
870 # information is not stored next to the file, so we will have to
871 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000872 if not os.path.exists(self.checkout_path):
873 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000874 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000875 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000876 command = self._AddAdditionalUpdateFlags(command, options,
877 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000878 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000879
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000880 def revert(self, options, args, file_list):
881 """Reverts local modifications. Subversion specific.
882
883 All reverted files will be appended to file_list, even if Subversion
884 doesn't know about them.
885 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000886 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000887 # svn revert won't work if the directory doesn't exist. It needs to
888 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000889 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000890 # Don't reuse the args.
891 return self.update(options, [], file_list)
892
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000893 def printcb(file_status):
894 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000895 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000896 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000897 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000898 print(os.path.join(self.checkout_path, file_status[1]))
899 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000900
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000901 try:
902 # svn revert is so broken we don't even use it. Using
903 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000904 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000905 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
906 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000907 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000908 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000909 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000910
msb@chromium.org0f282062009-11-06 20:14:02 +0000911 def revinfo(self, options, args, file_list):
912 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000913 try:
914 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +0000915 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000916 return None
msb@chromium.org0f282062009-11-06 20:14:02 +0000917
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000918 def runhooks(self, options, args, file_list):
919 self.status(options, args, file_list)
920
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000921 def status(self, options, args, file_list):
922 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000923 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000924 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000925 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000926 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
927 'The directory does not exist.') %
928 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000929 # There's no file list to retrieve.
930 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000931 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000932
933 def FullUrlForRelativeUrl(self, url):
934 # Find the forth '/' and strip from there. A bit hackish.
935 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000936
maruel@chromium.org669600d2010-09-01 19:06:31 +0000937 def _Run(self, args, options, **kwargs):
938 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000939 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000940 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000941 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000942
943 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
944 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000945 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +0000946 scm.SVN.RunAndGetFileList(
947 options.verbose,
948 args + ['--ignore-externals'],
949 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000950 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000951
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000952 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000953 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000954 """Add additional flags to command depending on what options are set.
955 command should be a list of strings that represents an svn command.
956
957 This method returns a new list to be used as a command."""
958 new_command = command[:]
959 if revision:
960 new_command.extend(['--revision', str(revision).strip()])
961 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000962 if ((options.force or options.manually_grab_svn_rev) and
963 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000964 new_command.append('--force')
965 return new_command