blob: a96e0367bbd5726f4bd2208cc1c0eca5e88b6d46 [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.orgfd876172010-04-30 14:01:05 +000012import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000014import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016
17
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000018class DiffFilterer(object):
19 """Simple class which tracks which file is being diffed and
20 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000021 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000022 index_string = "Index: "
23 original_prefix = "--- "
24 working_prefix = "+++ "
25
26 def __init__(self, relpath):
27 # Note that we always use '/' as the path separator to be
28 # consistent with svn's cygwin-style output on Windows
29 self._relpath = relpath.replace("\\", "/")
30 self._current_file = ""
31 self._replacement_file = ""
32
maruel@chromium.org6e29d572010-06-04 17:32:20 +000033 def SetCurrentFile(self, current_file):
34 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000035 # Note that we always use '/' as the path separator to be
36 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000037 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000038
39 def ReplaceAndPrint(self, line):
40 print(line.replace(self._current_file, self._replacement_file))
41
42 def Filter(self, line):
43 if (line.startswith(self.index_string)):
44 self.SetCurrentFile(line[len(self.index_string):])
45 self.ReplaceAndPrint(line)
46 else:
47 if (line.startswith(self.original_prefix) or
48 line.startswith(self.working_prefix)):
49 self.ReplaceAndPrint(line)
50 else:
51 print line
52
53
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000054### SCM abstraction layer
55
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000056# Factory Method for SCM wrapper creation
57
58def CreateSCM(url=None, root_dir=None, relpath=None, scm_name='svn'):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000059 scm_map = {
60 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000061 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000062 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000063
msb@chromium.org1b8779a2009-11-19 18:11:39 +000064 orig_url = url
65
66 if url:
67 url, _ = gclient_utils.SplitUrlRevision(url)
68 if url.startswith('git:') or url.startswith('ssh:') or url.endswith('.git'):
69 scm_name = 'git'
msb@chromium.orge28e4982009-09-25 20:51:45 +000070
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000071 if not scm_name in scm_map:
72 raise gclient_utils.Error('Unsupported scm %s' % scm_name)
msb@chromium.org1b8779a2009-11-19 18:11:39 +000073 return scm_map[scm_name](orig_url, root_dir, relpath, scm_name)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000074
75
76# SCMWrapper base class
77
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000078class SCMWrapper(object):
79 """Add necessary glue between all the supported SCM.
80
msb@chromium.orgd6504212010-01-13 17:34:31 +000081 This is the abstraction layer to bind to different SCM.
82 """
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000083 def __init__(self, url=None, root_dir=None, relpath=None,
84 scm_name='svn'):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000085 self.scm_name = scm_name
86 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000087 self._root_dir = root_dir
88 if self._root_dir:
89 self._root_dir = self._root_dir.replace('/', os.sep)
90 self.relpath = relpath
91 if self.relpath:
92 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000093 if self.relpath and self._root_dir:
94 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000095
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000096 def RunCommand(self, command, options, args, file_list=None):
97 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +000098 if file_list is None:
99 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000100
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000101 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
102 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000103
104 if not command in commands:
105 raise gclient_utils.Error('Unknown command %s' % command)
106
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000107 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000108 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000109 command, self.scm_name))
110
111 return getattr(self, command)(options, args, file_list)
112
113
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000114class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000115 """Wrapper for Git"""
116
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000117 @staticmethod
118 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000119 """'Cleanup' the repo.
120
121 There's no real git equivalent for the svn cleanup command, do a no-op.
122 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000123
124 def diff(self, 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.orge28e4982009-09-25 20:51:45 +0000134 assert len(args) == 1
135 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
136 if not os.path.exists(export_path):
137 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000138 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
139 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000140
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000141 def pack(self, options, args, file_list):
142 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000143 repository.
144
145 The patch file is generated from a diff of the merge base of HEAD and
146 its upstream branch.
147 """
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000148 path = os.path.join(self._root_dir, self.relpath)
149 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
150 command = ['diff', merge_base]
151 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000152 scm.GIT.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000153
msb@chromium.orge28e4982009-09-25 20:51:45 +0000154 def update(self, options, args, file_list):
155 """Runs git to update or transparently checkout the working copy.
156
157 All updated files will be appended to file_list.
158
159 Raises:
160 Error: if can't get URL for relative path.
161 """
162
163 if args:
164 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
165
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000166 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000167
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000168 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000169 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000170 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000171 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000172 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000173 # Override the revision number.
174 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000175 if not revision:
176 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000177
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000178 rev_str = ' at %s' % revision
179 files = []
180
181 printed_path = False
182 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000183 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000184 print("\n_____ %s%s" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000185 verbose = ['--verbose']
186 printed_path = True
187
188 if revision.startswith('refs/heads/'):
189 rev_type = "branch"
190 elif revision.startswith('origin/'):
191 # For compatability with old naming, translate 'origin' to 'refs/heads'
192 revision = revision.replace('origin/', 'refs/heads/')
193 rev_type = "branch"
194 else:
195 # hash is also a tag, only make a distinction at checkout
196 rev_type = "hash"
197
msb@chromium.orge28e4982009-09-25 20:51:45 +0000198 if not os.path.exists(self.checkout_path):
msb@chromium.org786fb682010-06-02 15:16:23 +0000199 self._Clone(revision, url, options.verbose)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000200 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000201 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000202 if not verbose:
203 # Make the output a little prettier. It's nice to have some whitespace
204 # between projects when cloning.
205 print ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000206 return
207
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000208 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
209 raise gclient_utils.Error('\n____ %s%s\n'
210 '\tPath is not a git repo. No .git dir.\n'
211 '\tTo resolve:\n'
212 '\t\trm -rf %s\n'
213 '\tAnd run gclient sync again\n'
214 % (self.relpath, rev_str, self.relpath))
215
msb@chromium.org5bde4852009-12-14 16:47:12 +0000216 cur_branch = self._GetCurrentBranch()
217
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000218 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000219 # 0) HEAD is detached. Probably from our initial clone.
220 # - make sure HEAD is contained by a named ref, then update.
221 # Cases 1-4. HEAD is a branch.
222 # 1) current branch is not tracking a remote branch (could be git-svn)
223 # - try to rebase onto the new hash or branch
224 # 2) current branch is tracking a remote branch with local committed
225 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000226 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000227 # 3) current branch is tracking a remote branch w/or w/out changes,
228 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000229 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000230 # 4) current branch is tracking a remote branch, switches to a different
231 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000232 # - exit
233
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000234 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
235 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000236 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
237 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000238 if cur_branch is None:
239 upstream_branch = None
240 current_type = "detached"
241 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000242 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000243 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
244 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
245 current_type = "hash"
246 logging.debug("Current branch is not tracking an upstream (remote)"
247 " branch.")
248 elif upstream_branch.startswith('refs/remotes'):
249 current_type = "branch"
250 else:
251 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000252
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000253 # Update the remotes first so we have all the refs.
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000254 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000255 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000256 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000257 ['remote'] + verbose + ['update'],
258 self.checkout_path,
259 print_error=False)
260 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000261 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000262 # Hackish but at that point, git is known to work so just checking for
263 # 502 in stderr should be fine.
264 if '502' in e.stderr:
265 print str(e)
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000266 print "Sleeping 15 seconds and retrying..."
267 time.sleep(15)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000268 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000269 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000270
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000271 if verbose:
272 print remote_output.strip()
273 # git remote update prints to stderr when used with --verbose
274 print remote_err.strip()
275
276 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000277 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000278 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
279
msb@chromium.org786fb682010-06-02 15:16:23 +0000280 if current_type == 'detached':
281 # case 0
282 self._CheckClean(rev_str)
283 self._CheckDetachedHead(rev_str)
284 self._Run(['checkout', '--quiet', '%s^0' % revision])
285 if not printed_path:
286 print("\n_____ %s%s" % (self.relpath, rev_str))
287 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000288 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000289 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000290 # Our git-svn branch (upstream_branch) is our upstream
291 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
292 newbase=revision, printed_path=printed_path)
293 printed_path = True
294 else:
295 # Can't find a merge-base since we don't know our upstream. That makes
296 # this command VERY likely to produce a rebase failure. For now we
297 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000298 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000299 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000300 upstream_branch = revision
301 self._AttemptRebase(upstream_branch, files=files,
302 verbose=options.verbose, printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000303 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000304 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000305 # case 2
306 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
307 newbase=revision, printed_path=printed_path)
308 printed_path = True
309 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
310 # case 4
311 new_base = revision.replace('heads', 'remotes/origin')
312 if not printed_path:
313 print("\n_____ %s%s" % (self.relpath, rev_str))
314 switch_error = ("Switching upstream branch from %s to %s\n"
315 % (upstream_branch, new_base) +
316 "Please merge or rebase manually:\n" +
317 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
318 "OR git checkout -b <some new branch> %s" % new_base)
319 raise gclient_utils.Error(switch_error)
320 else:
321 # case 3 - the default case
322 files = self._Run(['diff', upstream_branch, '--name-only']).split()
323 if verbose:
324 print "Trying fast-forward merge to branch : %s" % upstream_branch
325 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000326 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
327 upstream_branch],
328 self.checkout_path,
329 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000330 except gclient_utils.CheckCallError, e:
331 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
332 if not printed_path:
333 print("\n_____ %s%s" % (self.relpath, rev_str))
334 printed_path = True
335 while True:
336 try:
337 action = str(raw_input("Cannot fast-forward merge, attempt to "
338 "rebase? (y)es / (q)uit / (s)kip : "))
339 except ValueError:
340 gclient_utils.Error('Invalid Character')
341 continue
342 if re.match(r'yes|y', action, re.I):
343 self._AttemptRebase(upstream_branch, files,
344 verbose=options.verbose,
345 printed_path=printed_path)
346 printed_path = True
347 break
348 elif re.match(r'quit|q', action, re.I):
349 raise gclient_utils.Error("Can't fast-forward, please merge or "
350 "rebase manually.\n"
351 "cd %s && git " % self.checkout_path
352 + "rebase %s" % upstream_branch)
353 elif re.match(r'skip|s', action, re.I):
354 print "Skipping %s" % self.relpath
355 return
356 else:
357 print "Input not recognized"
358 elif re.match("error: Your local changes to '.*' would be "
359 "overwritten by merge. Aborting.\nPlease, commit your "
360 "changes or stash them before you can merge.\n",
361 e.stderr):
362 if not printed_path:
363 print("\n_____ %s%s" % (self.relpath, rev_str))
364 printed_path = True
365 raise gclient_utils.Error(e.stderr)
366 else:
367 # Some other problem happened with the merge
368 logging.error("Error during fast-forward merge in %s!" % self.relpath)
369 print e.stderr
370 raise
371 else:
372 # Fast-forward merge was successful
373 if not re.match('Already up-to-date.', merge_output) or verbose:
374 if not printed_path:
375 print("\n_____ %s%s" % (self.relpath, rev_str))
376 printed_path = True
377 print merge_output.strip()
378 if merge_err:
379 print "Merge produced error output:\n%s" % merge_err.strip()
380 if not verbose:
381 # Make the output a little prettier. It's nice to have some
382 # whitespace between projects when syncing.
383 print ""
384
385 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000386
387 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000388 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000389 raise gclient_utils.Error('\n____ %s%s\n'
390 '\nConflict while rebasing this branch.\n'
391 'Fix the conflict and run gclient again.\n'
392 'See man git-rebase for details.\n'
393 % (self.relpath, rev_str))
394
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000395 if verbose:
396 print "Checked out revision %s" % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000397
398 def revert(self, options, args, file_list):
399 """Reverts local modifications.
400
401 All reverted files will be appended to file_list.
402 """
msb@chromium.org260c6532009-10-28 03:22:35 +0000403 path = os.path.join(self._root_dir, self.relpath)
404 if not os.path.isdir(path):
405 # revert won't work if the directory doesn't exist. It needs to
406 # checkout instead.
407 print("\n_____ %s is missing, synching instead" % self.relpath)
408 # Don't reuse the args.
409 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000410
411 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000412 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000413 if not deps_revision:
414 deps_revision = default_rev
415 if deps_revision.startswith('refs/heads/'):
416 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
417
418 files = self._Run(['diff', deps_revision, '--name-only']).split()
419 self._Run(['reset', '--hard', deps_revision], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000420 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
421
msb@chromium.org0f282062009-11-06 20:14:02 +0000422 def revinfo(self, options, args, file_list):
423 """Display revision"""
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000424 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000425
msb@chromium.orge28e4982009-09-25 20:51:45 +0000426 def runhooks(self, options, args, file_list):
427 self.status(options, args, file_list)
428
429 def status(self, options, args, file_list):
430 """Display status information."""
431 if not os.path.isdir(self.checkout_path):
432 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000433 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000434 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000435 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
436 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
437 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000438 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
439
msb@chromium.orge6f78352010-01-13 17:05:33 +0000440 def FullUrlForRelativeUrl(self, url):
441 # Strip from last '/'
442 # Equivalent to unix basename
443 base_url = self.url
444 return base_url[:base_url.rfind('/')] + url
445
msb@chromium.org786fb682010-06-02 15:16:23 +0000446 def _Clone(self, revision, url, verbose=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000447 """Clone a git repository from the given URL.
448
msb@chromium.org786fb682010-06-02 15:16:23 +0000449 Once we've cloned the repo, we checkout a working branch if the specified
450 revision is a branch head. If it is a tag or a specific commit, then we
451 leave HEAD detached as it makes future updates simpler -- in this case the
452 user should first create a new branch or switch to an existing branch before
453 making changes in the repo."""
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000454 if not verbose:
455 # git clone doesn't seem to insert a newline properly before printing
456 # to stdout
457 print ""
458
459 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000460 if revision.startswith('refs/heads/'):
461 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
462 detach_head = False
463 else:
464 clone_cmd.append('--no-checkout')
465 detach_head = True
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000466 if verbose:
467 clone_cmd.append('--verbose')
468 clone_cmd.extend([url, self.checkout_path])
469
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000470 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000471 try:
472 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
473 break
474 except gclient_utils.Error, e:
475 # TODO(maruel): Hackish, should be fixed by moving _Run() to
476 # CheckCall().
477 # Too bad we don't have access to the actual output.
478 # We should check for "transfer closed with NNN bytes remaining to
479 # read". In the meantime, just make sure .git exists.
480 if (e.args[0] == 'git command clone returned 128' and
481 os.path.exists(os.path.join(self.checkout_path, '.git'))):
482 print str(e)
483 print "Retrying..."
484 continue
485 raise e
486
msb@chromium.org786fb682010-06-02 15:16:23 +0000487 if detach_head:
488 # Squelch git's very verbose detached HEAD warning and use our own
489 self._Run(['checkout', '--quiet', '%s^0' % revision])
490 print \
491 "Checked out %s to a detached HEAD. Before making any commits\n" \
492 "in this repo, you should use 'git checkout <branch>' to switch to\n" \
493 "an existing branch or use 'git checkout origin -b <branch>' to\n" \
494 "create a new branch for your work." % revision
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000495
496 def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
497 branch=None, printed_path=False):
498 """Attempt to rebase onto either upstream or, if specified, newbase."""
499 files.extend(self._Run(['diff', upstream, '--name-only']).split())
500 revision = upstream
501 if newbase:
502 revision = newbase
503 if not printed_path:
504 print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath,
505 revision)
506 printed_path = True
507 else:
508 print "Attempting rebase onto %s..." % revision
509
510 # Build the rebase command here using the args
511 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
512 rebase_cmd = ['rebase']
513 if verbose:
514 rebase_cmd.append('--verbose')
515 if newbase:
516 rebase_cmd.extend(['--onto', newbase])
517 rebase_cmd.append(upstream)
518 if branch:
519 rebase_cmd.append(branch)
520
521 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000522 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
523 self.checkout_path,
524 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000525 except gclient_utils.CheckCallError, e:
526 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
527 re.match(r'cannot rebase: your index contains uncommitted changes',
528 e.stderr):
529 while True:
530 rebase_action = str(raw_input("Cannot rebase because of unstaged "
531 "changes.\n'git reset --hard HEAD' ?\n"
532 "WARNING: destroys any uncommitted "
533 "work in your current branch!"
534 " (y)es / (q)uit / (s)how : "))
535 if re.match(r'yes|y', rebase_action, re.I):
536 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
537 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000538 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
539 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000540 break
541 elif re.match(r'quit|q', rebase_action, re.I):
542 raise gclient_utils.Error("Please merge or rebase manually\n"
543 "cd %s && git " % self.checkout_path
544 + "%s" % ' '.join(rebase_cmd))
545 elif re.match(r'show|s', rebase_action, re.I):
546 print "\n%s" % e.stderr.strip()
547 continue
548 else:
549 gclient_utils.Error("Input not recognized")
550 continue
551 elif re.search(r'^CONFLICT', e.stdout, re.M):
552 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
553 "Fix the conflict and run gclient again.\n"
554 "See 'man git-rebase' for details.\n")
555 else:
556 print e.stdout.strip()
557 print "Rebase produced error output:\n%s" % e.stderr.strip()
558 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
559 "manually.\ncd %s && git " %
560 self.checkout_path
561 + "%s" % ' '.join(rebase_cmd))
562
563 print rebase_output.strip()
564 if rebase_err:
565 print "Rebase produced error output:\n%s" % rebase_err.strip()
566 if not verbose:
567 # Make the output a little prettier. It's nice to have some
568 # whitespace between projects when syncing.
569 print ""
570
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000571 @staticmethod
572 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000573 (ok, current_version) = scm.GIT.AssertVersion(min_version)
574 if not ok:
575 raise gclient_utils.Error('git version %s < minimum required %s' %
576 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000577
msb@chromium.org786fb682010-06-02 15:16:23 +0000578 def _IsRebasing(self):
579 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
580 # have a plumbing command to determine whether a rebase is in progress, so
581 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
582 g = os.path.join(self.checkout_path, '.git')
583 return (
584 os.path.isdir(os.path.join(g, "rebase-merge")) or
585 os.path.isdir(os.path.join(g, "rebase-apply")))
586
587 def _CheckClean(self, rev_str):
588 # Make sure the tree is clean; see git-rebase.sh for reference
589 try:
590 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
591 self.checkout_path, print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000592 except gclient_utils.CheckCallError:
593 raise gclient_utils.Error('\n____ %s%s\n'
594 '\tYou have unstaged changes.\n'
595 '\tPlease commit, stash, or reset.\n'
596 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000597 try:
598 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
599 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
600 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000601 except gclient_utils.CheckCallError:
602 raise gclient_utils.Error('\n____ %s%s\n'
603 '\tYour index contains uncommitted changes\n'
604 '\tPlease commit, stash, or reset.\n'
605 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000606
607 def _CheckDetachedHead(self, rev_str):
608 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
609 # reference by a commit). If not, error out -- most likely a rebase is
610 # in progress, try to detect so we can give a better error.
611 try:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000612 _, _ = scm.GIT.Capture(
msb@chromium.org786fb682010-06-02 15:16:23 +0000613 ['name-rev', '--no-undefined', 'HEAD'],
614 self.checkout_path,
615 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000616 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000617 # Commit is not contained by any rev. See if the user is rebasing:
618 if self._IsRebasing():
619 # Punt to the user
620 raise gclient_utils.Error('\n____ %s%s\n'
621 '\tAlready in a conflict, i.e. (no branch).\n'
622 '\tFix the conflict and run gclient again.\n'
623 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
624 '\tSee man git-rebase for details.\n'
625 % (self.relpath, rev_str))
626 # Let's just save off the commit so we can proceed.
627 name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"])
628 self._Run(["branch", name])
629 print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
630
msb@chromium.org5bde4852009-12-14 16:47:12 +0000631 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000632 # Returns name of current branch or None for detached HEAD
633 branch = self._Run(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
634 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000635 return None
636 return branch
637
maruel@chromium.org2de10252010-02-08 01:10:39 +0000638 def _Run(self, args, cwd=None, redirect_stdout=True):
639 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000640 if cwd is None:
641 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000642 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000643 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000644 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000645 if cwd == None:
646 cwd = self.checkout_path
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000647 cmd = [scm.GIT.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000648 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000649 logging.debug(cmd)
650 try:
651 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
652 output = sp.communicate()[0]
653 except OSError:
654 raise gclient_utils.Error("git command '%s' failed to run." %
655 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000656 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000657 raise gclient_utils.Error('git command %s returned %d' %
658 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000659 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000660 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000661
662
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000663class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000664 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000665
666 def cleanup(self, options, args, file_list):
667 """Cleanup working copy."""
668 command = ['cleanup']
669 command.extend(args)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000670 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000671
672 def diff(self, options, args, file_list):
673 # NOTE: This function does not currently modify file_list.
674 command = ['diff']
675 command.extend(args)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000676 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000677
678 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000679 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000680 assert len(args) == 1
681 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
682 try:
683 os.makedirs(export_path)
684 except OSError:
685 pass
686 assert os.path.exists(export_path)
687 command = ['export', '--force', '.']
688 command.append(export_path)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000689 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000690
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000691 def pack(self, options, args, file_list):
692 """Generates a patch file which can be applied to the root of the
693 repository."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000694 path = os.path.join(self._root_dir, self.relpath)
695 command = ['diff']
696 command.extend(args)
697
698 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000699 scm.SVN.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000700
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000701 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000702 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000703
704 All updated files will be appended to file_list.
705
706 Raises:
707 Error: if can't get URL for relative path.
708 """
709 # Only update if git is not controlling the directory.
710 checkout_path = os.path.join(self._root_dir, self.relpath)
711 git_path = os.path.join(self._root_dir, self.relpath, '.git')
712 if os.path.exists(git_path):
713 print("________ found .git directory; skipping %s" % self.relpath)
714 return
715
716 if args:
717 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
718
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000719 url, revision = gclient_utils.SplitUrlRevision(self.url)
720 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000721 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000722 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000723 if options.revision:
724 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000725 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000726 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000727 forced_revision = True
728 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000729 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000730
731 if not os.path.exists(checkout_path):
732 # We need to checkout.
733 command = ['checkout', url, checkout_path]
tony@chromium.org99828122010-06-04 01:41:02 +0000734 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000735 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000736 return
737
738 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000739 from_info = scm.SVN.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000740 if not from_info:
741 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
742 "directory is present. Delete the directory "
743 "and try again." %
744 checkout_path)
745
maruel@chromium.org7753d242009-10-07 17:40:24 +0000746 if options.manually_grab_svn_rev:
747 # Retrieve the current HEAD version because svn is slow at null updates.
748 if not revision:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000749 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000750 revision = str(from_info_live['Revision'])
751 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000752
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000753 if from_info['URL'] != base_url:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000754 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000755 if not to_info.get('Repository Root') or not to_info.get('UUID'):
756 # The url is invalid or the server is not accessible, it's safer to bail
757 # out right now.
758 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000759 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
760 and (from_info['UUID'] == to_info['UUID']))
761 if can_switch:
762 print("\n_____ relocating %s to a new checkout" % self.relpath)
763 # We have different roots, so check if we can switch --relocate.
764 # Subversion only permits this if the repository UUIDs match.
765 # Perform the switch --relocate, then rewrite the from_url
766 # to reflect where we "are now." (This is the same way that
767 # Subversion itself handles the metadata when switch --relocate
768 # is used.) This makes the checks below for whether we
769 # can update to a revision or have to switch to a different
770 # branch work as expected.
771 # TODO(maruel): TEST ME !
772 command = ["switch", "--relocate",
773 from_info['Repository Root'],
774 to_info['Repository Root'],
775 self.relpath]
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000776 scm.SVN.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000777 from_info['URL'] = from_info['URL'].replace(
778 from_info['Repository Root'],
779 to_info['Repository Root'])
780 else:
tony@chromium.org92920412010-06-04 05:08:56 +0000781 if scm.SVN.CaptureStatus(checkout_path) and not options.force:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000782 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
783 "don't match and there is local changes "
784 "in %s. Delete the directory and "
785 "try again." % (url, checkout_path))
786 # Ok delete it.
787 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000788 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000789 # We need to checkout.
790 command = ['checkout', url, checkout_path]
tony@chromium.org99828122010-06-04 01:41:02 +0000791 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000792 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000793 return
794
795
796 # If the provided url has a revision number that matches the revision
797 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000798 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000799 if options.verbose or not forced_revision:
800 print("\n_____ %s%s" % (self.relpath, rev_str))
801 return
802
803 command = ["update", checkout_path]
tony@chromium.org99828122010-06-04 01:41:02 +0000804 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000805 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000806
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000807 def updatesingle(self, options, args, file_list):
808 checkout_path = os.path.join(self._root_dir, self.relpath)
809 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000810 if scm.SVN.AssertVersion("1.5")[0]:
811 if not os.path.exists(os.path.join(checkout_path, '.svn')):
812 # Create an empty checkout and then update the one file we want. Future
813 # operations will only apply to the one file we checked out.
814 command = ["checkout", "--depth", "empty", self.url, checkout_path]
815 scm.SVN.Run(command, self._root_dir)
816 if os.path.exists(os.path.join(checkout_path, filename)):
817 os.remove(os.path.join(checkout_path, filename))
818 command = ["update", filename]
819 scm.SVN.RunAndGetFileList(options, command, checkout_path, file_list)
820 # After the initial checkout, we can use update as if it were any other
821 # dep.
822 self.update(options, args, file_list)
823 else:
824 # If the installed version of SVN doesn't support --depth, fallback to
825 # just exporting the file. This has the downside that revision
826 # information is not stored next to the file, so we will have to
827 # re-export the file every time we sync.
828 if not os.path.exists(checkout_path):
829 os.makedirs(checkout_path)
830 command = ["export", os.path.join(self.url, filename),
831 os.path.join(checkout_path, filename)]
tony@chromium.org99828122010-06-04 01:41:02 +0000832 command = self.AddAdditionalFlags(command, options, options.revision)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000833 scm.SVN.Run(command, self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000834
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000835 def revert(self, options, args, file_list):
836 """Reverts local modifications. Subversion specific.
837
838 All reverted files will be appended to file_list, even if Subversion
839 doesn't know about them.
840 """
841 path = os.path.join(self._root_dir, self.relpath)
842 if not os.path.isdir(path):
843 # svn revert won't work if the directory doesn't exist. It needs to
844 # checkout instead.
845 print("\n_____ %s is missing, synching instead" % self.relpath)
846 # Don't reuse the args.
847 return self.update(options, [], file_list)
848
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000849 for file_status in scm.SVN.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000850 file_path = os.path.join(path, file_status[1])
851 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000852 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000853 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000854 continue
855
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000856 if logging.getLogger().isEnabledFor(logging.INFO):
857 logging.info('%s%s' % (file[0], file[1]))
858 else:
859 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000860 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000861 logging.error('No idea what is the status of %s.\n'
862 'You just found a bug in gclient, please ping '
863 'maruel@chromium.org ASAP!' % file_path)
864 # svn revert is really stupid. It fails on inconsistent line-endings,
865 # on switched directories, etc. So take no chance and delete everything!
866 try:
867 if not os.path.exists(file_path):
868 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000869 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000870 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000871 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000872 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000873 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000874 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000875 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000876 logging.error('no idea what is %s.\nYou just found a bug in gclient'
877 ', please ping maruel@chromium.org ASAP!' % file_path)
878 except EnvironmentError:
879 logging.error('Failed to remove %s.' % file_path)
880
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000881 try:
882 # svn revert is so broken we don't even use it. Using
883 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000884 scm.SVN.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
885 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000886 except OSError, e:
887 # Maybe the directory disapeared meanwhile. We don't want it to throw an
888 # exception.
889 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000890
msb@chromium.org0f282062009-11-06 20:14:02 +0000891 def revinfo(self, options, args, file_list):
892 """Display revision"""
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000893 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000894
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000895 def runhooks(self, options, args, file_list):
896 self.status(options, args, file_list)
897
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000898 def status(self, options, args, file_list):
899 """Display status information."""
900 path = os.path.join(self._root_dir, self.relpath)
901 command = ['status']
902 command.extend(args)
903 if not os.path.isdir(path):
904 # svn status won't work if the directory doesn't exist.
905 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
906 "does not exist."
907 % (' '.join(command), path))
908 # There's no file list to retrieve.
909 else:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000910 scm.SVN.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000911
912 def FullUrlForRelativeUrl(self, url):
913 # Find the forth '/' and strip from there. A bit hackish.
914 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000915
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000916 @staticmethod
917 def AddAdditionalFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000918 """Add additional flags to command depending on what options are set.
919 command should be a list of strings that represents an svn command.
920
921 This method returns a new list to be used as a command."""
922 new_command = command[:]
923 if revision:
924 new_command.extend(['--revision', str(revision).strip()])
925 # --force was added to 'svn update' in svn 1.5.
926 if options.force and scm.SVN.AssertVersion("1.5")[0]:
927 new_command.append('--force')
928 return new_command