blob: bd4eb731ed5a33d48cad79779d2909e113c0588a [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.org668667c2011-03-24 18:27:24 +0000217 # See if the url has changed
218 current_url = self._Capture(['config', 'remote.origin.url'])
219 if current_url != url:
220 print('_____ switching %s to a new upstream' % self.relpath)
221 # Make sure it's clean
222 self._CheckClean(rev_str)
223 # Switch over to the new upstream
224 self._Run(['remote', 'set-url', 'origin', url], options)
225 quiet = []
226 if not options.verbose:
227 quiet = ['--quiet']
228 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
229 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
230 files = self._Capture(['ls-files']).splitlines()
231 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
232 return
233
msb@chromium.org5bde4852009-12-14 16:47:12 +0000234 cur_branch = self._GetCurrentBranch()
235
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000236 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000237 # 0) HEAD is detached. Probably from our initial clone.
238 # - make sure HEAD is contained by a named ref, then update.
239 # Cases 1-4. HEAD is a branch.
240 # 1) current branch is not tracking a remote branch (could be git-svn)
241 # - try to rebase onto the new hash or branch
242 # 2) current branch is tracking a remote branch with local committed
243 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000244 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000245 # 3) current branch is tracking a remote branch w/or w/out changes,
246 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000247 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000248 # 4) current branch is tracking a remote branch, switches to a different
249 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000250 # - exit
251
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000252 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
253 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000254 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
255 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000256 if cur_branch is None:
257 upstream_branch = None
258 current_type = "detached"
259 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000260 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000261 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
262 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
263 current_type = "hash"
264 logging.debug("Current branch is not tracking an upstream (remote)"
265 " branch.")
266 elif upstream_branch.startswith('refs/remotes'):
267 current_type = "branch"
268 else:
269 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000270
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000271 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000272 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000273 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000274 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000275 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000276 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000277 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000278 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000279 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000280 # Hackish but at that point, git is known to work so just checking for
281 # 502 in stderr should be fine.
282 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000283 print(str(e))
284 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000285 time.sleep(backoff_time)
286 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000287 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000288 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000289
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000290 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000291 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000292
293 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000294 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000295 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000296
msb@chromium.org786fb682010-06-02 15:16:23 +0000297 if current_type == 'detached':
298 # case 0
299 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000300 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000301 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000302 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000303 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000304 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000305 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000306 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000307 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000308 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000309 newbase=revision, printed_path=printed_path)
310 printed_path = True
311 else:
312 # Can't find a merge-base since we don't know our upstream. That makes
313 # this command VERY likely to produce a rebase failure. For now we
314 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000315 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000316 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000317 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000318 self._AttemptRebase(upstream_branch, files, options,
319 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000320 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000321 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000322 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000323 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000324 newbase=revision, printed_path=printed_path)
325 printed_path = True
326 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
327 # case 4
328 new_base = revision.replace('heads', 'remotes/origin')
329 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000330 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000331 switch_error = ("Switching upstream branch from %s to %s\n"
332 % (upstream_branch, new_base) +
333 "Please merge or rebase manually:\n" +
334 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
335 "OR git checkout -b <some new branch> %s" % new_base)
336 raise gclient_utils.Error(switch_error)
337 else:
338 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000339 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000340 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000341 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000342 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000343 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
344 cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000345 except gclient_utils.CheckCallError, e:
346 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
347 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000348 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000349 printed_path = True
350 while True:
351 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000352 # TODO(maruel): That can't work with --jobs.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000353 action = str(raw_input("Cannot fast-forward merge, attempt to "
354 "rebase? (y)es / (q)uit / (s)kip : "))
355 except ValueError:
356 gclient_utils.Error('Invalid Character')
357 continue
358 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000359 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000360 printed_path=printed_path)
361 printed_path = True
362 break
363 elif re.match(r'quit|q', action, re.I):
364 raise gclient_utils.Error("Can't fast-forward, please merge or "
365 "rebase manually.\n"
366 "cd %s && git " % self.checkout_path
367 + "rebase %s" % upstream_branch)
368 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000369 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000370 return
371 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000372 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000373 elif re.match("error: Your local changes to '.*' would be "
374 "overwritten by merge. Aborting.\nPlease, commit your "
375 "changes or stash them before you can merge.\n",
376 e.stderr):
377 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000378 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000379 printed_path = True
380 raise gclient_utils.Error(e.stderr)
381 else:
382 # Some other problem happened with the merge
383 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000384 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000385 raise
386 else:
387 # Fast-forward merge was successful
388 if not re.match('Already up-to-date.', merge_output) or verbose:
389 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000390 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000391 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000392 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000393 if not verbose:
394 # Make the output a little prettier. It's nice to have some
395 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000396 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000397
398 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000399
400 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000401 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000402 raise gclient_utils.Error('\n____ %s%s\n'
403 '\nConflict while rebasing this branch.\n'
404 'Fix the conflict and run gclient again.\n'
405 'See man git-rebase for details.\n'
406 % (self.relpath, rev_str))
407
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000408 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000409 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000410
411 def revert(self, options, args, file_list):
412 """Reverts local modifications.
413
414 All reverted files will be appended to file_list.
415 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000416 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000417 # revert won't work if the directory doesn't exist. It needs to
418 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000419 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000420 # Don't reuse the args.
421 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000422
423 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000424 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000425 if not deps_revision:
426 deps_revision = default_rev
427 if deps_revision.startswith('refs/heads/'):
428 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
429
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000430 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000431 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000432 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
433
msb@chromium.org0f282062009-11-06 20:14:02 +0000434 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000435 """Returns revision"""
436 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000437
msb@chromium.orge28e4982009-09-25 20:51:45 +0000438 def runhooks(self, options, args, file_list):
439 self.status(options, args, file_list)
440
441 def status(self, options, args, file_list):
442 """Display status information."""
443 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000444 print(('\n________ couldn\'t run status in %s:\n'
445 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000446 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000447 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000448 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000449 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000450 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
451
msb@chromium.orge6f78352010-01-13 17:05:33 +0000452 def FullUrlForRelativeUrl(self, url):
453 # Strip from last '/'
454 # Equivalent to unix basename
455 base_url = self.url
456 return base_url[:base_url.rfind('/')] + url
457
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000458 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000459 """Clone a git repository from the given URL.
460
msb@chromium.org786fb682010-06-02 15:16:23 +0000461 Once we've cloned the repo, we checkout a working branch if the specified
462 revision is a branch head. If it is a tag or a specific commit, then we
463 leave HEAD detached as it makes future updates simpler -- in this case the
464 user should first create a new branch or switch to an existing branch before
465 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000466 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000467 # git clone doesn't seem to insert a newline properly before printing
468 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000469 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470
471 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000472 if revision.startswith('refs/heads/'):
473 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
474 detach_head = False
475 else:
476 clone_cmd.append('--no-checkout')
477 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000478 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000479 clone_cmd.append('--verbose')
480 clone_cmd.extend([url, self.checkout_path])
481
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000482 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 try:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000484 self._Run(clone_cmd, options, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000485 break
486 except gclient_utils.Error, e:
487 # TODO(maruel): Hackish, should be fixed by moving _Run() to
488 # CheckCall().
489 # Too bad we don't have access to the actual output.
490 # We should check for "transfer closed with NNN bytes remaining to
491 # read". In the meantime, just make sure .git exists.
492 if (e.args[0] == 'git command clone returned 128' and
493 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000494 print(str(e))
495 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000496 continue
497 raise e
498
msb@chromium.org786fb682010-06-02 15:16:23 +0000499 if detach_head:
500 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000501 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000502 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000503 ('Checked out %s to a detached HEAD. Before making any commits\n'
504 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
505 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
506 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000507
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000508 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000509 branch=None, printed_path=False):
510 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000511 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000512 revision = upstream
513 if newbase:
514 revision = newbase
515 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000516 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000517 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000518 printed_path = True
519 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000520 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000521
522 # Build the rebase command here using the args
523 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
524 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000525 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000526 rebase_cmd.append('--verbose')
527 if newbase:
528 rebase_cmd.extend(['--onto', newbase])
529 rebase_cmd.append(upstream)
530 if branch:
531 rebase_cmd.append(branch)
532
533 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000534 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000535 except gclient_utils.CheckCallError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000536 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
537 re.match(r'cannot rebase: your index contains uncommitted changes',
538 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000539 while True:
540 rebase_action = str(raw_input("Cannot rebase because of unstaged "
541 "changes.\n'git reset --hard HEAD' ?\n"
542 "WARNING: destroys any uncommitted "
543 "work in your current branch!"
544 " (y)es / (q)uit / (s)how : "))
545 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000546 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000547 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000548 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000549 break
550 elif re.match(r'quit|q', rebase_action, re.I):
551 raise gclient_utils.Error("Please merge or rebase manually\n"
552 "cd %s && git " % self.checkout_path
553 + "%s" % ' '.join(rebase_cmd))
554 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000555 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000556 continue
557 else:
558 gclient_utils.Error("Input not recognized")
559 continue
560 elif re.search(r'^CONFLICT', e.stdout, re.M):
561 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
562 "Fix the conflict and run gclient again.\n"
563 "See 'man git-rebase' for details.\n")
564 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000565 print(e.stdout.strip())
566 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000567 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
568 "manually.\ncd %s && git " %
569 self.checkout_path
570 + "%s" % ' '.join(rebase_cmd))
571
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000572 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000573 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000574 # Make the output a little prettier. It's nice to have some
575 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000576 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000577
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000578 @staticmethod
579 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000580 (ok, current_version) = scm.GIT.AssertVersion(min_version)
581 if not ok:
582 raise gclient_utils.Error('git version %s < minimum required %s' %
583 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000584
msb@chromium.org786fb682010-06-02 15:16:23 +0000585 def _IsRebasing(self):
586 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
587 # have a plumbing command to determine whether a rebase is in progress, so
588 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
589 g = os.path.join(self.checkout_path, '.git')
590 return (
591 os.path.isdir(os.path.join(g, "rebase-merge")) or
592 os.path.isdir(os.path.join(g, "rebase-apply")))
593
594 def _CheckClean(self, rev_str):
595 # Make sure the tree is clean; see git-rebase.sh for reference
596 try:
597 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000598 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000599 except gclient_utils.CheckCallError:
600 raise gclient_utils.Error('\n____ %s%s\n'
601 '\tYou have unstaged changes.\n'
602 '\tPlease commit, stash, or reset.\n'
603 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000604 try:
605 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000606 '--ignore-submodules', 'HEAD', '--'],
607 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000608 except gclient_utils.CheckCallError:
609 raise gclient_utils.Error('\n____ %s%s\n'
610 '\tYour index contains uncommitted changes\n'
611 '\tPlease commit, stash, or reset.\n'
612 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000613
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000614 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000615 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
616 # reference by a commit). If not, error out -- most likely a rebase is
617 # in progress, try to detect so we can give a better error.
618 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000619 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
620 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000621 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000622 # Commit is not contained by any rev. See if the user is rebasing:
623 if self._IsRebasing():
624 # Punt to the user
625 raise gclient_utils.Error('\n____ %s%s\n'
626 '\tAlready in a conflict, i.e. (no branch).\n'
627 '\tFix the conflict and run gclient again.\n'
628 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
629 '\tSee man git-rebase for details.\n'
630 % (self.relpath, rev_str))
631 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000632 name = ('saved-by-gclient-' +
633 self._Capture(['rev-parse', '--short', 'HEAD']))
634 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000635 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000636 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000637
msb@chromium.org5bde4852009-12-14 16:47:12 +0000638 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000639 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000640 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000641 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000642 return None
643 return branch
644
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000645 def _Capture(self, args):
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000646 return gclient_utils.CheckCall(
647 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000648
maruel@chromium.org37e89872010-09-07 16:11:33 +0000649 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000650 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000651 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000652 always=options.verbose, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000653
654
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000655class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000656 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000657
658 def cleanup(self, options, args, file_list):
659 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000660 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000661
662 def diff(self, options, args, file_list):
663 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000664 if not os.path.isdir(self.checkout_path):
665 raise gclient_utils.Error('Directory %s is not present.' %
666 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000667 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000668
669 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000670 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000671 assert len(args) == 1
672 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
673 try:
674 os.makedirs(export_path)
675 except OSError:
676 pass
677 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000678 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000679
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000680 def pack(self, options, args, file_list):
681 """Generates a patch file which can be applied to the root of the
682 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000683 if not os.path.isdir(self.checkout_path):
684 raise gclient_utils.Error('Directory %s is not present.' %
685 self.checkout_path)
686 gclient_utils.CheckCallAndFilter(
687 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
688 cwd=self.checkout_path,
689 print_stdout=False,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000690 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000691
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000692 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000693 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000694
695 All updated files will be appended to file_list.
696
697 Raises:
698 Error: if can't get URL for relative path.
699 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000700 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000701 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000702 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000703 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000704 return
705
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000706 hg_path = os.path.join(self.checkout_path, '.hg')
707 if os.path.exists(hg_path):
708 print('________ found .hg directory; skipping %s' % self.relpath)
709 return
710
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000711 if args:
712 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
713
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000714 # revision is the revision to match. It is None if no revision is specified,
715 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000716 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000717 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000718 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000719 if options.revision:
720 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000721 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000722 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000723 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000724 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000725 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000726 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000727 else:
728 forced_revision = False
729 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000730
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000731 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000732 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000733 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000734 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000735 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000736 return
737
738 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000739 try:
740 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
741 except gclient_utils.Error:
742 raise gclient_utils.Error(
743 ('Can\'t update/checkout %s if an unversioned directory is present. '
744 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000745
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000746 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000747 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
748 if [True for d in dir_info
749 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000750 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000751 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000752
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000753 # Retrieve the current HEAD version because svn is slow at null updates.
754 if options.manually_grab_svn_rev and not revision:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000755 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000756 revision = str(from_info_live['Revision'])
757 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000758
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000759 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000760 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000761 try:
762 to_info = scm.SVN.CaptureInfo(url)
763 except gclient_utils.Error:
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000764 # The url is invalid or the server is not accessible, it's safer to bail
765 # out right now.
766 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000767 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
768 and (from_info['UUID'] == to_info['UUID']))
769 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000770 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000771 # We have different roots, so check if we can switch --relocate.
772 # Subversion only permits this if the repository UUIDs match.
773 # Perform the switch --relocate, then rewrite the from_url
774 # to reflect where we "are now." (This is the same way that
775 # Subversion itself handles the metadata when switch --relocate
776 # is used.) This makes the checks below for whether we
777 # can update to a revision or have to switch to a different
778 # branch work as expected.
779 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000780 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000781 from_info['Repository Root'],
782 to_info['Repository Root'],
783 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000784 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000785 from_info['URL'] = from_info['URL'].replace(
786 from_info['Repository Root'],
787 to_info['Repository Root'])
788 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000789 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000790 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000791 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000792 if status[0] != '?':
793 raise gclient_utils.Error(
794 ('Can\'t switch the checkout to %s; UUID don\'t match and '
795 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000796 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000797 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000798 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000799 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000800 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000801 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000802 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000803 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000804 return
805
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000806 # If the provided url has a revision number that matches the revision
807 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000808 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000809 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000810 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000811 return
812
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000813 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000814 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000815 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000816
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000817 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000818 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000819 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000820 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000821 # Create an empty checkout and then update the one file we want. Future
822 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000823 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000824 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000825 if os.path.exists(os.path.join(self.checkout_path, filename)):
826 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000827 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000828 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000829 # After the initial checkout, we can use update as if it were any other
830 # dep.
831 self.update(options, args, file_list)
832 else:
833 # If the installed version of SVN doesn't support --depth, fallback to
834 # just exporting the file. This has the downside that revision
835 # information is not stored next to the file, so we will have to
836 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000837 if not os.path.exists(self.checkout_path):
838 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000839 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000840 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000841 command = self._AddAdditionalUpdateFlags(command, options,
842 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000843 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000844
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000845 def revert(self, options, args, file_list):
846 """Reverts local modifications. Subversion specific.
847
848 All reverted files will be appended to file_list, even if Subversion
849 doesn't know about them.
850 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000851 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000852 # svn revert won't work if the directory doesn't exist. It needs to
853 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000854 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000855 # Don't reuse the args.
856 return self.update(options, [], file_list)
857
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000858 def printcb(file_status):
859 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000860 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000861 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000862 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000863 print(os.path.join(self.checkout_path, file_status[1]))
864 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000865
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000866 try:
867 # svn revert is so broken we don't even use it. Using
868 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000869 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000870 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
871 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000872 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000873 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000874 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000875
msb@chromium.org0f282062009-11-06 20:14:02 +0000876 def revinfo(self, options, args, file_list):
877 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000878 try:
879 return scm.SVN.CaptureRevision(self.checkout_path)
880 except gclient_utils.Error:
881 return None
msb@chromium.org0f282062009-11-06 20:14:02 +0000882
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000883 def runhooks(self, options, args, file_list):
884 self.status(options, args, file_list)
885
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000886 def status(self, options, args, file_list):
887 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000888 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000889 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000890 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000891 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
892 'The directory does not exist.') %
893 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000894 # There's no file list to retrieve.
895 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000896 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000897
898 def FullUrlForRelativeUrl(self, url):
899 # Find the forth '/' and strip from there. A bit hackish.
900 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000901
maruel@chromium.org669600d2010-09-01 19:06:31 +0000902 def _Run(self, args, options, **kwargs):
903 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000904 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000905 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000906 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000907
908 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
909 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000910 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +0000911 scm.SVN.RunAndGetFileList(
912 options.verbose,
913 args + ['--ignore-externals'],
914 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000915 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000916
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000917 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000918 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000919 """Add additional flags to command depending on what options are set.
920 command should be a list of strings that represents an svn command.
921
922 This method returns a new list to be used as a command."""
923 new_command = command[:]
924 if revision:
925 new_command.extend(['--revision', str(revision).strip()])
926 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000927 if ((options.force or options.manually_grab_svn_rev) and
928 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000929 new_command.append('--force')
930 return new_command