blob: 30e604dd7ebca84fef94e0d12f45ff2c19b0152d [file] [log] [blame]
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +00001# Copyright (c) 2010 The Chromium Authors. All rights reserved.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00004
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00005"""Gclient-specific SCM-specific operations."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00006
maruel@chromium.org754960e2009-09-21 12:31:05 +00007import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00008import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00009import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000010import re
maruel@chromium.org90541732011-04-01 17:54:18 +000011import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000012import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000014import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016
17
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000018class DiffFilterer(object):
19 """Simple class which tracks which file is being diffed and
20 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000021 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000022 index_string = "Index: "
23 original_prefix = "--- "
24 working_prefix = "+++ "
25
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000026 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000027 # Note that we always use '/' as the path separator to be
28 # consistent with svn's cygwin-style output on Windows
29 self._relpath = relpath.replace("\\", "/")
30 self._current_file = ""
31 self._replacement_file = ""
32
maruel@chromium.org6e29d572010-06-04 17:32:20 +000033 def SetCurrentFile(self, current_file):
34 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000035 # Note that we always use '/' as the path separator to be
36 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000037 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000038
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000039 def _Replace(self, line):
40 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000041
42 def Filter(self, line):
43 if (line.startswith(self.index_string)):
44 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000045 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000046 else:
47 if (line.startswith(self.original_prefix) or
48 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000049 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000050 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000051
52
maruel@chromium.org90541732011-04-01 17:54:18 +000053def ask_for_data(prompt):
54 try:
55 return raw_input(prompt)
56 except KeyboardInterrupt:
57 # Hide the exception.
58 sys.exit(1)
59
60
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000061### SCM abstraction layer
62
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000063# Factory Method for SCM wrapper creation
64
maruel@chromium.org9eda4112010-06-11 18:56:10 +000065def GetScmName(url):
66 if url:
67 url, _ = gclient_utils.SplitUrlRevision(url)
68 if (url.startswith('git://') or url.startswith('ssh://') or
69 url.endswith('.git')):
70 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000071 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000072 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000073 return 'svn'
74 return None
75
76
77def CreateSCM(url, root_dir=None, relpath=None):
78 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000079 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000080 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000081 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000082
maruel@chromium.org9eda4112010-06-11 18:56:10 +000083 scm_name = GetScmName(url)
84 if not scm_name in SCM_MAP:
85 raise gclient_utils.Error('No SCM found for url %s' % url)
86 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000087
88
89# SCMWrapper base class
90
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000091class SCMWrapper(object):
92 """Add necessary glue between all the supported SCM.
93
msb@chromium.orgd6504212010-01-13 17:34:31 +000094 This is the abstraction layer to bind to different SCM.
95 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000096 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000097 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000098 self._root_dir = root_dir
99 if self._root_dir:
100 self._root_dir = self._root_dir.replace('/', os.sep)
101 self.relpath = relpath
102 if self.relpath:
103 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000104 if self.relpath and self._root_dir:
105 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000106
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000107 def RunCommand(self, command, options, args, file_list=None):
108 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000109 if file_list is None:
110 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000111
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000112 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
113 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000114
115 if not command in commands:
116 raise gclient_utils.Error('Unknown command %s' % command)
117
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000118 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000119 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000120 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000121
122 return getattr(self, command)(options, args, file_list)
123
124
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000125class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000126 """Wrapper for Git"""
127
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000128 @staticmethod
129 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000130 """'Cleanup' the repo.
131
132 There's no real git equivalent for the svn cleanup command, do a no-op.
133 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000134
135 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000136 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000137 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000138
139 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000140 """Export a clean directory tree into the given path.
141
142 Exports into the specified directory, creating the path if it does
143 already exist.
144 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000145 assert len(args) == 1
146 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
147 if not os.path.exists(export_path):
148 os.makedirs(export_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000149 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
150 options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000151
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000152 def pack(self, options, args, file_list):
153 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000154 repository.
155
156 The patch file is generated from a diff of the merge base of HEAD and
157 its upstream branch.
158 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000159 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000160 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000161 ['git', 'diff', merge_base],
162 cwd=self.checkout_path,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000163 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000164
msb@chromium.orge28e4982009-09-25 20:51:45 +0000165 def update(self, options, args, file_list):
166 """Runs git to update or transparently checkout the working copy.
167
168 All updated files will be appended to file_list.
169
170 Raises:
171 Error: if can't get URL for relative path.
172 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000173 if args:
174 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
175
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000176 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000177
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000178 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000179 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000180 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000181 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000182 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000183 # Override the revision number.
184 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000185 if not revision:
186 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000187
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000188 rev_str = ' at %s' % revision
189 files = []
190
191 printed_path = False
192 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000193 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000194 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000195 verbose = ['--verbose']
196 printed_path = True
197
198 if revision.startswith('refs/heads/'):
199 rev_type = "branch"
200 elif revision.startswith('origin/'):
201 # For compatability with old naming, translate 'origin' to 'refs/heads'
202 revision = revision.replace('origin/', 'refs/heads/')
203 rev_type = "branch"
204 else:
205 # hash is also a tag, only make a distinction at checkout
206 rev_type = "hash"
207
msb@chromium.orge28e4982009-09-25 20:51:45 +0000208 if not os.path.exists(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000209 self._Clone(revision, url, options)
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000210 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000211 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000212 if not verbose:
213 # Make the output a little prettier. It's nice to have some whitespace
214 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000215 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000216 return
217
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000218 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
219 raise gclient_utils.Error('\n____ %s%s\n'
220 '\tPath is not a git repo. No .git dir.\n'
221 '\tTo resolve:\n'
222 '\t\trm -rf %s\n'
223 '\tAnd run gclient sync again\n'
224 % (self.relpath, rev_str, self.relpath))
225
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000226 # See if the url has changed (the unittests use git://foo for the url, let
227 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000228 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000229 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
230 # unit test pass. (and update the comment above)
231 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000232 print('_____ switching %s to a new upstream' % self.relpath)
233 # Make sure it's clean
234 self._CheckClean(rev_str)
235 # Switch over to the new upstream
236 self._Run(['remote', 'set-url', 'origin', url], options)
237 quiet = []
238 if not options.verbose:
239 quiet = ['--quiet']
240 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
241 self._Run(['reset', '--hard', 'origin/master'] + quiet, options)
242 files = self._Capture(['ls-files']).splitlines()
243 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
244 return
245
msb@chromium.org5bde4852009-12-14 16:47:12 +0000246 cur_branch = self._GetCurrentBranch()
247
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000248 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000249 # 0) HEAD is detached. Probably from our initial clone.
250 # - make sure HEAD is contained by a named ref, then update.
251 # Cases 1-4. HEAD is a branch.
252 # 1) current branch is not tracking a remote branch (could be git-svn)
253 # - try to rebase onto the new hash or branch
254 # 2) current branch is tracking a remote branch with local committed
255 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000256 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000257 # 3) current branch is tracking a remote branch w/or w/out changes,
258 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000259 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000260 # 4) current branch is tracking a remote branch, switches to a different
261 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000262 # - exit
263
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000264 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
265 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000266 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
267 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000268 if cur_branch is None:
269 upstream_branch = None
270 current_type = "detached"
271 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000272 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000273 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
274 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
275 current_type = "hash"
276 logging.debug("Current branch is not tracking an upstream (remote)"
277 " branch.")
278 elif upstream_branch.startswith('refs/remotes'):
279 current_type = "branch"
280 else:
281 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000282
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000283 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000284 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000285 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000286 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000287 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000288 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000289 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000290 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000291 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000292 # Hackish but at that point, git is known to work so just checking for
293 # 502 in stderr should be fine.
294 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000295 print(str(e))
296 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000297 time.sleep(backoff_time)
298 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000299 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000300 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000301
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000302 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000303 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000304
305 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000306 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000307 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000308
msb@chromium.org786fb682010-06-02 15:16:23 +0000309 if current_type == 'detached':
310 # case 0
311 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000312 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000313 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000314 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000315 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000316 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000317 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000318 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000319 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000320 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000321 newbase=revision, printed_path=printed_path)
322 printed_path = True
323 else:
324 # Can't find a merge-base since we don't know our upstream. That makes
325 # this command VERY likely to produce a rebase failure. For now we
326 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000327 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000328 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000329 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000330 self._AttemptRebase(upstream_branch, files, options,
331 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000332 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000333 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000334 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000335 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000336 newbase=revision, printed_path=printed_path)
337 printed_path = True
338 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
339 # case 4
340 new_base = revision.replace('heads', 'remotes/origin')
341 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000342 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000343 switch_error = ("Switching upstream branch from %s to %s\n"
344 % (upstream_branch, new_base) +
345 "Please merge or rebase manually:\n" +
346 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
347 "OR git checkout -b <some new branch> %s" % new_base)
348 raise gclient_utils.Error(switch_error)
349 else:
350 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000351 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000352 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000353 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000354 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000355 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
356 cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000357 except gclient_utils.CheckCallError, e:
358 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
359 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000360 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000361 printed_path = True
362 while True:
363 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000364 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000365 action = ask_for_data(
366 'Cannot fast-forward merge, attempt to rebase? '
367 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000368 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000369 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000370 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000371 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000372 printed_path=printed_path)
373 printed_path = True
374 break
375 elif re.match(r'quit|q', action, re.I):
376 raise gclient_utils.Error("Can't fast-forward, please merge or "
377 "rebase manually.\n"
378 "cd %s && git " % self.checkout_path
379 + "rebase %s" % upstream_branch)
380 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000381 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000382 return
383 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000384 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000385 elif re.match("error: Your local changes to '.*' would be "
386 "overwritten by merge. Aborting.\nPlease, commit your "
387 "changes or stash them before you can merge.\n",
388 e.stderr):
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
392 raise gclient_utils.Error(e.stderr)
393 else:
394 # Some other problem happened with the merge
395 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000396 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000397 raise
398 else:
399 # Fast-forward merge was successful
400 if not re.match('Already up-to-date.', merge_output) or verbose:
401 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000402 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000403 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000404 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000405 if not verbose:
406 # Make the output a little prettier. It's nice to have some
407 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000408 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000409
410 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000411
412 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000413 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000414 raise gclient_utils.Error('\n____ %s%s\n'
415 '\nConflict while rebasing this branch.\n'
416 'Fix the conflict and run gclient again.\n'
417 'See man git-rebase for details.\n'
418 % (self.relpath, rev_str))
419
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000420 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000421 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000422
423 def revert(self, options, args, file_list):
424 """Reverts local modifications.
425
426 All reverted files will be appended to file_list.
427 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000428 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000429 # revert won't work if the directory doesn't exist. It needs to
430 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000431 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000432 # Don't reuse the args.
433 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000434
435 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000436 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000437 if not deps_revision:
438 deps_revision = default_rev
439 if deps_revision.startswith('refs/heads/'):
440 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
441
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000442 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000443 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000444 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
445
msb@chromium.org0f282062009-11-06 20:14:02 +0000446 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000447 """Returns revision"""
448 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000449
msb@chromium.orge28e4982009-09-25 20:51:45 +0000450 def runhooks(self, options, args, file_list):
451 self.status(options, args, file_list)
452
453 def status(self, options, args, file_list):
454 """Display status information."""
455 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000456 print(('\n________ couldn\'t run status in %s:\n'
457 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000458 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000459 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000460 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000461 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000462 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
463
msb@chromium.orge6f78352010-01-13 17:05:33 +0000464 def FullUrlForRelativeUrl(self, url):
465 # Strip from last '/'
466 # Equivalent to unix basename
467 base_url = self.url
468 return base_url[:base_url.rfind('/')] + url
469
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000470 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000471 """Clone a git repository from the given URL.
472
msb@chromium.org786fb682010-06-02 15:16:23 +0000473 Once we've cloned the repo, we checkout a working branch if the specified
474 revision is a branch head. If it is a tag or a specific commit, then we
475 leave HEAD detached as it makes future updates simpler -- in this case the
476 user should first create a new branch or switch to an existing branch before
477 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000478 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000479 # git clone doesn't seem to insert a newline properly before printing
480 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000481 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000482
483 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000484 if revision.startswith('refs/heads/'):
485 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
486 detach_head = False
487 else:
488 clone_cmd.append('--no-checkout')
489 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000490 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000491 clone_cmd.append('--verbose')
492 clone_cmd.extend([url, self.checkout_path])
493
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000494 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000495 try:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000496 self._Run(clone_cmd, options, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000497 break
498 except gclient_utils.Error, e:
499 # TODO(maruel): Hackish, should be fixed by moving _Run() to
500 # CheckCall().
501 # Too bad we don't have access to the actual output.
502 # We should check for "transfer closed with NNN bytes remaining to
503 # read". In the meantime, just make sure .git exists.
504 if (e.args[0] == 'git command clone returned 128' and
505 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000506 print(str(e))
507 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000508 continue
509 raise e
510
msb@chromium.org786fb682010-06-02 15:16:23 +0000511 if detach_head:
512 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000513 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000514 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000515 ('Checked out %s to a detached HEAD. Before making any commits\n'
516 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
517 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
518 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000519
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000520 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000521 branch=None, printed_path=False):
522 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000523 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000524 revision = upstream
525 if newbase:
526 revision = newbase
527 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000528 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000529 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000530 printed_path = True
531 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000532 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000533
534 # Build the rebase command here using the args
535 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
536 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000537 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000538 rebase_cmd.append('--verbose')
539 if newbase:
540 rebase_cmd.extend(['--onto', newbase])
541 rebase_cmd.append(upstream)
542 if branch:
543 rebase_cmd.append(branch)
544
545 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000546 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000547 except gclient_utils.CheckCallError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000548 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
549 re.match(r'cannot rebase: your index contains uncommitted changes',
550 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000551 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000552 rebase_action = ask_for_data(
553 'Cannot rebase because of unstaged changes.\n'
554 '\'git reset --hard HEAD\' ?\n'
555 'WARNING: destroys any uncommitted work in your current branch!'
556 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000557 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000558 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000559 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000560 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000561 break
562 elif re.match(r'quit|q', rebase_action, re.I):
563 raise gclient_utils.Error("Please merge or rebase manually\n"
564 "cd %s && git " % self.checkout_path
565 + "%s" % ' '.join(rebase_cmd))
566 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000567 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000568 continue
569 else:
570 gclient_utils.Error("Input not recognized")
571 continue
572 elif re.search(r'^CONFLICT', e.stdout, re.M):
573 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
574 "Fix the conflict and run gclient again.\n"
575 "See 'man git-rebase' for details.\n")
576 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000577 print(e.stdout.strip())
578 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000579 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
580 "manually.\ncd %s && git " %
581 self.checkout_path
582 + "%s" % ' '.join(rebase_cmd))
583
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000584 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000585 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000586 # Make the output a little prettier. It's nice to have some
587 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000588 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000589
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000590 @staticmethod
591 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000592 (ok, current_version) = scm.GIT.AssertVersion(min_version)
593 if not ok:
594 raise gclient_utils.Error('git version %s < minimum required %s' %
595 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000596
msb@chromium.org786fb682010-06-02 15:16:23 +0000597 def _IsRebasing(self):
598 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
599 # have a plumbing command to determine whether a rebase is in progress, so
600 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
601 g = os.path.join(self.checkout_path, '.git')
602 return (
603 os.path.isdir(os.path.join(g, "rebase-merge")) or
604 os.path.isdir(os.path.join(g, "rebase-apply")))
605
606 def _CheckClean(self, rev_str):
607 # Make sure the tree is clean; see git-rebase.sh for reference
608 try:
609 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000610 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000611 except gclient_utils.CheckCallError:
612 raise gclient_utils.Error('\n____ %s%s\n'
613 '\tYou have unstaged changes.\n'
614 '\tPlease commit, stash, or reset.\n'
615 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000616 try:
617 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000618 '--ignore-submodules', 'HEAD', '--'],
619 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000620 except gclient_utils.CheckCallError:
621 raise gclient_utils.Error('\n____ %s%s\n'
622 '\tYour index contains uncommitted changes\n'
623 '\tPlease commit, stash, or reset.\n'
624 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000625
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000626 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000627 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
628 # reference by a commit). If not, error out -- most likely a rebase is
629 # in progress, try to detect so we can give a better error.
630 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000631 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
632 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000633 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000634 # Commit is not contained by any rev. See if the user is rebasing:
635 if self._IsRebasing():
636 # Punt to the user
637 raise gclient_utils.Error('\n____ %s%s\n'
638 '\tAlready in a conflict, i.e. (no branch).\n'
639 '\tFix the conflict and run gclient again.\n'
640 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
641 '\tSee man git-rebase for details.\n'
642 % (self.relpath, rev_str))
643 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000644 name = ('saved-by-gclient-' +
645 self._Capture(['rev-parse', '--short', 'HEAD']))
646 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000647 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000648 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000649
msb@chromium.org5bde4852009-12-14 16:47:12 +0000650 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000651 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000652 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000653 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000654 return None
655 return branch
656
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000657 def _Capture(self, args):
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000658 return gclient_utils.CheckCall(
659 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000660
maruel@chromium.org37e89872010-09-07 16:11:33 +0000661 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000662 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000663 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000664 always=options.verbose, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000665
666
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000667class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000668 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000669
670 def cleanup(self, options, args, file_list):
671 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000672 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000673
674 def diff(self, options, args, file_list):
675 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000676 if not os.path.isdir(self.checkout_path):
677 raise gclient_utils.Error('Directory %s is not present.' %
678 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000679 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000680
681 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000682 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000683 assert len(args) == 1
684 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
685 try:
686 os.makedirs(export_path)
687 except OSError:
688 pass
689 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000690 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000691
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000692 def pack(self, options, args, file_list):
693 """Generates a patch file which can be applied to the root of the
694 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000695 if not os.path.isdir(self.checkout_path):
696 raise gclient_utils.Error('Directory %s is not present.' %
697 self.checkout_path)
698 gclient_utils.CheckCallAndFilter(
699 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
700 cwd=self.checkout_path,
701 print_stdout=False,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000702 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000703
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000704 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000705 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000706
707 All updated files will be appended to file_list.
708
709 Raises:
710 Error: if can't get URL for relative path.
711 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000712 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000713 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000714 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000715 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000716 return
717
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000718 hg_path = os.path.join(self.checkout_path, '.hg')
719 if os.path.exists(hg_path):
720 print('________ found .hg directory; skipping %s' % self.relpath)
721 return
722
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000723 if args:
724 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
725
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000726 # revision is the revision to match. It is None if no revision is specified,
727 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000728 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000729 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000730 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000731 if options.revision:
732 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000733 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000734 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000735 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000736 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000737 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000738 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000739 else:
740 forced_revision = False
741 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000742
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000743 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000744 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000745 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000746 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000747 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000748 return
749
750 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000751 try:
752 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
753 except gclient_utils.Error:
754 raise gclient_utils.Error(
755 ('Can\'t update/checkout %s if an unversioned directory is present. '
756 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000757
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000758 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000759 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
760 if [True for d in dir_info
761 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000762 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000763 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000764
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000765 # Retrieve the current HEAD version because svn is slow at null updates.
766 if options.manually_grab_svn_rev and not revision:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000767 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000768 revision = str(from_info_live['Revision'])
769 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000770
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000771 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000772 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000773 try:
774 to_info = scm.SVN.CaptureInfo(url)
775 except gclient_utils.Error:
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000776 # The url is invalid or the server is not accessible, it's safer to bail
777 # out right now.
778 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000779 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
780 and (from_info['UUID'] == to_info['UUID']))
781 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000782 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000783 # We have different roots, so check if we can switch --relocate.
784 # Subversion only permits this if the repository UUIDs match.
785 # Perform the switch --relocate, then rewrite the from_url
786 # to reflect where we "are now." (This is the same way that
787 # Subversion itself handles the metadata when switch --relocate
788 # is used.) This makes the checks below for whether we
789 # can update to a revision or have to switch to a different
790 # branch work as expected.
791 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000792 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000793 from_info['Repository Root'],
794 to_info['Repository Root'],
795 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000796 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000797 from_info['URL'] = from_info['URL'].replace(
798 from_info['Repository Root'],
799 to_info['Repository Root'])
800 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000801 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000802 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000803 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000804 if status[0] != '?':
805 raise gclient_utils.Error(
806 ('Can\'t switch the checkout to %s; UUID don\'t match and '
807 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000808 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000809 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000810 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000811 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000812 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000813 command = ['checkout', url, 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 return
817
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000818 # If the provided url has a revision number that matches the revision
819 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000820 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000821 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000822 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000823 return
824
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000825 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000826 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000827 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000828
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000829 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000830 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000831 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000832 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000833 # Create an empty checkout and then update the one file we want. Future
834 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000835 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000836 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000837 if os.path.exists(os.path.join(self.checkout_path, filename)):
838 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000839 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000840 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000841 # After the initial checkout, we can use update as if it were any other
842 # dep.
843 self.update(options, args, file_list)
844 else:
845 # If the installed version of SVN doesn't support --depth, fallback to
846 # just exporting the file. This has the downside that revision
847 # information is not stored next to the file, so we will have to
848 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000849 if not os.path.exists(self.checkout_path):
850 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000851 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000852 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000853 command = self._AddAdditionalUpdateFlags(command, options,
854 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000855 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000856
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000857 def revert(self, options, args, file_list):
858 """Reverts local modifications. Subversion specific.
859
860 All reverted files will be appended to file_list, even if Subversion
861 doesn't know about them.
862 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000863 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000864 # svn revert won't work if the directory doesn't exist. It needs to
865 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000866 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000867 # Don't reuse the args.
868 return self.update(options, [], file_list)
869
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000870 def printcb(file_status):
871 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000872 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000873 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000874 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000875 print(os.path.join(self.checkout_path, file_status[1]))
876 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000877
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000878 try:
879 # svn revert is so broken we don't even use it. Using
880 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000881 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000882 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
883 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000884 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +0000885 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000886 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000887
msb@chromium.org0f282062009-11-06 20:14:02 +0000888 def revinfo(self, options, args, file_list):
889 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000890 try:
891 return scm.SVN.CaptureRevision(self.checkout_path)
892 except gclient_utils.Error:
893 return None
msb@chromium.org0f282062009-11-06 20:14:02 +0000894
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000895 def runhooks(self, options, args, file_list):
896 self.status(options, args, file_list)
897
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000898 def status(self, options, args, file_list):
899 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000900 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000901 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000902 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000903 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
904 'The directory does not exist.') %
905 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000906 # There's no file list to retrieve.
907 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000908 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000909
910 def FullUrlForRelativeUrl(self, url):
911 # Find the forth '/' and strip from there. A bit hackish.
912 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000913
maruel@chromium.org669600d2010-09-01 19:06:31 +0000914 def _Run(self, args, options, **kwargs):
915 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000916 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000917 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000918 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000919
920 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
921 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000922 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +0000923 scm.SVN.RunAndGetFileList(
924 options.verbose,
925 args + ['--ignore-externals'],
926 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000927 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000928
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000929 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000930 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000931 """Add additional flags to command depending on what options are set.
932 command should be a list of strings that represents an svn command.
933
934 This method returns a new list to be used as a command."""
935 new_command = command[:]
936 if revision:
937 new_command.extend(['--revision', str(revision).strip()])
938 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000939 if ((options.force or options.manually_grab_svn_rev) and
940 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000941 new_command.append('--force')
942 return new_command