blob: b5e88617367623b7e5fdea5d220ac1fbdebd3550 [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)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000201 files = self._Capture(['ls-files']).split()
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
msb@chromium.org5bde4852009-12-14 16:47:12 +0000217 cur_branch = self._GetCurrentBranch()
218
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000219 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000220 # 0) HEAD is detached. Probably from our initial clone.
221 # - make sure HEAD is contained by a named ref, then update.
222 # Cases 1-4. HEAD is a branch.
223 # 1) current branch is not tracking a remote branch (could be git-svn)
224 # - try to rebase onto the new hash or branch
225 # 2) current branch is tracking a remote branch with local committed
226 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000227 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000228 # 3) current branch is tracking a remote branch w/or w/out changes,
229 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000230 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000231 # 4) current branch is tracking a remote branch, switches to a different
232 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000233 # - exit
234
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000235 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
236 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000237 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
238 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000239 if cur_branch is None:
240 upstream_branch = None
241 current_type = "detached"
242 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000243 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000244 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
245 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
246 current_type = "hash"
247 logging.debug("Current branch is not tracking an upstream (remote)"
248 " branch.")
249 elif upstream_branch.startswith('refs/remotes'):
250 current_type = "branch"
251 else:
252 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000253
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000254 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000255 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000256 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000257 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000258 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000259 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000260 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000261 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000262 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000263 # Hackish but at that point, git is known to work so just checking for
264 # 502 in stderr should be fine.
265 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000266 print(str(e))
267 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000268 time.sleep(backoff_time)
269 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000270 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000271 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000272
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000273 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000274 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000275
276 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000277 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000278 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000279
msb@chromium.org786fb682010-06-02 15:16:23 +0000280 if current_type == 'detached':
281 # case 0
282 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000283 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000284 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000285 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000286 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000287 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000288 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000289 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000290 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000291 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000292 newbase=revision, printed_path=printed_path)
293 printed_path = True
294 else:
295 # Can't find a merge-base since we don't know our upstream. That makes
296 # this command VERY likely to produce a rebase failure. For now we
297 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000298 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000299 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000300 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000301 self._AttemptRebase(upstream_branch, files, options,
302 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000303 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000304 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000305 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000306 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000307 newbase=revision, printed_path=printed_path)
308 printed_path = True
309 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
310 # case 4
311 new_base = revision.replace('heads', 'remotes/origin')
312 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000313 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000314 switch_error = ("Switching upstream branch from %s to %s\n"
315 % (upstream_branch, new_base) +
316 "Please merge or rebase manually:\n" +
317 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
318 "OR git checkout -b <some new branch> %s" % new_base)
319 raise gclient_utils.Error(switch_error)
320 else:
321 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000322 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000323 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000324 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000325 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000326 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
327 cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000328 except gclient_utils.CheckCallError, e:
329 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
330 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000331 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000332 printed_path = True
333 while True:
334 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000335 # TODO(maruel): That can't work with --jobs.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000336 action = str(raw_input("Cannot fast-forward merge, attempt to "
337 "rebase? (y)es / (q)uit / (s)kip : "))
338 except ValueError:
339 gclient_utils.Error('Invalid Character')
340 continue
341 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000342 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000343 printed_path=printed_path)
344 printed_path = True
345 break
346 elif re.match(r'quit|q', action, re.I):
347 raise gclient_utils.Error("Can't fast-forward, please merge or "
348 "rebase manually.\n"
349 "cd %s && git " % self.checkout_path
350 + "rebase %s" % upstream_branch)
351 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000352 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000353 return
354 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000355 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000356 elif re.match("error: Your local changes to '.*' would be "
357 "overwritten by merge. Aborting.\nPlease, commit your "
358 "changes or stash them before you can merge.\n",
359 e.stderr):
360 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000361 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000362 printed_path = True
363 raise gclient_utils.Error(e.stderr)
364 else:
365 # Some other problem happened with the merge
366 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000367 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000368 raise
369 else:
370 # Fast-forward merge was successful
371 if not re.match('Already up-to-date.', merge_output) or verbose:
372 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000373 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000374 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000375 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000376 if not verbose:
377 # Make the output a little prettier. It's nice to have some
378 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000379 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000380
381 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000382
383 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000384 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000385 raise gclient_utils.Error('\n____ %s%s\n'
386 '\nConflict while rebasing this branch.\n'
387 'Fix the conflict and run gclient again.\n'
388 'See man git-rebase for details.\n'
389 % (self.relpath, rev_str))
390
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000391 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000392 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000393
394 def revert(self, options, args, file_list):
395 """Reverts local modifications.
396
397 All reverted files will be appended to file_list.
398 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000399 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000400 # revert won't work if the directory doesn't exist. It needs to
401 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000402 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000403 # Don't reuse the args.
404 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000405
406 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000407 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000408 if not deps_revision:
409 deps_revision = default_rev
410 if deps_revision.startswith('refs/heads/'):
411 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
412
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000413 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000414 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000415 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
416
msb@chromium.org0f282062009-11-06 20:14:02 +0000417 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000418 """Returns revision"""
419 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000420
msb@chromium.orge28e4982009-09-25 20:51:45 +0000421 def runhooks(self, options, args, file_list):
422 self.status(options, args, file_list)
423
424 def status(self, options, args, file_list):
425 """Display status information."""
426 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000427 print(('\n________ couldn\'t run status in %s:\n'
428 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000429 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000430 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000431 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000432 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000433 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
434
msb@chromium.orge6f78352010-01-13 17:05:33 +0000435 def FullUrlForRelativeUrl(self, url):
436 # Strip from last '/'
437 # Equivalent to unix basename
438 base_url = self.url
439 return base_url[:base_url.rfind('/')] + url
440
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000441 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000442 """Clone a git repository from the given URL.
443
msb@chromium.org786fb682010-06-02 15:16:23 +0000444 Once we've cloned the repo, we checkout a working branch if the specified
445 revision is a branch head. If it is a tag or a specific commit, then we
446 leave HEAD detached as it makes future updates simpler -- in this case the
447 user should first create a new branch or switch to an existing branch before
448 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000449 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000450 # git clone doesn't seem to insert a newline properly before printing
451 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000452 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000453
454 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000455 if revision.startswith('refs/heads/'):
456 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
457 detach_head = False
458 else:
459 clone_cmd.append('--no-checkout')
460 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000461 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000462 clone_cmd.append('--verbose')
463 clone_cmd.extend([url, self.checkout_path])
464
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000465 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000466 try:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000467 self._Run(clone_cmd, options, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000468 break
469 except gclient_utils.Error, e:
470 # TODO(maruel): Hackish, should be fixed by moving _Run() to
471 # CheckCall().
472 # Too bad we don't have access to the actual output.
473 # We should check for "transfer closed with NNN bytes remaining to
474 # read". In the meantime, just make sure .git exists.
475 if (e.args[0] == 'git command clone returned 128' and
476 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000477 print(str(e))
478 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000479 continue
480 raise e
481
msb@chromium.org786fb682010-06-02 15:16:23 +0000482 if detach_head:
483 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000484 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000485 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000486 ('Checked out %s to a detached HEAD. Before making any commits\n'
487 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
488 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
489 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000490
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000491 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000492 branch=None, printed_path=False):
493 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000494 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000495 revision = upstream
496 if newbase:
497 revision = newbase
498 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000499 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000500 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000501 printed_path = True
502 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000503 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000504
505 # Build the rebase command here using the args
506 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
507 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000508 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000509 rebase_cmd.append('--verbose')
510 if newbase:
511 rebase_cmd.extend(['--onto', newbase])
512 rebase_cmd.append(upstream)
513 if branch:
514 rebase_cmd.append(branch)
515
516 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000517 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000518 except gclient_utils.CheckCallError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000519 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
520 re.match(r'cannot rebase: your index contains uncommitted changes',
521 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000522 while True:
523 rebase_action = str(raw_input("Cannot rebase because of unstaged "
524 "changes.\n'git reset --hard HEAD' ?\n"
525 "WARNING: destroys any uncommitted "
526 "work in your current branch!"
527 " (y)es / (q)uit / (s)how : "))
528 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000529 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000530 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000531 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000532 break
533 elif re.match(r'quit|q', rebase_action, re.I):
534 raise gclient_utils.Error("Please merge or rebase manually\n"
535 "cd %s && git " % self.checkout_path
536 + "%s" % ' '.join(rebase_cmd))
537 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000538 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000539 continue
540 else:
541 gclient_utils.Error("Input not recognized")
542 continue
543 elif re.search(r'^CONFLICT', e.stdout, re.M):
544 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
545 "Fix the conflict and run gclient again.\n"
546 "See 'man git-rebase' for details.\n")
547 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000548 print(e.stdout.strip())
549 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000550 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
551 "manually.\ncd %s && git " %
552 self.checkout_path
553 + "%s" % ' '.join(rebase_cmd))
554
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000555 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000556 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000557 # Make the output a little prettier. It's nice to have some
558 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000559 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000560
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000561 @staticmethod
562 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000563 (ok, current_version) = scm.GIT.AssertVersion(min_version)
564 if not ok:
565 raise gclient_utils.Error('git version %s < minimum required %s' %
566 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000567
msb@chromium.org786fb682010-06-02 15:16:23 +0000568 def _IsRebasing(self):
569 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
570 # have a plumbing command to determine whether a rebase is in progress, so
571 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
572 g = os.path.join(self.checkout_path, '.git')
573 return (
574 os.path.isdir(os.path.join(g, "rebase-merge")) or
575 os.path.isdir(os.path.join(g, "rebase-apply")))
576
577 def _CheckClean(self, rev_str):
578 # Make sure the tree is clean; see git-rebase.sh for reference
579 try:
580 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000581 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000582 except gclient_utils.CheckCallError:
583 raise gclient_utils.Error('\n____ %s%s\n'
584 '\tYou have unstaged changes.\n'
585 '\tPlease commit, stash, or reset.\n'
586 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000587 try:
588 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000589 '--ignore-submodules', 'HEAD', '--'],
590 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000591 except gclient_utils.CheckCallError:
592 raise gclient_utils.Error('\n____ %s%s\n'
593 '\tYour index contains uncommitted changes\n'
594 '\tPlease commit, stash, or reset.\n'
595 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000596
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000597 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000598 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
599 # reference by a commit). If not, error out -- most likely a rebase is
600 # in progress, try to detect so we can give a better error.
601 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000602 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
603 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000604 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000605 # Commit is not contained by any rev. See if the user is rebasing:
606 if self._IsRebasing():
607 # Punt to the user
608 raise gclient_utils.Error('\n____ %s%s\n'
609 '\tAlready in a conflict, i.e. (no branch).\n'
610 '\tFix the conflict and run gclient again.\n'
611 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
612 '\tSee man git-rebase for details.\n'
613 % (self.relpath, rev_str))
614 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000615 name = ('saved-by-gclient-' +
616 self._Capture(['rev-parse', '--short', 'HEAD']))
617 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000618 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000619 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000620
msb@chromium.org5bde4852009-12-14 16:47:12 +0000621 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000622 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000623 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000624 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000625 return None
626 return branch
627
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000628 def _Capture(self, args):
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000629 return gclient_utils.CheckCall(
630 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000631
maruel@chromium.org37e89872010-09-07 16:11:33 +0000632 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000633 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000634 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000635 always=options.verbose, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000636
637
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000638class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000639 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000640
641 def cleanup(self, options, args, file_list):
642 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000643 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000644
645 def diff(self, options, args, file_list):
646 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000647 if not os.path.isdir(self.checkout_path):
648 raise gclient_utils.Error('Directory %s is not present.' %
649 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000650 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000651
652 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000653 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000654 assert len(args) == 1
655 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
656 try:
657 os.makedirs(export_path)
658 except OSError:
659 pass
660 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000661 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000662
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000663 def pack(self, options, args, file_list):
664 """Generates a patch file which can be applied to the root of the
665 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000666 if not os.path.isdir(self.checkout_path):
667 raise gclient_utils.Error('Directory %s is not present.' %
668 self.checkout_path)
669 gclient_utils.CheckCallAndFilter(
670 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
671 cwd=self.checkout_path,
672 print_stdout=False,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000673 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000674
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000675 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000676 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000677
678 All updated files will be appended to file_list.
679
680 Raises:
681 Error: if can't get URL for relative path.
682 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000683 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000684 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000685 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000686 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000687 return
688
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000689 hg_path = os.path.join(self.checkout_path, '.hg')
690 if os.path.exists(hg_path):
691 print('________ found .hg directory; skipping %s' % self.relpath)
692 return
693
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000694 if args:
695 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
696
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000697 # revision is the revision to match. It is None if no revision is specified,
698 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000699 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000700 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000701 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000702 if options.revision:
703 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000704 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000705 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000706 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000707 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000708 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000709 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000710 else:
711 forced_revision = False
712 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000713
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000714 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000715 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000716 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000717 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000718 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000719 return
720
721 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000722 try:
723 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
724 except gclient_utils.Error:
725 raise gclient_utils.Error(
726 ('Can\'t update/checkout %s if an unversioned directory is present. '
727 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000728
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000729 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000730 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
731 if [True for d in dir_info
732 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000733 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000734 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000735
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000736 # Retrieve the current HEAD version because svn is slow at null updates.
737 if options.manually_grab_svn_rev and not revision:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000738 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000739 revision = str(from_info_live['Revision'])
740 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000741
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000742 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000743 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000744 try:
745 to_info = scm.SVN.CaptureInfo(url)
746 except gclient_utils.Error:
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000747 # The url is invalid or the server is not accessible, it's safer to bail
748 # out right now.
749 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000750 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
751 and (from_info['UUID'] == to_info['UUID']))
752 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000753 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000754 # We have different roots, so check if we can switch --relocate.
755 # Subversion only permits this if the repository UUIDs match.
756 # Perform the switch --relocate, then rewrite the from_url
757 # to reflect where we "are now." (This is the same way that
758 # Subversion itself handles the metadata when switch --relocate
759 # is used.) This makes the checks below for whether we
760 # can update to a revision or have to switch to a different
761 # branch work as expected.
762 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000763 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000764 from_info['Repository Root'],
765 to_info['Repository Root'],
766 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000767 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000768 from_info['URL'] = from_info['URL'].replace(
769 from_info['Repository Root'],
770 to_info['Repository Root'])
771 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000772 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000773 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000774 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000775 if status[0] != '?':
776 raise gclient_utils.Error(
777 ('Can\'t switch the checkout to %s; UUID don\'t match and '
778 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000779 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000780 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000781 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000782 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000783 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000784 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000785 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000786 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000787 return
788
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000789 # If the provided url has a revision number that matches the revision
790 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000791 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000792 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000793 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000794 return
795
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000796 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000797 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000798 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000799
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000800 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000801 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000802 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000803 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000804 # Create an empty checkout and then update the one file we want. Future
805 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000806 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000807 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000808 if os.path.exists(os.path.join(self.checkout_path, filename)):
809 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000810 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000811 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000812 # After the initial checkout, we can use update as if it were any other
813 # dep.
814 self.update(options, args, file_list)
815 else:
816 # If the installed version of SVN doesn't support --depth, fallback to
817 # just exporting the file. This has the downside that revision
818 # information is not stored next to the file, so we will have to
819 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000820 if not os.path.exists(self.checkout_path):
821 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000822 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000823 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000824 command = self._AddAdditionalUpdateFlags(command, options,
825 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000826 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000827
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000828 def revert(self, options, args, file_list):
829 """Reverts local modifications. Subversion specific.
830
831 All reverted files will be appended to file_list, even if Subversion
832 doesn't know about them.
833 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000834 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000835 # svn revert won't work if the directory doesn't exist. It needs to
836 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000837 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000838 # Don't reuse the args.
839 return self.update(options, [], file_list)
840
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000841 for file_status in scm.SVN.CaptureStatus(self.checkout_path):
842 file_path = os.path.join(self.checkout_path, file_status[1])
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000843 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000844 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000845 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000846 continue
847
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000848 if logging.getLogger().isEnabledFor(logging.INFO):
849 logging.info('%s%s' % (file[0], file[1]))
850 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000851 print(file_path)
maruel@chromium.org945405e2010-08-18 17:01:49 +0000852
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000853 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000854 logging.error('No idea what is the status of %s.\n'
855 'You just found a bug in gclient, please ping '
856 'maruel@chromium.org ASAP!' % file_path)
857 # svn revert is really stupid. It fails on inconsistent line-endings,
858 # on switched directories, etc. So take no chance and delete everything!
859 try:
860 if not os.path.exists(file_path):
861 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000862 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000863 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000864 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000865 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000866 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000867 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000868 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000869 logging.error('no idea what is %s.\nYou just found a bug in gclient'
870 ', please ping maruel@chromium.org ASAP!' % file_path)
871 except EnvironmentError:
872 logging.error('Failed to remove %s.' % file_path)
873
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000874 try:
875 # svn revert is so broken we don't even use it. Using
876 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000877 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
878 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000879 except OSError, e:
880 # Maybe the directory disapeared meanwhile. We don't want it to throw an
881 # exception.
882 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000883
msb@chromium.org0f282062009-11-06 20:14:02 +0000884 def revinfo(self, options, args, file_list):
885 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000886 try:
887 return scm.SVN.CaptureRevision(self.checkout_path)
888 except gclient_utils.Error:
889 return None
msb@chromium.org0f282062009-11-06 20:14:02 +0000890
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000891 def runhooks(self, options, args, file_list):
892 self.status(options, args, file_list)
893
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000894 def status(self, options, args, file_list):
895 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000896 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000897 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000898 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000899 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
900 'The directory does not exist.') %
901 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000902 # There's no file list to retrieve.
903 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000904 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000905
906 def FullUrlForRelativeUrl(self, url):
907 # Find the forth '/' and strip from there. A bit hackish.
908 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000909
maruel@chromium.org669600d2010-09-01 19:06:31 +0000910 def _Run(self, args, options, **kwargs):
911 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000912 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000913 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000914 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000915
916 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
917 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000918 cwd = cwd or self.checkout_path
maruel@chromium.org669600d2010-09-01 19:06:31 +0000919 scm.SVN.RunAndGetFileList(options.verbose, args, cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000920 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000921
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000922 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000923 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000924 """Add additional flags to command depending on what options are set.
925 command should be a list of strings that represents an svn command.
926
927 This method returns a new list to be used as a command."""
928 new_command = command[:]
929 if revision:
930 new_command.extend(['--revision', str(revision).strip()])
931 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000932 if ((options.force or options.manually_grab_svn_rev) and
933 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000934 new_command.append('--force')
935 return new_command