blob: f92e4f83104ef6207c86771a8afeba273af5330a [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
11import subprocess
maruel@chromium.org945405e2010-08-18 17:01:49 +000012import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000013import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000014
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000015import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000017
18
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000019class DiffFilterer(object):
20 """Simple class which tracks which file is being diffed and
21 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000022 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000023 index_string = "Index: "
24 original_prefix = "--- "
25 working_prefix = "+++ "
26
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000027 def __init__(self, relpath, stdout):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000028 # Note that we always use '/' as the path separator to be
29 # consistent with svn's cygwin-style output on Windows
30 self._relpath = relpath.replace("\\", "/")
31 self._current_file = ""
32 self._replacement_file = ""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000033 self._stdout = stdout
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000034
maruel@chromium.org6e29d572010-06-04 17:32:20 +000035 def SetCurrentFile(self, current_file):
36 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000037 # Note that we always use '/' as the path separator to be
38 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000039 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000040
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000041 def _Replace(self, line):
42 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000043
44 def Filter(self, line):
45 if (line.startswith(self.index_string)):
46 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000047 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000048 else:
49 if (line.startswith(self.original_prefix) or
50 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000051 line = self._Replace(line)
52 self._stdout.write(line + '\n')
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000053
54
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000055### SCM abstraction layer
56
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000057# Factory Method for SCM wrapper creation
58
maruel@chromium.org9eda4112010-06-11 18:56:10 +000059def GetScmName(url):
60 if url:
61 url, _ = gclient_utils.SplitUrlRevision(url)
62 if (url.startswith('git://') or url.startswith('ssh://') or
63 url.endswith('.git')):
64 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000065 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000066 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000067 return 'svn'
68 return None
69
70
71def CreateSCM(url, root_dir=None, relpath=None):
72 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000073 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000074 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000075 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000076
maruel@chromium.org9eda4112010-06-11 18:56:10 +000077 scm_name = GetScmName(url)
78 if not scm_name in SCM_MAP:
79 raise gclient_utils.Error('No SCM found for url %s' % url)
80 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000081
82
83# SCMWrapper base class
84
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000085class SCMWrapper(object):
86 """Add necessary glue between all the supported SCM.
87
msb@chromium.orgd6504212010-01-13 17:34:31 +000088 This is the abstraction layer to bind to different SCM.
89 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000090 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000091 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000092 self._root_dir = root_dir
93 if self._root_dir:
94 self._root_dir = self._root_dir.replace('/', os.sep)
95 self.relpath = relpath
96 if self.relpath:
97 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000098 if self.relpath and self._root_dir:
99 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000100
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000101 def RunCommand(self, command, options, args, file_list=None):
102 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000103 if file_list is None:
104 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000105
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000106 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
107 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000108
109 if not command in commands:
110 raise gclient_utils.Error('Unknown command %s' % command)
111
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000112 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000113 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000114 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000115
116 return getattr(self, command)(options, args, file_list)
117
118
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000119class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000120 """Wrapper for Git"""
121
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000122 @staticmethod
123 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000124 """'Cleanup' the repo.
125
126 There's no real git equivalent for the svn cleanup command, do a no-op.
127 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000128
129 def diff(self, options, args, file_list):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000130 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
131 self._Run(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000132
133 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000134 """Export a clean directory tree into the given path.
135
136 Exports into the specified directory, creating the path if it does
137 already exist.
138 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000139 assert len(args) == 1
140 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
141 if not os.path.exists(export_path):
142 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000143 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
144 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000145
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000146 def pack(self, options, args, file_list):
147 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000148 repository.
149
150 The patch file is generated from a diff of the merge base of HEAD and
151 its upstream branch.
152 """
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000153 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000154 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000155 ['git', 'diff', merge_base],
156 cwd=self.checkout_path,
157 filter_fn=DiffFilterer(self.relpath, options.stdout).Filter,
158 stdout=options.stdout)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000159
msb@chromium.orge28e4982009-09-25 20:51:45 +0000160 def update(self, options, args, file_list):
161 """Runs git to update or transparently checkout the working copy.
162
163 All updated files will be appended to file_list.
164
165 Raises:
166 Error: if can't get URL for relative path.
167 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000168 if args:
169 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
170
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000171 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000172
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000173 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000174 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000175 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000176 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000177 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000178 # Override the revision number.
179 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000180 if not revision:
181 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000182
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000183 rev_str = ' at %s' % revision
184 files = []
185
186 printed_path = False
187 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000188 if options.verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000189 options.stdout.write("\n_____ %s%s\n" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000190 verbose = ['--verbose']
191 printed_path = True
192
193 if revision.startswith('refs/heads/'):
194 rev_type = "branch"
195 elif revision.startswith('origin/'):
196 # For compatability with old naming, translate 'origin' to 'refs/heads'
197 revision = revision.replace('origin/', 'refs/heads/')
198 rev_type = "branch"
199 else:
200 # hash is also a tag, only make a distinction at checkout
201 rev_type = "hash"
202
msb@chromium.orge28e4982009-09-25 20:51:45 +0000203 if not os.path.exists(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000204 self._Clone(revision, url, options)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000205 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000206 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000207 if not verbose:
208 # Make the output a little prettier. It's nice to have some whitespace
209 # between projects when cloning.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000210 options.stdout.write('\n')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000211 return
212
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000213 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
214 raise gclient_utils.Error('\n____ %s%s\n'
215 '\tPath is not a git repo. No .git dir.\n'
216 '\tTo resolve:\n'
217 '\t\trm -rf %s\n'
218 '\tAnd run gclient sync again\n'
219 % (self.relpath, rev_str, self.relpath))
220
msb@chromium.org5bde4852009-12-14 16:47:12 +0000221 cur_branch = self._GetCurrentBranch()
222
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000223 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000224 # 0) HEAD is detached. Probably from our initial clone.
225 # - make sure HEAD is contained by a named ref, then update.
226 # Cases 1-4. HEAD is a branch.
227 # 1) current branch is not tracking a remote branch (could be git-svn)
228 # - try to rebase onto the new hash or branch
229 # 2) current branch is tracking a remote branch with local committed
230 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000231 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000232 # 3) current branch is tracking a remote branch w/or w/out changes,
233 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000234 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000235 # 4) current branch is tracking a remote branch, switches to a different
236 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000237 # - exit
238
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000239 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
240 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000241 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
242 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000243 if cur_branch is None:
244 upstream_branch = None
245 current_type = "detached"
246 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000247 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000248 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
249 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
250 current_type = "hash"
251 logging.debug("Current branch is not tracking an upstream (remote)"
252 " branch.")
253 elif upstream_branch.startswith('refs/remotes'):
254 current_type = "branch"
255 else:
256 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000257
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000258 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000259 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000260 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000261 try:
msb@chromium.org4a3bc282010-07-20 22:44:36 +0000262 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000263 ['remote'] + verbose + ['update'],
264 self.checkout_path,
265 print_error=False)
266 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000267 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000268 # Hackish but at that point, git is known to work so just checking for
269 # 502 in stderr should be fine.
270 if '502' in e.stderr:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000271 options.stdout.write(str(e) + '\n')
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000272 options.stdout.write('Sleeping %.1f seconds and retrying...\n' %
273 backoff_time)
274 time.sleep(backoff_time)
275 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000276 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000277 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000278
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000279 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000280 options.stdout.write(remote_output.strip() + '\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000281 # git remote update prints to stderr when used with --verbose
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000282 options.stdout.write(remote_err.strip() + '\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000283
284 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000285 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000286 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
287
msb@chromium.org786fb682010-06-02 15:16:23 +0000288 if current_type == 'detached':
289 # case 0
290 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000291 self._CheckDetachedHead(rev_str, options)
msb@chromium.org786fb682010-06-02 15:16:23 +0000292 self._Run(['checkout', '--quiet', '%s^0' % revision])
293 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000294 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000295 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000296 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000297 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000298 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000299 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000300 newbase=revision, printed_path=printed_path)
301 printed_path = True
302 else:
303 # Can't find a merge-base since we don't know our upstream. That makes
304 # this command VERY likely to produce a rebase failure. For now we
305 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000306 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000307 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000308 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000309 self._AttemptRebase(upstream_branch, files, options,
310 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000311 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000312 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000313 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000314 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000315 newbase=revision, printed_path=printed_path)
316 printed_path = True
317 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
318 # case 4
319 new_base = revision.replace('heads', 'remotes/origin')
320 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000321 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000322 switch_error = ("Switching upstream branch from %s to %s\n"
323 % (upstream_branch, new_base) +
324 "Please merge or rebase manually:\n" +
325 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
326 "OR git checkout -b <some new branch> %s" % new_base)
327 raise gclient_utils.Error(switch_error)
328 else:
329 # case 3 - the default case
330 files = self._Run(['diff', upstream_branch, '--name-only']).split()
331 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000332 options.stdout.write('Trying fast-forward merge to branch : %s\n' %
333 upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000334 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000335 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
336 upstream_branch],
337 self.checkout_path,
338 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000339 except gclient_utils.CheckCallError, e:
340 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
341 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000342 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000343 printed_path = True
344 while True:
345 try:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000346 # TODO(maruel): That can't work.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000347 action = str(raw_input("Cannot fast-forward merge, attempt to "
348 "rebase? (y)es / (q)uit / (s)kip : "))
349 except ValueError:
350 gclient_utils.Error('Invalid Character')
351 continue
352 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000353 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000354 printed_path=printed_path)
355 printed_path = True
356 break
357 elif re.match(r'quit|q', action, re.I):
358 raise gclient_utils.Error("Can't fast-forward, please merge or "
359 "rebase manually.\n"
360 "cd %s && git " % self.checkout_path
361 + "rebase %s" % upstream_branch)
362 elif re.match(r'skip|s', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000363 options.stdout.write('Skipping %s\n' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000364 return
365 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000366 options.stdout.write('Input not recognized\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000367 elif re.match("error: Your local changes to '.*' would be "
368 "overwritten by merge. Aborting.\nPlease, commit your "
369 "changes or stash them before you can merge.\n",
370 e.stderr):
371 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000372 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000373 printed_path = True
374 raise gclient_utils.Error(e.stderr)
375 else:
376 # Some other problem happened with the merge
377 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000378 options.stdout.write(e.stderr + '\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000379 raise
380 else:
381 # Fast-forward merge was successful
382 if not re.match('Already up-to-date.', merge_output) or verbose:
383 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000384 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000385 printed_path = True
386 print merge_output.strip()
387 if merge_err:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000388 options.stdout.write('Merge produced error output:\n%s\n' %
389 merge_err.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000390 if not verbose:
391 # Make the output a little prettier. It's nice to have some
392 # whitespace between projects when syncing.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000393 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000394
395 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000396
397 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000398 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000399 raise gclient_utils.Error('\n____ %s%s\n'
400 '\nConflict while rebasing this branch.\n'
401 'Fix the conflict and run gclient again.\n'
402 'See man git-rebase for details.\n'
403 % (self.relpath, rev_str))
404
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000405 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000406 options.stdout.write('Checked out revision %s\n' %
407 self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000408
409 def revert(self, options, args, file_list):
410 """Reverts local modifications.
411
412 All reverted files will be appended to file_list.
413 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000414 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000415 # revert won't work if the directory doesn't exist. It needs to
416 # checkout instead.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000417 options.stdout.write('\n_____ %s is missing, synching instead\n' %
418 self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000419 # Don't reuse the args.
420 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000421
422 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000423 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000424 if not deps_revision:
425 deps_revision = default_rev
426 if deps_revision.startswith('refs/heads/'):
427 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
428
429 files = self._Run(['diff', deps_revision, '--name-only']).split()
430 self._Run(['reset', '--hard', deps_revision], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000431 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
432
msb@chromium.org0f282062009-11-06 20:14:02 +0000433 def revinfo(self, options, args, file_list):
434 """Display revision"""
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000435 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000436
msb@chromium.orge28e4982009-09-25 20:51:45 +0000437 def runhooks(self, options, args, file_list):
438 self.status(options, args, file_list)
439
440 def status(self, options, args, file_list):
441 """Display status information."""
442 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000443 options.stdout.write(
444 ('\n________ couldn\'t run status in %s:\nThe directory '
445 'does not exist.\n') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000446 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000447 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
448 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
449 files = self._Run(['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.orgf5d37bf2010-09-02 00:50:34 +0000469 options.stdout.write('\n')
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:
484 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
485 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.orgf5d37bf2010-09-02 00:50:34 +0000494 options.stdout.write(str(e) + '\n')
495 options.stdout.write('Retrying...\n')
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
501 self._Run(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000502 options.stdout.write(
503 ('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."""
511 files.extend(self._Run(['diff', upstream, '--name-only']).split())
512 revision = upstream
513 if newbase:
514 revision = newbase
515 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000516 options.stdout.write('\n_____ %s : Attempting rebase onto %s...\n' % (
517 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000518 printed_path = True
519 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000520 options.stdout.write('Attempting rebase onto %s...\n' % 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.org55e724e2010-03-11 19:36:49 +0000534 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
535 self.checkout_path,
536 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000537 except gclient_utils.CheckCallError, e:
538 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
539 re.match(r'cannot rebase: your index contains uncommitted changes',
540 e.stderr):
541 while True:
542 rebase_action = str(raw_input("Cannot rebase because of unstaged "
543 "changes.\n'git reset --hard HEAD' ?\n"
544 "WARNING: destroys any uncommitted "
545 "work in your current branch!"
546 " (y)es / (q)uit / (s)how : "))
547 if re.match(r'yes|y', rebase_action, re.I):
548 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
549 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000550 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
551 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000552 break
553 elif re.match(r'quit|q', rebase_action, re.I):
554 raise gclient_utils.Error("Please merge or rebase manually\n"
555 "cd %s && git " % self.checkout_path
556 + "%s" % ' '.join(rebase_cmd))
557 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000558 options.stdout.write('\n%s\n' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000559 continue
560 else:
561 gclient_utils.Error("Input not recognized")
562 continue
563 elif re.search(r'^CONFLICT', e.stdout, re.M):
564 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
565 "Fix the conflict and run gclient again.\n"
566 "See 'man git-rebase' for details.\n")
567 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000568 options.stdout.write(e.stdout.strip() + '\n')
569 options.stdout.write('Rebase produced error output:\n%s\n' %
570 e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000571 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
572 "manually.\ncd %s && git " %
573 self.checkout_path
574 + "%s" % ' '.join(rebase_cmd))
575
576 print rebase_output.strip()
577 if rebase_err:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000578 options.stdout.write('Rebase produced error output:\n%s\n' %
579 rebase_err.strip())
580 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000581 # Make the output a little prettier. It's nice to have some
582 # whitespace between projects when syncing.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000583 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000584
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000585 @staticmethod
586 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000587 (ok, current_version) = scm.GIT.AssertVersion(min_version)
588 if not ok:
589 raise gclient_utils.Error('git version %s < minimum required %s' %
590 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000591
msb@chromium.org786fb682010-06-02 15:16:23 +0000592 def _IsRebasing(self):
593 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
594 # have a plumbing command to determine whether a rebase is in progress, so
595 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
596 g = os.path.join(self.checkout_path, '.git')
597 return (
598 os.path.isdir(os.path.join(g, "rebase-merge")) or
599 os.path.isdir(os.path.join(g, "rebase-apply")))
600
601 def _CheckClean(self, rev_str):
602 # Make sure the tree is clean; see git-rebase.sh for reference
603 try:
604 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
605 self.checkout_path, print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000606 except gclient_utils.CheckCallError:
607 raise gclient_utils.Error('\n____ %s%s\n'
608 '\tYou have unstaged changes.\n'
609 '\tPlease commit, stash, or reset.\n'
610 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000611 try:
612 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
613 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
614 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000615 except gclient_utils.CheckCallError:
616 raise gclient_utils.Error('\n____ %s%s\n'
617 '\tYour index contains uncommitted changes\n'
618 '\tPlease commit, stash, or reset.\n'
619 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000620
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000621 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000622 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
623 # reference by a commit). If not, error out -- most likely a rebase is
624 # in progress, try to detect so we can give a better error.
625 try:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000626 _, _ = scm.GIT.Capture(
msb@chromium.org786fb682010-06-02 15:16:23 +0000627 ['name-rev', '--no-undefined', 'HEAD'],
628 self.checkout_path,
629 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000630 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000631 # Commit is not contained by any rev. See if the user is rebasing:
632 if self._IsRebasing():
633 # Punt to the user
634 raise gclient_utils.Error('\n____ %s%s\n'
635 '\tAlready in a conflict, i.e. (no branch).\n'
636 '\tFix the conflict and run gclient again.\n'
637 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
638 '\tSee man git-rebase for details.\n'
639 % (self.relpath, rev_str))
640 # Let's just save off the commit so we can proceed.
641 name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"])
642 self._Run(["branch", name])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000643 options.stdout.write(
644 '\n_____ found an unreferenced commit and saved it as \'%s\'\n' %
645 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000646
msb@chromium.org5bde4852009-12-14 16:47:12 +0000647 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000648 # Returns name of current branch or None for detached HEAD
649 branch = self._Run(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
650 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000651 return None
652 return branch
653
maruel@chromium.org2de10252010-02-08 01:10:39 +0000654 def _Run(self, args, cwd=None, redirect_stdout=True):
655 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000656 if cwd is None:
maruel@chromium.org2b9aa8e2010-08-25 20:01:42 +0000657 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000658 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000659 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000660 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000661 if cwd == None:
662 cwd = self.checkout_path
maruel@chromium.org17d01792010-09-01 18:07:10 +0000663 cmd = ['git'] + args
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000664 logging.debug(cmd)
665 try:
maruel@chromium.org3a292682010-08-23 18:54:55 +0000666 sp = gclient_utils.Popen(cmd, cwd=cwd, stdout=stdout)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000667 output = sp.communicate()[0]
668 except OSError:
669 raise gclient_utils.Error("git command '%s' failed to run." %
670 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000671 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000672 raise gclient_utils.Error('git command %s returned %d' %
673 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000674 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000675 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000676
677
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000678class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000679 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000680
681 def cleanup(self, options, args, file_list):
682 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000683 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000684
685 def diff(self, options, args, file_list):
686 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000687 if not os.path.isdir(self.checkout_path):
688 raise gclient_utils.Error('Directory %s is not present.' %
689 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000690 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000691
692 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000693 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000694 assert len(args) == 1
695 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
696 try:
697 os.makedirs(export_path)
698 except OSError:
699 pass
700 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000701 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000702
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000703 def pack(self, options, args, file_list):
704 """Generates a patch file which can be applied to the root of the
705 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000706 if not os.path.isdir(self.checkout_path):
707 raise gclient_utils.Error('Directory %s is not present.' %
708 self.checkout_path)
709 gclient_utils.CheckCallAndFilter(
710 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
711 cwd=self.checkout_path,
712 print_stdout=False,
713 filter_fn=DiffFilterer(self.relpath, options.stdout).Filter,
maruel@chromium.org559c3f82010-08-23 19:26:08 +0000714 stdout=options.stdout)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000715
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000716 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000717 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000718
719 All updated files will be appended to file_list.
720
721 Raises:
722 Error: if can't get URL for relative path.
723 """
724 # Only update if git is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000725 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000726 if os.path.exists(git_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000727 options.stdout.write('________ found .git directory; skipping %s\n' %
728 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000729 return
730
731 if args:
732 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
733
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000734 # revision is the revision to match. It is None if no revision is specified,
735 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000736 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000737 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000738 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000739 if options.revision:
740 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000741 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000742 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000743 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000744 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000745 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000746 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000747 else:
748 forced_revision = False
749 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000750
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000751 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000752 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000753 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000754 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000755 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000756 return
757
758 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000759 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000760 if not from_info:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000761 raise gclient_utils.Error(('Can\'t update/checkout %r if an unversioned '
762 'directory is present. Delete the directory '
763 'and try again.') %
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000764 self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000765
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000766 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000767 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
768 if [True for d in dir_info
769 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000770 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000771 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000772
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000773 # Retrieve the current HEAD version because svn is slow at null updates.
774 if options.manually_grab_svn_rev and not revision:
775 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
776 revision = str(from_info_live['Revision'])
777 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000778
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000779 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000780 # The repository url changed, need to switch.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000781 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000782 if not to_info.get('Repository Root') or not to_info.get('UUID'):
783 # The url is invalid or the server is not accessible, it's safer to bail
784 # out right now.
785 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000786 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
787 and (from_info['UUID'] == to_info['UUID']))
788 if can_switch:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000789 options.stdout.write('\n_____ relocating %s to a new checkout\n' %
790 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000791 # We have different roots, so check if we can switch --relocate.
792 # Subversion only permits this if the repository UUIDs match.
793 # Perform the switch --relocate, then rewrite the from_url
794 # to reflect where we "are now." (This is the same way that
795 # Subversion itself handles the metadata when switch --relocate
796 # is used.) This makes the checks below for whether we
797 # can update to a revision or have to switch to a different
798 # branch work as expected.
799 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000800 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000801 from_info['Repository Root'],
802 to_info['Repository Root'],
803 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000804 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000805 from_info['URL'] = from_info['URL'].replace(
806 from_info['Repository Root'],
807 to_info['Repository Root'])
808 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000809 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000810 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000811 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000812 if status[0] != '?':
813 raise gclient_utils.Error(
814 ('Can\'t switch the checkout to %s; UUID don\'t match and '
815 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000816 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000817 # Ok delete it.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000818 options.stdout.write('\n_____ switching %s to a new checkout\n' %
819 self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000820 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000821 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000822 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000823 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000824 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000825 return
826
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000827 # If the provided url has a revision number that matches the revision
828 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000829 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000830 if options.verbose or not forced_revision:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000831 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000832 return
833
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000834 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000835 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000836 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000837
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000838 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000839 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000840 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000841 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000842 # Create an empty checkout and then update the one file we want. Future
843 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000844 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000845 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000846 if os.path.exists(os.path.join(self.checkout_path, filename)):
847 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000848 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000849 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000850 # After the initial checkout, we can use update as if it were any other
851 # dep.
852 self.update(options, args, file_list)
853 else:
854 # If the installed version of SVN doesn't support --depth, fallback to
855 # just exporting the file. This has the downside that revision
856 # information is not stored next to the file, so we will have to
857 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000858 if not os.path.exists(self.checkout_path):
859 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000860 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000861 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000862 command = self._AddAdditionalUpdateFlags(command, options,
863 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000864 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000865
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000866 def revert(self, options, args, file_list):
867 """Reverts local modifications. Subversion specific.
868
869 All reverted files will be appended to file_list, even if Subversion
870 doesn't know about them.
871 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000872 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000873 # svn revert won't work if the directory doesn't exist. It needs to
874 # checkout instead.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000875 options.stdout.write('\n_____ %s is missing, synching instead\n' %
876 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000877 # Don't reuse the args.
878 return self.update(options, [], file_list)
879
maruel@chromium.org945405e2010-08-18 17:01:49 +0000880 # Do a flush of sys.stdout every 10 secs or so otherwise it may never be
881 # flushed fast enough for buildbot.
882 last_flushed_at = time.time()
883 sys.stdout.flush()
884
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000885 for file_status in scm.SVN.CaptureStatus(self.checkout_path):
886 file_path = os.path.join(self.checkout_path, file_status[1])
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000887 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000888 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000889 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000890 continue
891
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000892 if logging.getLogger().isEnabledFor(logging.INFO):
893 logging.info('%s%s' % (file[0], file[1]))
894 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000895 options.stdout.write(file_path + '\n')
maruel@chromium.org945405e2010-08-18 17:01:49 +0000896 # Flush at least 10 seconds between line writes. We wait at least 10
897 # seconds to avoid overloading the reader that called us with output,
898 # which can slow busy readers down.
899 if (time.time() - last_flushed_at) > 10:
900 last_flushed_at = time.time()
901 sys.stdout.flush()
902
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000903 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000904 logging.error('No idea what is the status of %s.\n'
905 'You just found a bug in gclient, please ping '
906 'maruel@chromium.org ASAP!' % file_path)
907 # svn revert is really stupid. It fails on inconsistent line-endings,
908 # on switched directories, etc. So take no chance and delete everything!
909 try:
910 if not os.path.exists(file_path):
911 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000912 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000913 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000914 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000915 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000916 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000917 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000918 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000919 logging.error('no idea what is %s.\nYou just found a bug in gclient'
920 ', please ping maruel@chromium.org ASAP!' % file_path)
921 except EnvironmentError:
922 logging.error('Failed to remove %s.' % file_path)
923
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000924 try:
925 # svn revert is so broken we don't even use it. Using
926 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000927 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
928 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000929 except OSError, e:
930 # Maybe the directory disapeared meanwhile. We don't want it to throw an
931 # exception.
932 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000933
msb@chromium.org0f282062009-11-06 20:14:02 +0000934 def revinfo(self, options, args, file_list):
935 """Display revision"""
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000936 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000937
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000938 def runhooks(self, options, args, file_list):
939 self.status(options, args, file_list)
940
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000941 def status(self, options, args, file_list):
942 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000943 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000944 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000945 # svn status won't work if the directory doesn't exist.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000946 options.stdout.write(
947 ('\n________ couldn\'t run \'%s\' in \'%s\':\nThe directory '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000948 'does not exist.') % (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000949 # There's no file list to retrieve.
950 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000951 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000952
953 def FullUrlForRelativeUrl(self, url):
954 # Find the forth '/' and strip from there. A bit hackish.
955 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000956
maruel@chromium.org669600d2010-09-01 19:06:31 +0000957 def _Run(self, args, options, **kwargs):
958 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000959 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000960 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
961 always=options.verbose, stdout=options.stdout, **kwargs)
962
963 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
964 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000965 cwd = cwd or self.checkout_path
maruel@chromium.org669600d2010-09-01 19:06:31 +0000966 scm.SVN.RunAndGetFileList(options.verbose, args, cwd=cwd,
967 file_list=file_list, stdout=options.stdout)
968
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000969 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000970 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000971 """Add additional flags to command depending on what options are set.
972 command should be a list of strings that represents an svn command.
973
974 This method returns a new list to be used as a command."""
975 new_command = command[:]
976 if revision:
977 new_command.extend(['--revision', str(revision).strip()])
978 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000979 if ((options.force or options.manually_grab_svn_rev) and
980 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000981 new_command.append('--force')
982 return new_command