blob: 38656431a5072ecff2a54fe4ff33583b423cd4b2 [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.orgfd876172010-04-30 14:01:05 +000011import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000012
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000013import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000014import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015
16
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000017class DiffFilterer(object):
18 """Simple class which tracks which file is being diffed and
19 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000020 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000021 index_string = "Index: "
22 original_prefix = "--- "
23 working_prefix = "+++ "
24
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000025 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000026 # Note that we always use '/' as the path separator to be
27 # consistent with svn's cygwin-style output on Windows
28 self._relpath = relpath.replace("\\", "/")
29 self._current_file = ""
30 self._replacement_file = ""
31
maruel@chromium.org6e29d572010-06-04 17:32:20 +000032 def SetCurrentFile(self, current_file):
33 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000034 # Note that we always use '/' as the path separator to be
35 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000036 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000037
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000038 def _Replace(self, line):
39 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000040
41 def Filter(self, line):
42 if (line.startswith(self.index_string)):
43 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000044 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000045 else:
46 if (line.startswith(self.original_prefix) or
47 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000048 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000049 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000050
51
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000052### SCM abstraction layer
53
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000054# Factory Method for SCM wrapper creation
55
maruel@chromium.org9eda4112010-06-11 18:56:10 +000056def GetScmName(url):
57 if url:
58 url, _ = gclient_utils.SplitUrlRevision(url)
59 if (url.startswith('git://') or url.startswith('ssh://') or
60 url.endswith('.git')):
61 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000062 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000063 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000064 return 'svn'
65 return None
66
67
68def CreateSCM(url, root_dir=None, relpath=None):
69 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000070 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000071 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000072 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000073
maruel@chromium.org9eda4112010-06-11 18:56:10 +000074 scm_name = GetScmName(url)
75 if not scm_name in SCM_MAP:
76 raise gclient_utils.Error('No SCM found for url %s' % url)
77 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000078
79
80# SCMWrapper base class
81
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000082class SCMWrapper(object):
83 """Add necessary glue between all the supported SCM.
84
msb@chromium.orgd6504212010-01-13 17:34:31 +000085 This is the abstraction layer to bind to different SCM.
86 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000087 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000088 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000089 self._root_dir = root_dir
90 if self._root_dir:
91 self._root_dir = self._root_dir.replace('/', os.sep)
92 self.relpath = relpath
93 if self.relpath:
94 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000095 if self.relpath and self._root_dir:
96 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000097
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000098 def RunCommand(self, command, options, args, file_list=None):
99 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000100 if file_list is None:
101 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000102
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000103 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
104 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000105
106 if not command in commands:
107 raise gclient_utils.Error('Unknown command %s' % command)
108
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000109 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000110 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000111 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000112
113 return getattr(self, command)(options, args, file_list)
114
115
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000116class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000117 """Wrapper for Git"""
118
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000119 @staticmethod
120 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000121 """'Cleanup' the repo.
122
123 There's no real git equivalent for the svn cleanup command, do a no-op.
124 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000125
126 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000127 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000128 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000129
130 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000131 """Export a clean directory tree into the given path.
132
133 Exports into the specified directory, creating the path if it does
134 already exist.
135 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000136 assert len(args) == 1
137 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
138 if not os.path.exists(export_path):
139 os.makedirs(export_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000140 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
141 options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000142
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000143 def pack(self, options, args, file_list):
144 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000145 repository.
146
147 The patch file is generated from a diff of the merge base of HEAD and
148 its upstream branch.
149 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000150 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000151 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000152 ['git', 'diff', merge_base],
153 cwd=self.checkout_path,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000154 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000155
msb@chromium.orge28e4982009-09-25 20:51:45 +0000156 def update(self, options, args, file_list):
157 """Runs git to update or transparently checkout the working copy.
158
159 All updated files will be appended to file_list.
160
161 Raises:
162 Error: if can't get URL for relative path.
163 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000164 if args:
165 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
166
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000167 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000168
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000169 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000170 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000171 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000172 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000173 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000174 # Override the revision number.
175 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000176 if not revision:
177 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000178
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000179 rev_str = ' at %s' % revision
180 files = []
181
182 printed_path = False
183 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000184 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000185 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000186 verbose = ['--verbose']
187 printed_path = True
188
189 if revision.startswith('refs/heads/'):
190 rev_type = "branch"
191 elif revision.startswith('origin/'):
192 # For compatability with old naming, translate 'origin' to 'refs/heads'
193 revision = revision.replace('origin/', 'refs/heads/')
194 rev_type = "branch"
195 else:
196 # hash is also a tag, only make a distinction at checkout
197 rev_type = "hash"
198
msb@chromium.orge28e4982009-09-25 20:51:45 +0000199 if not os.path.exists(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000200 self._Clone(revision, url, options)
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000201 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000202 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000203 if not verbose:
204 # Make the output a little prettier. It's nice to have some whitespace
205 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000206 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000207 return
208
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000209 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
210 raise gclient_utils.Error('\n____ %s%s\n'
211 '\tPath is not a git repo. No .git dir.\n'
212 '\tTo resolve:\n'
213 '\t\trm -rf %s\n'
214 '\tAnd run gclient sync again\n'
215 % (self.relpath, rev_str, self.relpath))
216
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000217 # See if the url has changed (the unittests use git://foo for the url, let
218 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000219 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000220 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
221 # unit test pass. (and update the comment above)
222 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000223 print('_____ switching %s to a new upstream' % self.relpath)
224 # Make sure it's clean
225 self._CheckClean(rev_str)
226 # Switch over to the new upstream
227 self._Run(['remote', 'set-url', 'origin', url], options)
228 quiet = []
229 if not options.verbose:
230 quiet = ['--quiet']
231 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
232 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
233 files = self._Capture(['ls-files']).splitlines()
234 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
235 return
236
msb@chromium.org5bde4852009-12-14 16:47:12 +0000237 cur_branch = self._GetCurrentBranch()
238
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000239 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000240 # 0) HEAD is detached. Probably from our initial clone.
241 # - make sure HEAD is contained by a named ref, then update.
242 # Cases 1-4. HEAD is a branch.
243 # 1) current branch is not tracking a remote branch (could be git-svn)
244 # - try to rebase onto the new hash or branch
245 # 2) current branch is tracking a remote branch with local committed
246 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000247 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000248 # 3) current branch is tracking a remote branch w/or w/out changes,
249 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000250 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000251 # 4) current branch is tracking a remote branch, switches to a different
252 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000253 # - exit
254
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000255 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
256 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000257 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
258 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000259 if cur_branch is None:
260 upstream_branch = None
261 current_type = "detached"
262 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000263 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000264 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
265 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
266 current_type = "hash"
267 logging.debug("Current branch is not tracking an upstream (remote)"
268 " branch.")
269 elif upstream_branch.startswith('refs/remotes'):
270 current_type = "branch"
271 else:
272 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000273
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000274 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000275 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000276 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000277 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000278 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000279 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000280 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000281 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000282 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000283 # Hackish but at that point, git is known to work so just checking for
284 # 502 in stderr should be fine.
285 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000286 print(str(e))
287 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000288 time.sleep(backoff_time)
289 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000290 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000291 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000292
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000293 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000294 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000295
296 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000297 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000298 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000299
msb@chromium.org786fb682010-06-02 15:16:23 +0000300 if current_type == 'detached':
301 # case 0
302 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000303 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000304 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000305 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000306 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000307 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000308 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000309 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000310 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000311 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000312 newbase=revision, printed_path=printed_path)
313 printed_path = True
314 else:
315 # Can't find a merge-base since we don't know our upstream. That makes
316 # this command VERY likely to produce a rebase failure. For now we
317 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000318 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000319 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000320 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000321 self._AttemptRebase(upstream_branch, files, options,
322 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000323 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000324 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000325 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000326 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000327 newbase=revision, printed_path=printed_path)
328 printed_path = True
329 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
330 # case 4
331 new_base = revision.replace('heads', 'remotes/origin')
332 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000333 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000334 switch_error = ("Switching upstream branch from %s to %s\n"
335 % (upstream_branch, new_base) +
336 "Please merge or rebase manually:\n" +
337 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
338 "OR git checkout -b <some new branch> %s" % new_base)
339 raise gclient_utils.Error(switch_error)
340 else:
341 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000342 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000343 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000344 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000345 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000346 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
347 cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000348 except gclient_utils.CheckCallError, e:
349 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
350 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000351 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000352 printed_path = True
353 while True:
354 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000355 # TODO(maruel): That can't work with --jobs.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000356 action = str(raw_input("Cannot fast-forward merge, attempt to "
357 "rebase? (y)es / (q)uit / (s)kip : "))
358 except ValueError:
359 gclient_utils.Error('Invalid Character')
360 continue
361 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000362 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000363 printed_path=printed_path)
364 printed_path = True
365 break
366 elif re.match(r'quit|q', action, re.I):
367 raise gclient_utils.Error("Can't fast-forward, please merge or "
368 "rebase manually.\n"
369 "cd %s && git " % self.checkout_path
370 + "rebase %s" % upstream_branch)
371 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000372 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000373 return
374 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000375 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000376 elif re.match("error: Your local changes to '.*' would be "
377 "overwritten by merge. Aborting.\nPlease, commit your "
378 "changes or stash them before you can merge.\n",
379 e.stderr):
380 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000381 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000382 printed_path = True
383 raise gclient_utils.Error(e.stderr)
384 else:
385 # Some other problem happened with the merge
386 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000387 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000388 raise
389 else:
390 # Fast-forward merge was successful
391 if not re.match('Already up-to-date.', merge_output) or verbose:
392 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000393 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000394 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000395 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000396 if not verbose:
397 # Make the output a little prettier. It's nice to have some
398 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000399 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000400
401 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000402
403 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000404 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000405 raise gclient_utils.Error('\n____ %s%s\n'
406 '\nConflict while rebasing this branch.\n'
407 'Fix the conflict and run gclient again.\n'
408 'See man git-rebase for details.\n'
409 % (self.relpath, rev_str))
410
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000411 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000412 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000413
414 def revert(self, options, args, file_list):
415 """Reverts local modifications.
416
417 All reverted files will be appended to file_list.
418 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000419 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000420 # revert won't work if the directory doesn't exist. It needs to
421 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000422 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000423 # Don't reuse the args.
424 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000425
426 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000427 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000428 if not deps_revision:
429 deps_revision = default_rev
430 if deps_revision.startswith('refs/heads/'):
431 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
432
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000433 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000434 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000435 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
436
msb@chromium.org0f282062009-11-06 20:14:02 +0000437 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000438 """Returns revision"""
439 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000440
msb@chromium.orge28e4982009-09-25 20:51:45 +0000441 def runhooks(self, options, args, file_list):
442 self.status(options, args, file_list)
443
444 def status(self, options, args, file_list):
445 """Display status information."""
446 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000447 print(('\n________ couldn\'t run status in %s:\n'
448 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000449 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000450 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000451 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000452 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000453 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
454
msb@chromium.orge6f78352010-01-13 17:05:33 +0000455 def FullUrlForRelativeUrl(self, url):
456 # Strip from last '/'
457 # Equivalent to unix basename
458 base_url = self.url
459 return base_url[:base_url.rfind('/')] + url
460
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000461 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000462 """Clone a git repository from the given URL.
463
msb@chromium.org786fb682010-06-02 15:16:23 +0000464 Once we've cloned the repo, we checkout a working branch if the specified
465 revision is a branch head. If it is a tag or a specific commit, then we
466 leave HEAD detached as it makes future updates simpler -- in this case the
467 user should first create a new branch or switch to an existing branch before
468 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000469 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470 # git clone doesn't seem to insert a newline properly before printing
471 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000472 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000473
474 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000475 if revision.startswith('refs/heads/'):
476 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
477 detach_head = False
478 else:
479 clone_cmd.append('--no-checkout')
480 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000481 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000482 clone_cmd.append('--verbose')
483 clone_cmd.extend([url, self.checkout_path])
484
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000485 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000486 try:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000487 self._Run(clone_cmd, options, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000488 break
489 except gclient_utils.Error, e:
490 # TODO(maruel): Hackish, should be fixed by moving _Run() to
491 # CheckCall().
492 # Too bad we don't have access to the actual output.
493 # We should check for "transfer closed with NNN bytes remaining to
494 # read". In the meantime, just make sure .git exists.
495 if (e.args[0] == 'git command clone returned 128' and
496 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000497 print(str(e))
498 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000499 continue
500 raise e
501
msb@chromium.org786fb682010-06-02 15:16:23 +0000502 if detach_head:
503 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000504 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000505 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000506 ('Checked out %s to a detached HEAD. Before making any commits\n'
507 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
508 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
509 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000510
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000511 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000512 branch=None, printed_path=False):
513 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000514 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000515 revision = upstream
516 if newbase:
517 revision = newbase
518 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000519 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000520 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000521 printed_path = True
522 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000523 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000524
525 # Build the rebase command here using the args
526 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
527 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000528 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000529 rebase_cmd.append('--verbose')
530 if newbase:
531 rebase_cmd.extend(['--onto', newbase])
532 rebase_cmd.append(upstream)
533 if branch:
534 rebase_cmd.append(branch)
535
536 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000537 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000538 except gclient_utils.CheckCallError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000539 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
540 re.match(r'cannot rebase: your index contains uncommitted changes',
541 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000542 while True:
543 rebase_action = str(raw_input("Cannot rebase because of unstaged "
544 "changes.\n'git reset --hard HEAD' ?\n"
545 "WARNING: destroys any uncommitted "
546 "work in your current branch!"
547 " (y)es / (q)uit / (s)how : "))
548 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000549 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000550 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000551 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000552 break
553 elif re.match(r'quit|q', rebase_action, re.I):
554 raise gclient_utils.Error("Please merge or rebase manually\n"
555 "cd %s && git " % self.checkout_path
556 + "%s" % ' '.join(rebase_cmd))
557 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000558 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000559 continue
560 else:
561 gclient_utils.Error("Input not recognized")
562 continue
563 elif re.search(r'^CONFLICT', e.stdout, re.M):
564 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
565 "Fix the conflict and run gclient again.\n"
566 "See 'man git-rebase' for details.\n")
567 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000568 print(e.stdout.strip())
569 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000570 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
571 "manually.\ncd %s && git " %
572 self.checkout_path
573 + "%s" % ' '.join(rebase_cmd))
574
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000575 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000576 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000577 # Make the output a little prettier. It's nice to have some
578 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000579 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000580
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000581 @staticmethod
582 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000583 (ok, current_version) = scm.GIT.AssertVersion(min_version)
584 if not ok:
585 raise gclient_utils.Error('git version %s < minimum required %s' %
586 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000587
msb@chromium.org786fb682010-06-02 15:16:23 +0000588 def _IsRebasing(self):
589 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
590 # have a plumbing command to determine whether a rebase is in progress, so
591 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
592 g = os.path.join(self.checkout_path, '.git')
593 return (
594 os.path.isdir(os.path.join(g, "rebase-merge")) or
595 os.path.isdir(os.path.join(g, "rebase-apply")))
596
597 def _CheckClean(self, rev_str):
598 # Make sure the tree is clean; see git-rebase.sh for reference
599 try:
600 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000601 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000602 except gclient_utils.CheckCallError:
603 raise gclient_utils.Error('\n____ %s%s\n'
604 '\tYou have unstaged changes.\n'
605 '\tPlease commit, stash, or reset.\n'
606 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000607 try:
608 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000609 '--ignore-submodules', 'HEAD', '--'],
610 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000611 except gclient_utils.CheckCallError:
612 raise gclient_utils.Error('\n____ %s%s\n'
613 '\tYour index contains uncommitted changes\n'
614 '\tPlease commit, stash, or reset.\n'
615 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000616
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000617 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000618 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
619 # reference by a commit). If not, error out -- most likely a rebase is
620 # in progress, try to detect so we can give a better error.
621 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000622 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
623 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000624 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000625 # Commit is not contained by any rev. See if the user is rebasing:
626 if self._IsRebasing():
627 # Punt to the user
628 raise gclient_utils.Error('\n____ %s%s\n'
629 '\tAlready in a conflict, i.e. (no branch).\n'
630 '\tFix the conflict and run gclient again.\n'
631 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
632 '\tSee man git-rebase for details.\n'
633 % (self.relpath, rev_str))
634 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000635 name = ('saved-by-gclient-' +
636 self._Capture(['rev-parse', '--short', 'HEAD']))
637 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000638 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000639 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000640
msb@chromium.org5bde4852009-12-14 16:47:12 +0000641 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000642 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000643 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000644 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000645 return None
646 return branch
647
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000648 def _Capture(self, args):
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000649 return gclient_utils.CheckCall(
650 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000651
maruel@chromium.org37e89872010-09-07 16:11:33 +0000652 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000653 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000654 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000655 always=options.verbose, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000656
657
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000658class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000659 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000660
661 def cleanup(self, options, args, file_list):
662 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000663 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000664
665 def diff(self, options, args, file_list):
666 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000667 if not os.path.isdir(self.checkout_path):
668 raise gclient_utils.Error('Directory %s is not present.' %
669 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000670 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000671
672 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000673 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000674 assert len(args) == 1
675 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
676 try:
677 os.makedirs(export_path)
678 except OSError:
679 pass
680 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000681 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000682
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000683 def pack(self, options, args, file_list):
684 """Generates a patch file which can be applied to the root of the
685 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000686 if not os.path.isdir(self.checkout_path):
687 raise gclient_utils.Error('Directory %s is not present.' %
688 self.checkout_path)
689 gclient_utils.CheckCallAndFilter(
690 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
691 cwd=self.checkout_path,
692 print_stdout=False,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000693 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000694
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000695 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000696 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000697
698 All updated files will be appended to file_list.
699
700 Raises:
701 Error: if can't get URL for relative path.
702 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000703 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000704 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000705 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000706 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000707 return
708
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000709 hg_path = os.path.join(self.checkout_path, '.hg')
710 if os.path.exists(hg_path):
711 print('________ found .hg directory; skipping %s' % self.relpath)
712 return
713
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000714 if args:
715 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
716
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000717 # revision is the revision to match. It is None if no revision is specified,
718 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000719 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000720 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000721 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000722 if options.revision:
723 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000724 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000725 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000726 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000727 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000728 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000729 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000730 else:
731 forced_revision = False
732 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000733
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000734 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000735 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000736 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000737 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000738 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000739 return
740
741 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000742 try:
743 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
744 except gclient_utils.Error:
745 raise gclient_utils.Error(
746 ('Can\'t update/checkout %s if an unversioned directory is present. '
747 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000748
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000749 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000750 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
751 if [True for d in dir_info
752 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000753 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000754 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000755
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000756 # Retrieve the current HEAD version because svn is slow at null updates.
757 if options.manually_grab_svn_rev and not revision:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000758 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000759 revision = str(from_info_live['Revision'])
760 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000761
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000762 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000763 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000764 try:
765 to_info = scm.SVN.CaptureInfo(url)
766 except gclient_utils.Error:
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000767 # The url is invalid or the server is not accessible, it's safer to bail
768 # out right now.
769 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000770 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
771 and (from_info['UUID'] == to_info['UUID']))
772 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000773 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000774 # We have different roots, so check if we can switch --relocate.
775 # Subversion only permits this if the repository UUIDs match.
776 # Perform the switch --relocate, then rewrite the from_url
777 # to reflect where we "are now." (This is the same way that
778 # Subversion itself handles the metadata when switch --relocate
779 # is used.) This makes the checks below for whether we
780 # can update to a revision or have to switch to a different
781 # branch work as expected.
782 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000783 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000784 from_info['Repository Root'],
785 to_info['Repository Root'],
786 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000787 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000788 from_info['URL'] = from_info['URL'].replace(
789 from_info['Repository Root'],
790 to_info['Repository Root'])
791 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000792 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000793 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000794 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000795 if status[0] != '?':
796 raise gclient_utils.Error(
797 ('Can\'t switch the checkout to %s; UUID don\'t match and '
798 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000799 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000800 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000801 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000802 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000803 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000804 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000805 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000806 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000807 return
808
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000809 # If the provided url has a revision number that matches the revision
810 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000811 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000812 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000813 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000814 return
815
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000816 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000817 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000818 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000819
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000820 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000821 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000822 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000823 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000824 # Create an empty checkout and then update the one file we want. Future
825 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000826 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000827 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000828 if os.path.exists(os.path.join(self.checkout_path, filename)):
829 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000830 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000831 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000832 # After the initial checkout, we can use update as if it were any other
833 # dep.
834 self.update(options, args, file_list)
835 else:
836 # If the installed version of SVN doesn't support --depth, fallback to
837 # just exporting the file. This has the downside that revision
838 # information is not stored next to the file, so we will have to
839 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000840 if not os.path.exists(self.checkout_path):
841 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000842 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000843 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000844 command = self._AddAdditionalUpdateFlags(command, options,
845 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000846 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000847
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000848 def revert(self, options, args, file_list):
849 """Reverts local modifications. Subversion specific.
850
851 All reverted files will be appended to file_list, even if Subversion
852 doesn't know about them.
853 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000854 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000855 # svn revert won't work if the directory doesn't exist. It needs to
856 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000857 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000858 # Don't reuse the args.
859 return self.update(options, [], file_list)
860
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000861 def printcb(file_status):
862 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000863 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000864 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000865 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000866 print(os.path.join(self.checkout_path, file_status[1]))
867 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000868
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000869 try:
870 # svn revert is so broken we don't even use it. Using
871 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000872 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000873 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
874 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000875 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000876 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000877 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000878
msb@chromium.org0f282062009-11-06 20:14:02 +0000879 def revinfo(self, options, args, file_list):
880 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000881 try:
882 return scm.SVN.CaptureRevision(self.checkout_path)
883 except gclient_utils.Error:
884 return None
msb@chromium.org0f282062009-11-06 20:14:02 +0000885
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000886 def runhooks(self, options, args, file_list):
887 self.status(options, args, file_list)
888
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000889 def status(self, options, args, file_list):
890 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000891 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000892 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000893 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000894 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
895 'The directory does not exist.') %
896 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000897 # There's no file list to retrieve.
898 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000899 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000900
901 def FullUrlForRelativeUrl(self, url):
902 # Find the forth '/' and strip from there. A bit hackish.
903 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000904
maruel@chromium.org669600d2010-09-01 19:06:31 +0000905 def _Run(self, args, options, **kwargs):
906 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000907 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000908 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000909 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000910
911 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
912 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000913 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +0000914 scm.SVN.RunAndGetFileList(
915 options.verbose,
916 args + ['--ignore-externals'],
917 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000918 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000919
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000920 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000921 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000922 """Add additional flags to command depending on what options are set.
923 command should be a list of strings that represents an svn command.
924
925 This method returns a new list to be used as a command."""
926 new_command = command[:]
927 if revision:
928 new_command.extend(['--revision', str(revision).strip()])
929 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000930 if ((options.force or options.manually_grab_svn_rev) and
931 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000932 new_command.append('--force')
933 return new_command