blob: 26d9a1588de1caa5b19d8690d65fa915c191df04 [file] [log] [blame]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00001# Copyright (c) 2009 The Chromium Authors. All rights reserved.
2# 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.org5f3eee32009-09-17 00:34:30 +000012
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000013import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000014import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015
16
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000017class DiffFilterer(object):
18 """Simple class which tracks which file is being diffed and
19 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000020 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000021 index_string = "Index: "
22 original_prefix = "--- "
23 working_prefix = "+++ "
24
25 def __init__(self, relpath):
26 # Note that we always use '/' as the path separator to be
27 # consistent with svn's cygwin-style output on Windows
28 self._relpath = relpath.replace("\\", "/")
29 self._current_file = ""
30 self._replacement_file = ""
31
32 def SetCurrentFile(self, file):
33 self._current_file = file
34 # Note that we always use '/' as the path separator to be
35 # consistent with svn's cygwin-style output on Windows
36 self._replacement_file = posixpath.join(self._relpath, file)
37
38 def ReplaceAndPrint(self, line):
39 print(line.replace(self._current_file, self._replacement_file))
40
41 def Filter(self, line):
42 if (line.startswith(self.index_string)):
43 self.SetCurrentFile(line[len(self.index_string):])
44 self.ReplaceAndPrint(line)
45 else:
46 if (line.startswith(self.original_prefix) or
47 line.startswith(self.working_prefix)):
48 self.ReplaceAndPrint(line)
49 else:
50 print line
51
52
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000053### SCM abstraction layer
54
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000055# Factory Method for SCM wrapper creation
56
57def CreateSCM(url=None, root_dir=None, relpath=None, scm_name='svn'):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000058 scm_map = {
59 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000060 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000061 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000062
msb@chromium.org1b8779a2009-11-19 18:11:39 +000063 orig_url = url
64
65 if url:
66 url, _ = gclient_utils.SplitUrlRevision(url)
67 if url.startswith('git:') or url.startswith('ssh:') or url.endswith('.git'):
68 scm_name = 'git'
msb@chromium.orge28e4982009-09-25 20:51:45 +000069
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000070 if not scm_name in scm_map:
71 raise gclient_utils.Error('Unsupported scm %s' % scm_name)
msb@chromium.org1b8779a2009-11-19 18:11:39 +000072 return scm_map[scm_name](orig_url, root_dir, relpath, scm_name)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000073
74
75# SCMWrapper base class
76
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000077class SCMWrapper(object):
78 """Add necessary glue between all the supported SCM.
79
msb@chromium.orgd6504212010-01-13 17:34:31 +000080 This is the abstraction layer to bind to different SCM.
81 """
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000082 def __init__(self, url=None, root_dir=None, relpath=None,
83 scm_name='svn'):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000084 self.scm_name = scm_name
85 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000086 self._root_dir = root_dir
87 if self._root_dir:
88 self._root_dir = self._root_dir.replace('/', os.sep)
89 self.relpath = relpath
90 if self.relpath:
91 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000092 if self.relpath and self._root_dir:
93 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000094
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000095 def RunCommand(self, command, options, args, file_list=None):
96 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +000097 if file_list is None:
98 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000099
msb@chromium.org0f282062009-11-06 20:14:02 +0000100 commands = ['cleanup', 'export', 'update', 'revert', 'revinfo',
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000101 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000102
103 if not command in commands:
104 raise gclient_utils.Error('Unknown command %s' % command)
105
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000106 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000107 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000108 command, self.scm_name))
109
110 return getattr(self, command)(options, args, file_list)
111
112
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000113class GitWrapper(SCMWrapper, scm.GIT):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000114 """Wrapper for Git"""
115
116 def cleanup(self, options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000117 """'Cleanup' the repo.
118
119 There's no real git equivalent for the svn cleanup command, do a no-op.
120 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000121 __pychecker__ = 'unusednames=options,args,file_list'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000122
123 def diff(self, options, args, file_list):
msb@chromium.org3904caa2010-01-25 17:37:46 +0000124 __pychecker__ = 'unusednames=options,args,file_list'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000125 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
126 self._Run(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000127
128 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000129 """Export a clean directory tree into the given path.
130
131 Exports into the specified directory, creating the path if it does
132 already exist.
133 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000134 __pychecker__ = 'unusednames=options,file_list'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000135 assert len(args) == 1
136 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
137 if not os.path.exists(export_path):
138 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000139 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
140 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000141
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000142 def pack(self, options, args, file_list):
143 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000144 repository.
145
146 The patch file is generated from a diff of the merge base of HEAD and
147 its upstream branch.
148 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000149 __pychecker__ = 'unusednames=options,file_list'
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000150 path = os.path.join(self._root_dir, self.relpath)
151 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
152 command = ['diff', merge_base]
153 filterer = DiffFilterer(self.relpath)
154 self.RunAndFilterOutput(command, path, False, False, filterer.Filter)
155
msb@chromium.orge28e4982009-09-25 20:51:45 +0000156 def update(self, options, args, file_list):
157 """Runs git to update or transparently checkout the working copy.
158
159 All updated files will be appended to file_list.
160
161 Raises:
162 Error: if can't get URL for relative path.
163 """
164
165 if args:
166 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
167
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000168 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000169
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000170 default_rev = "refs/heads/master"
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000171 url, revision = gclient_utils.SplitUrlRevision(self.url)
172 rev_str = ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000173 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000174 # Override the revision number.
175 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000176 if not revision:
177 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000178
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000179 rev_str = ' at %s' % revision
180 files = []
181
182 printed_path = False
183 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000184 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000185 print("\n_____ %s%s" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000186 verbose = ['--verbose']
187 printed_path = True
188
189 if revision.startswith('refs/heads/'):
190 rev_type = "branch"
191 elif revision.startswith('origin/'):
192 # For compatability with old naming, translate 'origin' to 'refs/heads'
193 revision = revision.replace('origin/', 'refs/heads/')
194 rev_type = "branch"
195 else:
196 # hash is also a tag, only make a distinction at checkout
197 rev_type = "hash"
198
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000199
msb@chromium.orge28e4982009-09-25 20:51:45 +0000200 if not os.path.exists(self.checkout_path):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000201 self._Clone(rev_type, revision, url, options.verbose)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000202 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000203 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000204 if not verbose:
205 # Make the output a little prettier. It's nice to have some whitespace
206 # between projects when cloning.
207 print ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000208 return
209
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000210 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
211 raise gclient_utils.Error('\n____ %s%s\n'
212 '\tPath is not a git repo. No .git dir.\n'
213 '\tTo resolve:\n'
214 '\t\trm -rf %s\n'
215 '\tAnd run gclient sync again\n'
216 % (self.relpath, rev_str, self.relpath))
217
msb@chromium.org5bde4852009-12-14 16:47:12 +0000218 cur_branch = self._GetCurrentBranch()
219
220 # Check if we are in a rebase conflict
221 if cur_branch is None:
222 raise gclient_utils.Error('\n____ %s%s\n'
223 '\tAlready in a conflict, i.e. (no branch).\n'
224 '\tFix the conflict and run gclient again.\n'
225 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
226 '\tSee man git-rebase for details.\n'
227 % (self.relpath, rev_str))
228
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000229 # Cases:
230 # 1) current branch based on a hash (could be git-svn)
231 # - try to rebase onto the new upstream (hash or branch)
232 # 2) current branch based on a remote branch with local committed changes,
233 # but the DEPS file switched to point to a hash
234 # - rebase those changes on top of the hash
235 # 3) current branch based on a remote with or without changes, no switch
236 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
237 # 4) current branch based on a remote, switches to a new remote
238 # - exit
239
240 # GetUpstream returns something like 'refs/remotes/origin/master' for a
241 # tracking branch
242 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
243 # or it returns None if it couldn't find an upstream
244 upstream_branch = self.GetUpstream(self.checkout_path)
245 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
246 current_type = "hash"
247 logging.debug("Current branch is based off a specific rev and is not "
248 "tracking an upstream.")
249 elif upstream_branch.startswith('refs/remotes'):
250 current_type = "branch"
251 else:
252 raise gclient_utils.Error('Invalid Upstream')
253
254 # Update the remotes first so we have all the refs
255 remote_output, remote_err = self.Capture(['remote'] + verbose + ['update'],
256 self.checkout_path,
257 print_error=False)
258 if verbose:
259 print remote_output.strip()
260 # git remote update prints to stderr when used with --verbose
261 print remote_err.strip()
262
263 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000264 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000265 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
266
267 if current_type is 'hash':
268 # case 1
269 if self.IsGitSvn(self.checkout_path) and upstream_branch is not None:
270 # Our git-svn branch (upstream_branch) is our upstream
271 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
272 newbase=revision, printed_path=printed_path)
273 printed_path = True
274 else:
275 # Can't find a merge-base since we don't know our upstream. That makes
276 # this command VERY likely to produce a rebase failure. For now we
277 # assume origin is our upstream since that's what the old behavior was.
278 self._AttemptRebase('origin', files=files, verbose=options.verbose,
279 printed_path=printed_path)
280 printed_path = True
281 elif rev_type is 'hash':
282 # case 2
283 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
284 newbase=revision, printed_path=printed_path)
285 printed_path = True
286 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
287 # case 4
288 new_base = revision.replace('heads', 'remotes/origin')
289 if not printed_path:
290 print("\n_____ %s%s" % (self.relpath, rev_str))
291 switch_error = ("Switching upstream branch from %s to %s\n"
292 % (upstream_branch, new_base) +
293 "Please merge or rebase manually:\n" +
294 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
295 "OR git checkout -b <some new branch> %s" % new_base)
296 raise gclient_utils.Error(switch_error)
297 else:
298 # case 3 - the default case
299 files = self._Run(['diff', upstream_branch, '--name-only']).split()
300 if verbose:
301 print "Trying fast-forward merge to branch : %s" % upstream_branch
302 try:
303 merge_output, merge_err = self.Capture(['merge', '--ff-only',
304 upstream_branch],
305 self.checkout_path,
306 print_error=False)
307 except gclient_utils.CheckCallError, e:
308 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
309 if not printed_path:
310 print("\n_____ %s%s" % (self.relpath, rev_str))
311 printed_path = True
312 while True:
313 try:
314 action = str(raw_input("Cannot fast-forward merge, attempt to "
315 "rebase? (y)es / (q)uit / (s)kip : "))
316 except ValueError:
317 gclient_utils.Error('Invalid Character')
318 continue
319 if re.match(r'yes|y', action, re.I):
320 self._AttemptRebase(upstream_branch, files,
321 verbose=options.verbose,
322 printed_path=printed_path)
323 printed_path = True
324 break
325 elif re.match(r'quit|q', action, re.I):
326 raise gclient_utils.Error("Can't fast-forward, please merge or "
327 "rebase manually.\n"
328 "cd %s && git " % self.checkout_path
329 + "rebase %s" % upstream_branch)
330 elif re.match(r'skip|s', action, re.I):
331 print "Skipping %s" % self.relpath
332 return
333 else:
334 print "Input not recognized"
335 elif re.match("error: Your local changes to '.*' would be "
336 "overwritten by merge. Aborting.\nPlease, commit your "
337 "changes or stash them before you can merge.\n",
338 e.stderr):
339 if not printed_path:
340 print("\n_____ %s%s" % (self.relpath, rev_str))
341 printed_path = True
342 raise gclient_utils.Error(e.stderr)
343 else:
344 # Some other problem happened with the merge
345 logging.error("Error during fast-forward merge in %s!" % self.relpath)
346 print e.stderr
347 raise
348 else:
349 # Fast-forward merge was successful
350 if not re.match('Already up-to-date.', merge_output) or verbose:
351 if not printed_path:
352 print("\n_____ %s%s" % (self.relpath, rev_str))
353 printed_path = True
354 print merge_output.strip()
355 if merge_err:
356 print "Merge produced error output:\n%s" % merge_err.strip()
357 if not verbose:
358 # Make the output a little prettier. It's nice to have some
359 # whitespace between projects when syncing.
360 print ""
361
362 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000363
364 # If the rebase generated a conflict, abort and ask user to fix
365 if self._GetCurrentBranch() is None:
366 raise gclient_utils.Error('\n____ %s%s\n'
367 '\nConflict while rebasing this branch.\n'
368 'Fix the conflict and run gclient again.\n'
369 'See man git-rebase for details.\n'
370 % (self.relpath, rev_str))
371
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000372 if verbose:
373 print "Checked out revision %s" % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000374
375 def revert(self, options, args, file_list):
376 """Reverts local modifications.
377
378 All reverted files will be appended to file_list.
379 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000380 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000381 path = os.path.join(self._root_dir, self.relpath)
382 if not os.path.isdir(path):
383 # revert won't work if the directory doesn't exist. It needs to
384 # checkout instead.
385 print("\n_____ %s is missing, synching instead" % self.relpath)
386 # Don't reuse the args.
387 return self.update(options, [], file_list)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000388 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
389 files = self._Run(['diff', merge_base, '--name-only']).split()
390 self._Run(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000391 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
392
msb@chromium.org0f282062009-11-06 20:14:02 +0000393 def revinfo(self, options, args, file_list):
394 """Display revision"""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000395 __pychecker__ = 'unusednames=options,args,file_list'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000396 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000397
msb@chromium.orge28e4982009-09-25 20:51:45 +0000398 def runhooks(self, options, args, file_list):
399 self.status(options, args, file_list)
400
401 def status(self, options, args, file_list):
402 """Display status information."""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000403 __pychecker__ = 'unusednames=options,args'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000404 if not os.path.isdir(self.checkout_path):
405 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000406 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000407 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000408 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
409 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
410 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000411 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
412
msb@chromium.orge6f78352010-01-13 17:05:33 +0000413 def FullUrlForRelativeUrl(self, url):
414 # Strip from last '/'
415 # Equivalent to unix basename
416 base_url = self.url
417 return base_url[:base_url.rfind('/')] + url
418
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000419 def _Clone(self, rev_type, revision, url, verbose=False):
420 """Clone a git repository from the given URL.
421
422 Once we've cloned the repo, we checkout a working branch based off the
423 specified revision."""
424 if not verbose:
425 # git clone doesn't seem to insert a newline properly before printing
426 # to stdout
427 print ""
428
429 clone_cmd = ['clone']
430 if verbose:
431 clone_cmd.append('--verbose')
432 clone_cmd.extend([url, self.checkout_path])
433
434 for i in range(3):
435 try:
436 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
437 break
438 except gclient_utils.Error, e:
439 # TODO(maruel): Hackish, should be fixed by moving _Run() to
440 # CheckCall().
441 # Too bad we don't have access to the actual output.
442 # We should check for "transfer closed with NNN bytes remaining to
443 # read". In the meantime, just make sure .git exists.
444 if (e.args[0] == 'git command clone returned 128' and
445 os.path.exists(os.path.join(self.checkout_path, '.git'))):
446 print str(e)
447 print "Retrying..."
448 continue
449 raise e
450
451 if rev_type is "branch":
452 short_rev = revision.replace('refs/heads/', '')
453 new_branch = revision.replace('heads', 'remotes/origin')
454 elif revision.startswith('refs/tags/'):
455 short_rev = revision.replace('refs/tags/', '')
456 new_branch = revision
457 else:
458 # revision is a specific sha1 hash
459 short_rev = revision
460 new_branch = revision
461
462 cur_branch = self._GetCurrentBranch()
463 if cur_branch != short_rev:
464 self._Run(['checkout', '-b', short_rev, new_branch],
465 redirect_stdout=False)
466
467 def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
468 branch=None, printed_path=False):
469 """Attempt to rebase onto either upstream or, if specified, newbase."""
470 files.extend(self._Run(['diff', upstream, '--name-only']).split())
471 revision = upstream
472 if newbase:
473 revision = newbase
474 if not printed_path:
475 print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath,
476 revision)
477 printed_path = True
478 else:
479 print "Attempting rebase onto %s..." % revision
480
481 # Build the rebase command here using the args
482 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
483 rebase_cmd = ['rebase']
484 if verbose:
485 rebase_cmd.append('--verbose')
486 if newbase:
487 rebase_cmd.extend(['--onto', newbase])
488 rebase_cmd.append(upstream)
489 if branch:
490 rebase_cmd.append(branch)
491
492 try:
493 rebase_output, rebase_err = self.Capture(rebase_cmd, self.checkout_path,
494 print_error=False)
495 except gclient_utils.CheckCallError, e:
496 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
497 re.match(r'cannot rebase: your index contains uncommitted changes',
498 e.stderr):
499 while True:
500 rebase_action = str(raw_input("Cannot rebase because of unstaged "
501 "changes.\n'git reset --hard HEAD' ?\n"
502 "WARNING: destroys any uncommitted "
503 "work in your current branch!"
504 " (y)es / (q)uit / (s)how : "))
505 if re.match(r'yes|y', rebase_action, re.I):
506 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
507 # Should this be recursive?
508 rebase_output, rebase_err = self.Capture(rebase_cmd,
509 self.checkout_path)
510 break
511 elif re.match(r'quit|q', rebase_action, re.I):
512 raise gclient_utils.Error("Please merge or rebase manually\n"
513 "cd %s && git " % self.checkout_path
514 + "%s" % ' '.join(rebase_cmd))
515 elif re.match(r'show|s', rebase_action, re.I):
516 print "\n%s" % e.stderr.strip()
517 continue
518 else:
519 gclient_utils.Error("Input not recognized")
520 continue
521 elif re.search(r'^CONFLICT', e.stdout, re.M):
522 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
523 "Fix the conflict and run gclient again.\n"
524 "See 'man git-rebase' for details.\n")
525 else:
526 print e.stdout.strip()
527 print "Rebase produced error output:\n%s" % e.stderr.strip()
528 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
529 "manually.\ncd %s && git " %
530 self.checkout_path
531 + "%s" % ' '.join(rebase_cmd))
532
533 print rebase_output.strip()
534 if rebase_err:
535 print "Rebase produced error output:\n%s" % rebase_err.strip()
536 if not verbose:
537 # Make the output a little prettier. It's nice to have some
538 # whitespace between projects when syncing.
539 print ""
540
msb@chromium.org923a0372009-12-11 20:42:43 +0000541 def _CheckMinVersion(self, min_version):
msb@chromium.org83376f22009-12-11 22:25:31 +0000542 def only_int(val):
543 if val.isdigit():
544 return int(val)
545 else:
546 return 0
msb@chromium.orgba9b2392009-12-11 23:30:13 +0000547 version = self._Run(['--version'], cwd='.').split()[-1]
msb@chromium.org83376f22009-12-11 22:25:31 +0000548 version_list = map(only_int, version.split('.'))
msb@chromium.org923a0372009-12-11 20:42:43 +0000549 min_version_list = map(int, min_version.split('.'))
550 for min_ver in min_version_list:
551 ver = version_list.pop(0)
552 if min_ver > ver:
553 raise gclient_utils.Error('git version %s < minimum required %s' %
554 (version, min_version))
555 elif min_ver < ver:
556 return
557
msb@chromium.org5bde4852009-12-14 16:47:12 +0000558 def _GetCurrentBranch(self):
559 # Returns name of current branch
560 # Returns None if inside a (no branch)
561 tokens = self._Run(['branch']).split()
562 branch = tokens[tokens.index('*') + 1]
563 if branch == '(no':
564 return None
565 return branch
566
maruel@chromium.org2de10252010-02-08 01:10:39 +0000567 def _Run(self, args, cwd=None, redirect_stdout=True):
568 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000569 if cwd is None:
570 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000571 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000572 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000573 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000574 if cwd == None:
575 cwd = self.checkout_path
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000576 cmd = [self.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000577 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000578 logging.debug(cmd)
579 try:
580 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
581 output = sp.communicate()[0]
582 except OSError:
583 raise gclient_utils.Error("git command '%s' failed to run." %
584 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000585 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000586 raise gclient_utils.Error('git command %s returned %d' %
587 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000588 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000589 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000590
591
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000592class SVNWrapper(SCMWrapper, scm.SVN):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000593 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000594
595 def cleanup(self, options, args, file_list):
596 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000597 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000598 command = ['cleanup']
599 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000600 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000601
602 def diff(self, options, args, file_list):
603 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000604 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000605 command = ['diff']
606 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000607 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000608
609 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000610 """Export a clean directory tree into the given path."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000611 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000612 assert len(args) == 1
613 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
614 try:
615 os.makedirs(export_path)
616 except OSError:
617 pass
618 assert os.path.exists(export_path)
619 command = ['export', '--force', '.']
620 command.append(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000621 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000622
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000623 def pack(self, options, args, file_list):
624 """Generates a patch file which can be applied to the root of the
625 repository."""
626 __pychecker__ = 'unusednames=file_list,options'
627 path = os.path.join(self._root_dir, self.relpath)
628 command = ['diff']
629 command.extend(args)
630
631 filterer = DiffFilterer(self.relpath)
632 self.RunAndFilterOutput(command, path, False, False, filterer.Filter)
633
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000634 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000635 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000636
637 All updated files will be appended to file_list.
638
639 Raises:
640 Error: if can't get URL for relative path.
641 """
642 # Only update if git is not controlling the directory.
643 checkout_path = os.path.join(self._root_dir, self.relpath)
644 git_path = os.path.join(self._root_dir, self.relpath, '.git')
645 if os.path.exists(git_path):
646 print("________ found .git directory; skipping %s" % self.relpath)
647 return
648
649 if args:
650 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
651
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000652 url, revision = gclient_utils.SplitUrlRevision(self.url)
653 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000654 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000655 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000656 if options.revision:
657 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000658 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000659 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000660 forced_revision = True
661 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000662 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000663
664 if not os.path.exists(checkout_path):
665 # We need to checkout.
666 command = ['checkout', url, checkout_path]
667 if revision:
668 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000669 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000670 return
671
672 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000673 from_info = self.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000674 if not from_info:
675 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
676 "directory is present. Delete the directory "
677 "and try again." %
678 checkout_path)
679
maruel@chromium.org7753d242009-10-07 17:40:24 +0000680 if options.manually_grab_svn_rev:
681 # Retrieve the current HEAD version because svn is slow at null updates.
682 if not revision:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000683 from_info_live = self.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000684 revision = str(from_info_live['Revision'])
685 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000686
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000687 if from_info['URL'] != base_url:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000688 to_info = self.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000689 if not to_info.get('Repository Root') or not to_info.get('UUID'):
690 # The url is invalid or the server is not accessible, it's safer to bail
691 # out right now.
692 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000693 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
694 and (from_info['UUID'] == to_info['UUID']))
695 if can_switch:
696 print("\n_____ relocating %s to a new checkout" % self.relpath)
697 # We have different roots, so check if we can switch --relocate.
698 # Subversion only permits this if the repository UUIDs match.
699 # Perform the switch --relocate, then rewrite the from_url
700 # to reflect where we "are now." (This is the same way that
701 # Subversion itself handles the metadata when switch --relocate
702 # is used.) This makes the checks below for whether we
703 # can update to a revision or have to switch to a different
704 # branch work as expected.
705 # TODO(maruel): TEST ME !
706 command = ["switch", "--relocate",
707 from_info['Repository Root'],
708 to_info['Repository Root'],
709 self.relpath]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000710 self.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000711 from_info['URL'] = from_info['URL'].replace(
712 from_info['Repository Root'],
713 to_info['Repository Root'])
714 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000715 if self.CaptureStatus(checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000716 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
717 "don't match and there is local changes "
718 "in %s. Delete the directory and "
719 "try again." % (url, checkout_path))
720 # Ok delete it.
721 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000722 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000723 # We need to checkout.
724 command = ['checkout', url, checkout_path]
725 if revision:
726 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000727 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000728 return
729
730
731 # If the provided url has a revision number that matches the revision
732 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000733 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000734 if options.verbose or not forced_revision:
735 print("\n_____ %s%s" % (self.relpath, rev_str))
736 return
737
738 command = ["update", checkout_path]
739 if revision:
740 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000741 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000742
743 def revert(self, options, args, file_list):
744 """Reverts local modifications. Subversion specific.
745
746 All reverted files will be appended to file_list, even if Subversion
747 doesn't know about them.
748 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000749 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000750 path = os.path.join(self._root_dir, self.relpath)
751 if not os.path.isdir(path):
752 # svn revert won't work if the directory doesn't exist. It needs to
753 # checkout instead.
754 print("\n_____ %s is missing, synching instead" % self.relpath)
755 # Don't reuse the args.
756 return self.update(options, [], file_list)
757
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000758 for file_status in self.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000759 file_path = os.path.join(path, file_status[1])
760 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000761 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000762 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000763 continue
764
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000765 if logging.getLogger().isEnabledFor(logging.INFO):
766 logging.info('%s%s' % (file[0], file[1]))
767 else:
768 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000769 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000770 logging.error('No idea what is the status of %s.\n'
771 'You just found a bug in gclient, please ping '
772 'maruel@chromium.org ASAP!' % file_path)
773 # svn revert is really stupid. It fails on inconsistent line-endings,
774 # on switched directories, etc. So take no chance and delete everything!
775 try:
776 if not os.path.exists(file_path):
777 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000778 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000779 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000780 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000781 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000782 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000783 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000784 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000785 logging.error('no idea what is %s.\nYou just found a bug in gclient'
786 ', please ping maruel@chromium.org ASAP!' % file_path)
787 except EnvironmentError:
788 logging.error('Failed to remove %s.' % file_path)
789
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000790 try:
791 # svn revert is so broken we don't even use it. Using
792 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000793 self.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000794 file_list)
795 except OSError, e:
796 # Maybe the directory disapeared meanwhile. We don't want it to throw an
797 # exception.
798 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000799
msb@chromium.org0f282062009-11-06 20:14:02 +0000800 def revinfo(self, options, args, file_list):
801 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000802 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000803 return self.CaptureHeadRevision(self.url)
msb@chromium.org0f282062009-11-06 20:14:02 +0000804
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000805 def runhooks(self, options, args, file_list):
806 self.status(options, args, file_list)
807
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000808 def status(self, options, args, file_list):
809 """Display status information."""
810 path = os.path.join(self._root_dir, self.relpath)
811 command = ['status']
812 command.extend(args)
813 if not os.path.isdir(path):
814 # svn status won't work if the directory doesn't exist.
815 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
816 "does not exist."
817 % (' '.join(command), path))
818 # There's no file list to retrieve.
819 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000820 self.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000821
822 def FullUrlForRelativeUrl(self, url):
823 # Find the forth '/' and strip from there. A bit hackish.
824 return '/'.join(self.url.split('/')[:4]) + url