blob: 134df35b023d4fa5775e9661f34aa6dc55a09fb1 [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
33 def SetCurrentFile(self, file):
34 self._current_file = file
35 # Note that we always use '/' as the path separator to be
36 # consistent with svn's cygwin-style output on Windows
37 self._replacement_file = posixpath.join(self._relpath, file)
38
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
117 def cleanup(self, options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000118 """'Cleanup' the repo.
119
120 There's no real git equivalent for the svn cleanup command, do a no-op.
121 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000122 __pychecker__ = 'unusednames=options,args,file_list'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000123
124 def diff(self, options, args, file_list):
msb@chromium.org3904caa2010-01-25 17:37:46 +0000125 __pychecker__ = 'unusednames=options,args,file_list'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000126 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
127 self._Run(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000128
129 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000130 """Export a clean directory tree into the given path.
131
132 Exports into the specified directory, creating the path if it does
133 already exist.
134 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000135 __pychecker__ = 'unusednames=options,file_list'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000136 assert len(args) == 1
137 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
138 if not os.path.exists(export_path):
139 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000140 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
141 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000142
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000143 def pack(self, options, args, file_list):
144 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000145 repository.
146
147 The patch file is generated from a diff of the merge base of HEAD and
148 its upstream branch.
149 """
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000150 __pychecker__ = 'unusednames=options,args,file_list'
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000151 path = os.path.join(self._root_dir, self.relpath)
152 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
153 command = ['diff', merge_base]
154 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000155 scm.GIT.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000156
msb@chromium.orge28e4982009-09-25 20:51:45 +0000157 def update(self, options, args, file_list):
158 """Runs git to update or transparently checkout the working copy.
159
160 All updated files will be appended to file_list.
161
162 Raises:
163 Error: if can't get URL for relative path.
164 """
165
166 if args:
167 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
168
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000169 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000170
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000171 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000172 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000173 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000174 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000175 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000176 # Override the revision number.
177 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000178 if not revision:
179 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000180
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000181 rev_str = ' at %s' % revision
182 files = []
183
184 printed_path = False
185 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000186 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000187 print("\n_____ %s%s" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000188 verbose = ['--verbose']
189 printed_path = True
190
191 if revision.startswith('refs/heads/'):
192 rev_type = "branch"
193 elif revision.startswith('origin/'):
194 # For compatability with old naming, translate 'origin' to 'refs/heads'
195 revision = revision.replace('origin/', 'refs/heads/')
196 rev_type = "branch"
197 else:
198 # hash is also a tag, only make a distinction at checkout
199 rev_type = "hash"
200
msb@chromium.orge28e4982009-09-25 20:51:45 +0000201 if not os.path.exists(self.checkout_path):
msb@chromium.org786fb682010-06-02 15:16:23 +0000202 self._Clone(revision, url, options.verbose)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000203 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000204 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000205 if not verbose:
206 # Make the output a little prettier. It's nice to have some whitespace
207 # between projects when cloning.
208 print ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000209 return
210
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000211 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
212 raise gclient_utils.Error('\n____ %s%s\n'
213 '\tPath is not a git repo. No .git dir.\n'
214 '\tTo resolve:\n'
215 '\t\trm -rf %s\n'
216 '\tAnd run gclient sync again\n'
217 % (self.relpath, rev_str, self.relpath))
218
msb@chromium.org5bde4852009-12-14 16:47:12 +0000219 cur_branch = self._GetCurrentBranch()
220
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000221 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000222 # 0) HEAD is detached. Probably from our initial clone.
223 # - make sure HEAD is contained by a named ref, then update.
224 # Cases 1-4. HEAD is a branch.
225 # 1) current branch is not tracking a remote branch (could be git-svn)
226 # - try to rebase onto the new hash or branch
227 # 2) current branch is tracking a remote branch with local committed
228 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000229 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000230 # 3) current branch is tracking a remote branch w/or w/out changes,
231 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000232 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000233 # 4) current branch is tracking a remote branch, switches to a different
234 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000235 # - exit
236
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000237 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
238 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000239 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
240 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000241 if cur_branch is None:
242 upstream_branch = None
243 current_type = "detached"
244 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000245 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000246 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
247 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
248 current_type = "hash"
249 logging.debug("Current branch is not tracking an upstream (remote)"
250 " branch.")
251 elif upstream_branch.startswith('refs/remotes'):
252 current_type = "branch"
253 else:
254 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000255
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000256 # Update the remotes first so we have all the refs.
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000257 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000258 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000259 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000260 ['remote'] + verbose + ['update'],
261 self.checkout_path,
262 print_error=False)
263 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000264 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000265 # Hackish but at that point, git is known to work so just checking for
266 # 502 in stderr should be fine.
267 if '502' in e.stderr:
268 print str(e)
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000269 print "Sleeping 15 seconds and retrying..."
270 time.sleep(15)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000271 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000272 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000273
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000274 if verbose:
275 print remote_output.strip()
276 # git remote update prints to stderr when used with --verbose
277 print remote_err.strip()
278
279 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000280 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000281 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
282
msb@chromium.org786fb682010-06-02 15:16:23 +0000283 if current_type == 'detached':
284 # case 0
285 self._CheckClean(rev_str)
286 self._CheckDetachedHead(rev_str)
287 self._Run(['checkout', '--quiet', '%s^0' % revision])
288 if not printed_path:
289 print("\n_____ %s%s" % (self.relpath, rev_str))
290 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000291 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000292 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000293 # Our git-svn branch (upstream_branch) is our upstream
294 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
295 newbase=revision, printed_path=printed_path)
296 printed_path = True
297 else:
298 # Can't find a merge-base since we don't know our upstream. That makes
299 # this command VERY likely to produce a rebase failure. For now we
300 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000301 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000302 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000303 upstream_branch = revision
304 self._AttemptRebase(upstream_branch, files=files,
305 verbose=options.verbose, printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000306 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000307 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000308 # case 2
309 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
310 newbase=revision, printed_path=printed_path)
311 printed_path = True
312 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
313 # case 4
314 new_base = revision.replace('heads', 'remotes/origin')
315 if not printed_path:
316 print("\n_____ %s%s" % (self.relpath, rev_str))
317 switch_error = ("Switching upstream branch from %s to %s\n"
318 % (upstream_branch, new_base) +
319 "Please merge or rebase manually:\n" +
320 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
321 "OR git checkout -b <some new branch> %s" % new_base)
322 raise gclient_utils.Error(switch_error)
323 else:
324 # case 3 - the default case
325 files = self._Run(['diff', upstream_branch, '--name-only']).split()
326 if verbose:
327 print "Trying fast-forward merge to branch : %s" % upstream_branch
328 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000329 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
330 upstream_branch],
331 self.checkout_path,
332 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000333 except gclient_utils.CheckCallError, e:
334 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
335 if not printed_path:
336 print("\n_____ %s%s" % (self.relpath, rev_str))
337 printed_path = True
338 while True:
339 try:
340 action = str(raw_input("Cannot fast-forward merge, attempt to "
341 "rebase? (y)es / (q)uit / (s)kip : "))
342 except ValueError:
343 gclient_utils.Error('Invalid Character')
344 continue
345 if re.match(r'yes|y', action, re.I):
346 self._AttemptRebase(upstream_branch, files,
347 verbose=options.verbose,
348 printed_path=printed_path)
349 printed_path = True
350 break
351 elif re.match(r'quit|q', action, re.I):
352 raise gclient_utils.Error("Can't fast-forward, please merge or "
353 "rebase manually.\n"
354 "cd %s && git " % self.checkout_path
355 + "rebase %s" % upstream_branch)
356 elif re.match(r'skip|s', action, re.I):
357 print "Skipping %s" % self.relpath
358 return
359 else:
360 print "Input not recognized"
361 elif re.match("error: Your local changes to '.*' would be "
362 "overwritten by merge. Aborting.\nPlease, commit your "
363 "changes or stash them before you can merge.\n",
364 e.stderr):
365 if not printed_path:
366 print("\n_____ %s%s" % (self.relpath, rev_str))
367 printed_path = True
368 raise gclient_utils.Error(e.stderr)
369 else:
370 # Some other problem happened with the merge
371 logging.error("Error during fast-forward merge in %s!" % self.relpath)
372 print e.stderr
373 raise
374 else:
375 # Fast-forward merge was successful
376 if not re.match('Already up-to-date.', merge_output) or verbose:
377 if not printed_path:
378 print("\n_____ %s%s" % (self.relpath, rev_str))
379 printed_path = True
380 print merge_output.strip()
381 if merge_err:
382 print "Merge produced error output:\n%s" % merge_err.strip()
383 if not verbose:
384 # Make the output a little prettier. It's nice to have some
385 # whitespace between projects when syncing.
386 print ""
387
388 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000389
390 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000391 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000392 raise gclient_utils.Error('\n____ %s%s\n'
393 '\nConflict while rebasing this branch.\n'
394 'Fix the conflict and run gclient again.\n'
395 'See man git-rebase for details.\n'
396 % (self.relpath, rev_str))
397
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000398 if verbose:
399 print "Checked out revision %s" % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000400
401 def revert(self, options, args, file_list):
402 """Reverts local modifications.
403
404 All reverted files will be appended to file_list.
405 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000406 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000407 path = os.path.join(self._root_dir, self.relpath)
408 if not os.path.isdir(path):
409 # revert won't work if the directory doesn't exist. It needs to
410 # checkout instead.
411 print("\n_____ %s is missing, synching instead" % self.relpath)
412 # Don't reuse the args.
413 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000414
415 default_rev = "refs/heads/master"
416 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
417 if not deps_revision:
418 deps_revision = default_rev
419 if deps_revision.startswith('refs/heads/'):
420 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
421
422 files = self._Run(['diff', deps_revision, '--name-only']).split()
423 self._Run(['reset', '--hard', deps_revision], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000424 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
425
msb@chromium.org0f282062009-11-06 20:14:02 +0000426 def revinfo(self, options, args, file_list):
427 """Display revision"""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000428 __pychecker__ = 'unusednames=options,args,file_list'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000429 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000430
msb@chromium.orge28e4982009-09-25 20:51:45 +0000431 def runhooks(self, options, args, file_list):
432 self.status(options, args, file_list)
433
434 def status(self, options, args, file_list):
435 """Display status information."""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000436 __pychecker__ = 'unusednames=options,args'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000437 if not os.path.isdir(self.checkout_path):
438 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000439 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000440 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000441 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
442 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
443 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000444 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
445
msb@chromium.orge6f78352010-01-13 17:05:33 +0000446 def FullUrlForRelativeUrl(self, url):
447 # Strip from last '/'
448 # Equivalent to unix basename
449 base_url = self.url
450 return base_url[:base_url.rfind('/')] + url
451
msb@chromium.org786fb682010-06-02 15:16:23 +0000452 def _Clone(self, revision, url, verbose=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000453 """Clone a git repository from the given URL.
454
msb@chromium.org786fb682010-06-02 15:16:23 +0000455 Once we've cloned the repo, we checkout a working branch if the specified
456 revision is a branch head. If it is a tag or a specific commit, then we
457 leave HEAD detached as it makes future updates simpler -- in this case the
458 user should first create a new branch or switch to an existing branch before
459 making changes in the repo."""
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000460 if not verbose:
461 # git clone doesn't seem to insert a newline properly before printing
462 # to stdout
463 print ""
464
465 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000466 if revision.startswith('refs/heads/'):
467 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
468 detach_head = False
469 else:
470 clone_cmd.append('--no-checkout')
471 detach_head = True
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000472 if verbose:
473 clone_cmd.append('--verbose')
474 clone_cmd.extend([url, self.checkout_path])
475
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000476 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000477 try:
478 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
479 break
480 except gclient_utils.Error, e:
481 # TODO(maruel): Hackish, should be fixed by moving _Run() to
482 # CheckCall().
483 # Too bad we don't have access to the actual output.
484 # We should check for "transfer closed with NNN bytes remaining to
485 # read". In the meantime, just make sure .git exists.
486 if (e.args[0] == 'git command clone returned 128' and
487 os.path.exists(os.path.join(self.checkout_path, '.git'))):
488 print str(e)
489 print "Retrying..."
490 continue
491 raise e
492
msb@chromium.org786fb682010-06-02 15:16:23 +0000493 if detach_head:
494 # Squelch git's very verbose detached HEAD warning and use our own
495 self._Run(['checkout', '--quiet', '%s^0' % revision])
496 print \
497 "Checked out %s to a detached HEAD. Before making any commits\n" \
498 "in this repo, you should use 'git checkout <branch>' to switch to\n" \
499 "an existing branch or use 'git checkout origin -b <branch>' to\n" \
500 "create a new branch for your work." % revision
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000501
502 def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
503 branch=None, printed_path=False):
504 """Attempt to rebase onto either upstream or, if specified, newbase."""
505 files.extend(self._Run(['diff', upstream, '--name-only']).split())
506 revision = upstream
507 if newbase:
508 revision = newbase
509 if not printed_path:
510 print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath,
511 revision)
512 printed_path = True
513 else:
514 print "Attempting rebase onto %s..." % revision
515
516 # Build the rebase command here using the args
517 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
518 rebase_cmd = ['rebase']
519 if verbose:
520 rebase_cmd.append('--verbose')
521 if newbase:
522 rebase_cmd.extend(['--onto', newbase])
523 rebase_cmd.append(upstream)
524 if branch:
525 rebase_cmd.append(branch)
526
527 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000528 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
529 self.checkout_path,
530 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000531 except gclient_utils.CheckCallError, e:
532 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
533 re.match(r'cannot rebase: your index contains uncommitted changes',
534 e.stderr):
535 while True:
536 rebase_action = str(raw_input("Cannot rebase because of unstaged "
537 "changes.\n'git reset --hard HEAD' ?\n"
538 "WARNING: destroys any uncommitted "
539 "work in your current branch!"
540 " (y)es / (q)uit / (s)how : "))
541 if re.match(r'yes|y', rebase_action, re.I):
542 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
543 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000544 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
545 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000546 break
547 elif re.match(r'quit|q', rebase_action, re.I):
548 raise gclient_utils.Error("Please merge or rebase manually\n"
549 "cd %s && git " % self.checkout_path
550 + "%s" % ' '.join(rebase_cmd))
551 elif re.match(r'show|s', rebase_action, re.I):
552 print "\n%s" % e.stderr.strip()
553 continue
554 else:
555 gclient_utils.Error("Input not recognized")
556 continue
557 elif re.search(r'^CONFLICT', e.stdout, re.M):
558 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
559 "Fix the conflict and run gclient again.\n"
560 "See 'man git-rebase' for details.\n")
561 else:
562 print e.stdout.strip()
563 print "Rebase produced error output:\n%s" % e.stderr.strip()
564 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
565 "manually.\ncd %s && git " %
566 self.checkout_path
567 + "%s" % ' '.join(rebase_cmd))
568
569 print rebase_output.strip()
570 if rebase_err:
571 print "Rebase produced error output:\n%s" % rebase_err.strip()
572 if not verbose:
573 # Make the output a little prettier. It's nice to have some
574 # whitespace between projects when syncing.
575 print ""
576
msb@chromium.org923a0372009-12-11 20:42:43 +0000577 def _CheckMinVersion(self, min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000578 (ok, current_version) = scm.GIT.AssertVersion(min_version)
579 if not ok:
580 raise gclient_utils.Error('git version %s < minimum required %s' %
581 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000582
msb@chromium.org786fb682010-06-02 15:16:23 +0000583 def _IsRebasing(self):
584 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
585 # have a plumbing command to determine whether a rebase is in progress, so
586 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
587 g = os.path.join(self.checkout_path, '.git')
588 return (
589 os.path.isdir(os.path.join(g, "rebase-merge")) or
590 os.path.isdir(os.path.join(g, "rebase-apply")))
591
592 def _CheckClean(self, rev_str):
593 # Make sure the tree is clean; see git-rebase.sh for reference
594 try:
595 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
596 self.checkout_path, print_error=False)
597 except gclient_utils.CheckCallError, e:
598 raise gclient_utils.Error('\n____ %s%s\n'
599 '\tYou have unstaged changes.\n'
600 '\tPlease commit, stash, or reset.\n'
601 % (self.relpath, rev_str))
602 try:
603 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
604 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
605 print_error=False)
606 except gclient_utils.CheckCallError, e:
607 raise gclient_utils.Error('\n____ %s%s\n'
608 '\tYour index contains uncommitted changes\n'
609 '\tPlease commit, stash, or reset.\n'
610 % (self.relpath, rev_str))
611
612 def _CheckDetachedHead(self, rev_str):
613 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
614 # reference by a commit). If not, error out -- most likely a rebase is
615 # in progress, try to detect so we can give a better error.
616 try:
617 out, err = scm.GIT.Capture(
618 ['name-rev', '--no-undefined', 'HEAD'],
619 self.checkout_path,
620 print_error=False)
621 except gclient_utils.CheckCallError, e:
622 # Commit is not contained by any rev. See if the user is rebasing:
623 if self._IsRebasing():
624 # Punt to the user
625 raise gclient_utils.Error('\n____ %s%s\n'
626 '\tAlready in a conflict, i.e. (no branch).\n'
627 '\tFix the conflict and run gclient again.\n'
628 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
629 '\tSee man git-rebase for details.\n'
630 % (self.relpath, rev_str))
631 # Let's just save off the commit so we can proceed.
632 name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"])
633 self._Run(["branch", name])
634 print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
635
msb@chromium.org5bde4852009-12-14 16:47:12 +0000636 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000637 # Returns name of current branch or None for detached HEAD
638 branch = self._Run(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
639 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000640 return None
641 return branch
642
maruel@chromium.org2de10252010-02-08 01:10:39 +0000643 def _Run(self, args, cwd=None, redirect_stdout=True):
644 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000645 if cwd is None:
646 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000647 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000648 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000649 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000650 if cwd == None:
651 cwd = self.checkout_path
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000652 cmd = [scm.GIT.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000653 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000654 logging.debug(cmd)
655 try:
656 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
657 output = sp.communicate()[0]
658 except OSError:
659 raise gclient_utils.Error("git command '%s' failed to run." %
660 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000661 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000662 raise gclient_utils.Error('git command %s returned %d' %
663 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000664 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000665 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000666
667
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000668class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000669 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000670
671 def cleanup(self, options, args, file_list):
672 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000673 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000674 command = ['cleanup']
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 diff(self, options, args, file_list):
679 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000680 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000681 command = ['diff']
682 command.extend(args)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000683 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000684
685 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000686 """Export a clean directory tree into the given path."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000687 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000688 assert len(args) == 1
689 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
690 try:
691 os.makedirs(export_path)
692 except OSError:
693 pass
694 assert os.path.exists(export_path)
695 command = ['export', '--force', '.']
696 command.append(export_path)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000697 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000698
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000699 def pack(self, options, args, file_list):
700 """Generates a patch file which can be applied to the root of the
701 repository."""
702 __pychecker__ = 'unusednames=file_list,options'
703 path = os.path.join(self._root_dir, self.relpath)
704 command = ['diff']
705 command.extend(args)
706
707 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000708 scm.SVN.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000709
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000710 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000711 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000712
713 All updated files will be appended to file_list.
714
715 Raises:
716 Error: if can't get URL for relative path.
717 """
718 # Only update if git is not controlling the directory.
719 checkout_path = os.path.join(self._root_dir, self.relpath)
720 git_path = os.path.join(self._root_dir, self.relpath, '.git')
721 if os.path.exists(git_path):
722 print("________ found .git directory; skipping %s" % self.relpath)
723 return
724
725 if args:
726 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
727
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000728 url, revision = gclient_utils.SplitUrlRevision(self.url)
729 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000730 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000731 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000732 if options.revision:
733 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000734 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000735 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000736 forced_revision = True
737 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000738 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000739
740 if not os.path.exists(checkout_path):
741 # We need to checkout.
742 command = ['checkout', url, checkout_path]
743 if revision:
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +0000744 command.extend(['--revision', str(revision).strip()])
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000745 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000746 return
747
748 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000749 from_info = scm.SVN.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000750 if not from_info:
751 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
752 "directory is present. Delete the directory "
753 "and try again." %
754 checkout_path)
755
maruel@chromium.org7753d242009-10-07 17:40:24 +0000756 if options.manually_grab_svn_rev:
757 # Retrieve the current HEAD version because svn is slow at null updates.
758 if not revision:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000759 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000760 revision = str(from_info_live['Revision'])
761 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000762
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000763 if from_info['URL'] != base_url:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000764 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000765 if not to_info.get('Repository Root') or not to_info.get('UUID'):
766 # The url is invalid or the server is not accessible, it's safer to bail
767 # out right now.
768 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000769 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
770 and (from_info['UUID'] == to_info['UUID']))
771 if can_switch:
772 print("\n_____ relocating %s to a new checkout" % self.relpath)
773 # We have different roots, so check if we can switch --relocate.
774 # Subversion only permits this if the repository UUIDs match.
775 # Perform the switch --relocate, then rewrite the from_url
776 # to reflect where we "are now." (This is the same way that
777 # Subversion itself handles the metadata when switch --relocate
778 # is used.) This makes the checks below for whether we
779 # can update to a revision or have to switch to a different
780 # branch work as expected.
781 # TODO(maruel): TEST ME !
782 command = ["switch", "--relocate",
783 from_info['Repository Root'],
784 to_info['Repository Root'],
785 self.relpath]
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000786 scm.SVN.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000787 from_info['URL'] = from_info['URL'].replace(
788 from_info['Repository Root'],
789 to_info['Repository Root'])
790 else:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000791 if scm.SVN.CaptureStatus(checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000792 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
793 "don't match and there is local changes "
794 "in %s. Delete the directory and "
795 "try again." % (url, checkout_path))
796 # Ok delete it.
797 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000798 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000799 # We need to checkout.
800 command = ['checkout', url, checkout_path]
801 if revision:
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +0000802 command.extend(['--revision', str(revision).strip()])
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000803 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000804 return
805
806
807 # If the provided url has a revision number that matches the revision
808 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000809 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000810 if options.verbose or not forced_revision:
811 print("\n_____ %s%s" % (self.relpath, rev_str))
812 return
813
814 command = ["update", checkout_path]
815 if revision:
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +0000816 command.extend(['--revision', str(revision).strip()])
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000817 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000818
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000819 def updatesingle(self, options, args, file_list):
820 checkout_path = os.path.join(self._root_dir, self.relpath)
821 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000822 if scm.SVN.AssertVersion("1.5")[0]:
823 if not os.path.exists(os.path.join(checkout_path, '.svn')):
824 # Create an empty checkout and then update the one file we want. Future
825 # operations will only apply to the one file we checked out.
826 command = ["checkout", "--depth", "empty", self.url, checkout_path]
827 scm.SVN.Run(command, self._root_dir)
828 if os.path.exists(os.path.join(checkout_path, filename)):
829 os.remove(os.path.join(checkout_path, filename))
830 command = ["update", filename]
831 scm.SVN.RunAndGetFileList(options, command, checkout_path, file_list)
832 # After the initial checkout, we can use update as if it were any other
833 # dep.
834 self.update(options, args, file_list)
835 else:
836 # If the installed version of SVN doesn't support --depth, fallback to
837 # just exporting the file. This has the downside that revision
838 # information is not stored next to the file, so we will have to
839 # re-export the file every time we sync.
840 if not os.path.exists(checkout_path):
841 os.makedirs(checkout_path)
842 command = ["export", os.path.join(self.url, filename),
843 os.path.join(checkout_path, filename)]
844 if options.revision:
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +0000845 command.extend(['--revision', str(options.revision).strip()])
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000846 scm.SVN.Run(command, self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000847
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000848 def revert(self, options, args, file_list):
849 """Reverts local modifications. Subversion specific.
850
851 All reverted files will be appended to file_list, even if Subversion
852 doesn't know about them.
853 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000854 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000855 path = os.path.join(self._root_dir, self.relpath)
856 if not os.path.isdir(path):
857 # svn revert won't work if the directory doesn't exist. It needs to
858 # checkout instead.
859 print("\n_____ %s is missing, synching instead" % self.relpath)
860 # Don't reuse the args.
861 return self.update(options, [], file_list)
862
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000863 for file_status in scm.SVN.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000864 file_path = os.path.join(path, file_status[1])
865 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000866 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000867 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000868 continue
869
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000870 if logging.getLogger().isEnabledFor(logging.INFO):
871 logging.info('%s%s' % (file[0], file[1]))
872 else:
873 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000874 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000875 logging.error('No idea what is the status of %s.\n'
876 'You just found a bug in gclient, please ping '
877 'maruel@chromium.org ASAP!' % file_path)
878 # svn revert is really stupid. It fails on inconsistent line-endings,
879 # on switched directories, etc. So take no chance and delete everything!
880 try:
881 if not os.path.exists(file_path):
882 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000883 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000884 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000885 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000886 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000887 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000888 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000889 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000890 logging.error('no idea what is %s.\nYou just found a bug in gclient'
891 ', please ping maruel@chromium.org ASAP!' % file_path)
892 except EnvironmentError:
893 logging.error('Failed to remove %s.' % file_path)
894
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000895 try:
896 # svn revert is so broken we don't even use it. Using
897 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000898 scm.SVN.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
899 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000900 except OSError, e:
901 # Maybe the directory disapeared meanwhile. We don't want it to throw an
902 # exception.
903 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000904
msb@chromium.org0f282062009-11-06 20:14:02 +0000905 def revinfo(self, options, args, file_list):
906 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000907 __pychecker__ = 'unusednames=args,file_list,options'
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000908 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000909
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000910 def runhooks(self, options, args, file_list):
911 self.status(options, args, file_list)
912
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000913 def status(self, options, args, file_list):
914 """Display status information."""
915 path = os.path.join(self._root_dir, self.relpath)
916 command = ['status']
917 command.extend(args)
918 if not os.path.isdir(path):
919 # svn status won't work if the directory doesn't exist.
920 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
921 "does not exist."
922 % (' '.join(command), path))
923 # There's no file list to retrieve.
924 else:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000925 scm.SVN.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000926
927 def FullUrlForRelativeUrl(self, url):
928 # Find the forth '/' and strip from there. A bit hackish.
929 return '/'.join(self.url.split('/')[:4]) + url