blob: 8e4540e39ac0e148dc2168f37fa0e285912300ea [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
maruel@chromium.org9eda4112010-06-11 18:56:10 +000058def GetScmName(url):
59 if url:
60 url, _ = gclient_utils.SplitUrlRevision(url)
61 if (url.startswith('git://') or url.startswith('ssh://') or
62 url.endswith('.git')):
63 return 'git'
64 elif (url.startswith('http://') or url.startswith('svn://') or
65 url.startswith('ssh+svn://')):
66 return 'svn'
67 return None
68
69
70def CreateSCM(url, root_dir=None, relpath=None):
71 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000072 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000073 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000074 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000075
maruel@chromium.org9eda4112010-06-11 18:56:10 +000076 scm_name = GetScmName(url)
77 if not scm_name in SCM_MAP:
78 raise gclient_utils.Error('No SCM found for url %s' % url)
79 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000080
81
82# SCMWrapper base class
83
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000084class SCMWrapper(object):
85 """Add necessary glue between all the supported SCM.
86
msb@chromium.orgd6504212010-01-13 17:34:31 +000087 This is the abstraction layer to bind to different SCM.
88 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000089 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000090 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000091 self._root_dir = root_dir
92 if self._root_dir:
93 self._root_dir = self._root_dir.replace('/', os.sep)
94 self.relpath = relpath
95 if self.relpath:
96 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000097 if self.relpath and self._root_dir:
98 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000099
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000100 def RunCommand(self, command, options, args, file_list=None):
101 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000102 if file_list is None:
103 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000104
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000105 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
106 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000107
108 if not command in commands:
109 raise gclient_utils.Error('Unknown command %s' % command)
110
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000111 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000112 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000113 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000114
115 return getattr(self, command)(options, args, file_list)
116
117
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000118class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000119 """Wrapper for Git"""
120
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000121 @staticmethod
122 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000123 """'Cleanup' the repo.
124
125 There's no real git equivalent for the svn cleanup command, do a no-op.
126 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000127
128 def diff(self, options, args, file_list):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000129 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
130 self._Run(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000131
132 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000133 """Export a clean directory tree into the given path.
134
135 Exports into the specified directory, creating the path if it does
136 already exist.
137 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000138 assert len(args) == 1
139 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
140 if not os.path.exists(export_path):
141 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000142 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
143 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000144
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000145 def pack(self, options, args, file_list):
146 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000147 repository.
148
149 The patch file is generated from a diff of the merge base of HEAD and
150 its upstream branch.
151 """
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000152 path = os.path.join(self._root_dir, self.relpath)
153 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
154 command = ['diff', merge_base]
155 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000156 scm.GIT.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000157
msb@chromium.orge28e4982009-09-25 20:51:45 +0000158 def update(self, options, args, file_list):
159 """Runs git to update or transparently checkout the working copy.
160
161 All updated files will be appended to file_list.
162
163 Raises:
164 Error: if can't get URL for relative path.
165 """
166
167 if args:
168 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
169
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000170 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000171
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000172 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000173 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000174 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000175 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000176 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000177 # Override the revision number.
178 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000179 if not revision:
180 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000181
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000182 rev_str = ' at %s' % revision
183 files = []
184
185 printed_path = False
186 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000187 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000188 print("\n_____ %s%s" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000189 verbose = ['--verbose']
190 printed_path = True
191
192 if revision.startswith('refs/heads/'):
193 rev_type = "branch"
194 elif revision.startswith('origin/'):
195 # For compatability with old naming, translate 'origin' to 'refs/heads'
196 revision = revision.replace('origin/', 'refs/heads/')
197 rev_type = "branch"
198 else:
199 # hash is also a tag, only make a distinction at checkout
200 rev_type = "hash"
201
msb@chromium.orge28e4982009-09-25 20:51:45 +0000202 if not os.path.exists(self.checkout_path):
msb@chromium.org786fb682010-06-02 15:16:23 +0000203 self._Clone(revision, url, options.verbose)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000204 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000205 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000206 if not verbose:
207 # Make the output a little prettier. It's nice to have some whitespace
208 # between projects when cloning.
209 print ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000210 return
211
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000212 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
213 raise gclient_utils.Error('\n____ %s%s\n'
214 '\tPath is not a git repo. No .git dir.\n'
215 '\tTo resolve:\n'
216 '\t\trm -rf %s\n'
217 '\tAnd run gclient sync again\n'
218 % (self.relpath, rev_str, self.relpath))
219
msb@chromium.org5bde4852009-12-14 16:47:12 +0000220 cur_branch = self._GetCurrentBranch()
221
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000222 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000223 # 0) HEAD is detached. Probably from our initial clone.
224 # - make sure HEAD is contained by a named ref, then update.
225 # Cases 1-4. HEAD is a branch.
226 # 1) current branch is not tracking a remote branch (could be git-svn)
227 # - try to rebase onto the new hash or branch
228 # 2) current branch is tracking a remote branch with local committed
229 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000230 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000231 # 3) current branch is tracking a remote branch w/or w/out changes,
232 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000233 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000234 # 4) current branch is tracking a remote branch, switches to a different
235 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000236 # - exit
237
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000238 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
239 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000240 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
241 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000242 if cur_branch is None:
243 upstream_branch = None
244 current_type = "detached"
245 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000246 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000247 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
248 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
249 current_type = "hash"
250 logging.debug("Current branch is not tracking an upstream (remote)"
251 " branch.")
252 elif upstream_branch.startswith('refs/remotes'):
253 current_type = "branch"
254 else:
255 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000256
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000257 # Update the remotes first so we have all the refs.
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000258 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000259 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000260 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000261 ['remote'] + verbose + ['update'],
262 self.checkout_path,
263 print_error=False)
264 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000265 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000266 # Hackish but at that point, git is known to work so just checking for
267 # 502 in stderr should be fine.
268 if '502' in e.stderr:
269 print str(e)
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000270 print "Sleeping 15 seconds and retrying..."
271 time.sleep(15)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000272 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000273 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000274
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000275 if verbose:
276 print remote_output.strip()
277 # git remote update prints to stderr when used with --verbose
278 print remote_err.strip()
279
280 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000281 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000282 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
283
msb@chromium.org786fb682010-06-02 15:16:23 +0000284 if current_type == 'detached':
285 # case 0
286 self._CheckClean(rev_str)
287 self._CheckDetachedHead(rev_str)
288 self._Run(['checkout', '--quiet', '%s^0' % revision])
289 if not printed_path:
290 print("\n_____ %s%s" % (self.relpath, rev_str))
291 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000292 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000293 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000294 # Our git-svn branch (upstream_branch) is our upstream
295 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
296 newbase=revision, printed_path=printed_path)
297 printed_path = True
298 else:
299 # Can't find a merge-base since we don't know our upstream. That makes
300 # this command VERY likely to produce a rebase failure. For now we
301 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000302 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000303 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000304 upstream_branch = revision
305 self._AttemptRebase(upstream_branch, files=files,
306 verbose=options.verbose, printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000307 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000308 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000309 # case 2
310 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
311 newbase=revision, printed_path=printed_path)
312 printed_path = True
313 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
314 # case 4
315 new_base = revision.replace('heads', 'remotes/origin')
316 if not printed_path:
317 print("\n_____ %s%s" % (self.relpath, rev_str))
318 switch_error = ("Switching upstream branch from %s to %s\n"
319 % (upstream_branch, new_base) +
320 "Please merge or rebase manually:\n" +
321 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
322 "OR git checkout -b <some new branch> %s" % new_base)
323 raise gclient_utils.Error(switch_error)
324 else:
325 # case 3 - the default case
326 files = self._Run(['diff', upstream_branch, '--name-only']).split()
327 if verbose:
328 print "Trying fast-forward merge to branch : %s" % upstream_branch
329 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000330 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
331 upstream_branch],
332 self.checkout_path,
333 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000334 except gclient_utils.CheckCallError, e:
335 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
336 if not printed_path:
337 print("\n_____ %s%s" % (self.relpath, rev_str))
338 printed_path = True
339 while True:
340 try:
341 action = str(raw_input("Cannot fast-forward merge, attempt to "
342 "rebase? (y)es / (q)uit / (s)kip : "))
343 except ValueError:
344 gclient_utils.Error('Invalid Character')
345 continue
346 if re.match(r'yes|y', action, re.I):
347 self._AttemptRebase(upstream_branch, files,
348 verbose=options.verbose,
349 printed_path=printed_path)
350 printed_path = True
351 break
352 elif re.match(r'quit|q', action, re.I):
353 raise gclient_utils.Error("Can't fast-forward, please merge or "
354 "rebase manually.\n"
355 "cd %s && git " % self.checkout_path
356 + "rebase %s" % upstream_branch)
357 elif re.match(r'skip|s', action, re.I):
358 print "Skipping %s" % self.relpath
359 return
360 else:
361 print "Input not recognized"
362 elif re.match("error: Your local changes to '.*' would be "
363 "overwritten by merge. Aborting.\nPlease, commit your "
364 "changes or stash them before you can merge.\n",
365 e.stderr):
366 if not printed_path:
367 print("\n_____ %s%s" % (self.relpath, rev_str))
368 printed_path = True
369 raise gclient_utils.Error(e.stderr)
370 else:
371 # Some other problem happened with the merge
372 logging.error("Error during fast-forward merge in %s!" % self.relpath)
373 print e.stderr
374 raise
375 else:
376 # Fast-forward merge was successful
377 if not re.match('Already up-to-date.', merge_output) or verbose:
378 if not printed_path:
379 print("\n_____ %s%s" % (self.relpath, rev_str))
380 printed_path = True
381 print merge_output.strip()
382 if merge_err:
383 print "Merge produced error output:\n%s" % merge_err.strip()
384 if not verbose:
385 # Make the output a little prettier. It's nice to have some
386 # whitespace between projects when syncing.
387 print ""
388
389 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000390
391 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000392 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000393 raise gclient_utils.Error('\n____ %s%s\n'
394 '\nConflict while rebasing this branch.\n'
395 'Fix the conflict and run gclient again.\n'
396 'See man git-rebase for details.\n'
397 % (self.relpath, rev_str))
398
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000399 if verbose:
400 print "Checked out revision %s" % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000401
402 def revert(self, options, args, file_list):
403 """Reverts local modifications.
404
405 All reverted files will be appended to file_list.
406 """
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"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000416 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000417 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"""
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000428 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000429
msb@chromium.orge28e4982009-09-25 20:51:45 +0000430 def runhooks(self, options, args, file_list):
431 self.status(options, args, file_list)
432
433 def status(self, options, args, file_list):
434 """Display status information."""
435 if not os.path.isdir(self.checkout_path):
436 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000437 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000438 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000439 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
440 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
441 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000442 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
443
msb@chromium.orge6f78352010-01-13 17:05:33 +0000444 def FullUrlForRelativeUrl(self, url):
445 # Strip from last '/'
446 # Equivalent to unix basename
447 base_url = self.url
448 return base_url[:base_url.rfind('/')] + url
449
msb@chromium.org786fb682010-06-02 15:16:23 +0000450 def _Clone(self, revision, url, verbose=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000451 """Clone a git repository from the given URL.
452
msb@chromium.org786fb682010-06-02 15:16:23 +0000453 Once we've cloned the repo, we checkout a working branch if the specified
454 revision is a branch head. If it is a tag or a specific commit, then we
455 leave HEAD detached as it makes future updates simpler -- in this case the
456 user should first create a new branch or switch to an existing branch before
457 making changes in the repo."""
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000458 if not verbose:
459 # git clone doesn't seem to insert a newline properly before printing
460 # to stdout
461 print ""
462
463 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000464 if revision.startswith('refs/heads/'):
465 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
466 detach_head = False
467 else:
468 clone_cmd.append('--no-checkout')
469 detach_head = True
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470 if verbose:
471 clone_cmd.append('--verbose')
472 clone_cmd.extend([url, self.checkout_path])
473
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000474 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000475 try:
476 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
477 break
478 except gclient_utils.Error, e:
479 # TODO(maruel): Hackish, should be fixed by moving _Run() to
480 # CheckCall().
481 # Too bad we don't have access to the actual output.
482 # We should check for "transfer closed with NNN bytes remaining to
483 # read". In the meantime, just make sure .git exists.
484 if (e.args[0] == 'git command clone returned 128' and
485 os.path.exists(os.path.join(self.checkout_path, '.git'))):
486 print str(e)
487 print "Retrying..."
488 continue
489 raise e
490
msb@chromium.org786fb682010-06-02 15:16:23 +0000491 if detach_head:
492 # Squelch git's very verbose detached HEAD warning and use our own
493 self._Run(['checkout', '--quiet', '%s^0' % revision])
494 print \
495 "Checked out %s to a detached HEAD. Before making any commits\n" \
496 "in this repo, you should use 'git checkout <branch>' to switch to\n" \
497 "an existing branch or use 'git checkout origin -b <branch>' to\n" \
498 "create a new branch for your work." % revision
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000499
500 def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
501 branch=None, printed_path=False):
502 """Attempt to rebase onto either upstream or, if specified, newbase."""
503 files.extend(self._Run(['diff', upstream, '--name-only']).split())
504 revision = upstream
505 if newbase:
506 revision = newbase
507 if not printed_path:
508 print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath,
509 revision)
510 printed_path = True
511 else:
512 print "Attempting rebase onto %s..." % revision
513
514 # Build the rebase command here using the args
515 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
516 rebase_cmd = ['rebase']
517 if verbose:
518 rebase_cmd.append('--verbose')
519 if newbase:
520 rebase_cmd.extend(['--onto', newbase])
521 rebase_cmd.append(upstream)
522 if branch:
523 rebase_cmd.append(branch)
524
525 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000526 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
527 self.checkout_path,
528 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000529 except gclient_utils.CheckCallError, e:
530 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
531 re.match(r'cannot rebase: your index contains uncommitted changes',
532 e.stderr):
533 while True:
534 rebase_action = str(raw_input("Cannot rebase because of unstaged "
535 "changes.\n'git reset --hard HEAD' ?\n"
536 "WARNING: destroys any uncommitted "
537 "work in your current branch!"
538 " (y)es / (q)uit / (s)how : "))
539 if re.match(r'yes|y', rebase_action, re.I):
540 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
541 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000542 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
543 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000544 break
545 elif re.match(r'quit|q', rebase_action, re.I):
546 raise gclient_utils.Error("Please merge or rebase manually\n"
547 "cd %s && git " % self.checkout_path
548 + "%s" % ' '.join(rebase_cmd))
549 elif re.match(r'show|s', rebase_action, re.I):
550 print "\n%s" % e.stderr.strip()
551 continue
552 else:
553 gclient_utils.Error("Input not recognized")
554 continue
555 elif re.search(r'^CONFLICT', e.stdout, re.M):
556 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
557 "Fix the conflict and run gclient again.\n"
558 "See 'man git-rebase' for details.\n")
559 else:
560 print e.stdout.strip()
561 print "Rebase produced error output:\n%s" % e.stderr.strip()
562 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
563 "manually.\ncd %s && git " %
564 self.checkout_path
565 + "%s" % ' '.join(rebase_cmd))
566
567 print rebase_output.strip()
568 if rebase_err:
569 print "Rebase produced error output:\n%s" % rebase_err.strip()
570 if not verbose:
571 # Make the output a little prettier. It's nice to have some
572 # whitespace between projects when syncing.
573 print ""
574
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000575 @staticmethod
576 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000577 (ok, current_version) = scm.GIT.AssertVersion(min_version)
578 if not ok:
579 raise gclient_utils.Error('git version %s < minimum required %s' %
580 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000581
msb@chromium.org786fb682010-06-02 15:16:23 +0000582 def _IsRebasing(self):
583 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
584 # have a plumbing command to determine whether a rebase is in progress, so
585 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
586 g = os.path.join(self.checkout_path, '.git')
587 return (
588 os.path.isdir(os.path.join(g, "rebase-merge")) or
589 os.path.isdir(os.path.join(g, "rebase-apply")))
590
591 def _CheckClean(self, rev_str):
592 # Make sure the tree is clean; see git-rebase.sh for reference
593 try:
594 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
595 self.checkout_path, print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000596 except gclient_utils.CheckCallError:
597 raise gclient_utils.Error('\n____ %s%s\n'
598 '\tYou have unstaged changes.\n'
599 '\tPlease commit, stash, or reset.\n'
600 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000601 try:
602 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
603 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
604 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000605 except gclient_utils.CheckCallError:
606 raise gclient_utils.Error('\n____ %s%s\n'
607 '\tYour index contains uncommitted changes\n'
608 '\tPlease commit, stash, or reset.\n'
609 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000610
611 def _CheckDetachedHead(self, rev_str):
612 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
613 # reference by a commit). If not, error out -- most likely a rebase is
614 # in progress, try to detect so we can give a better error.
615 try:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000616 _, _ = scm.GIT.Capture(
msb@chromium.org786fb682010-06-02 15:16:23 +0000617 ['name-rev', '--no-undefined', 'HEAD'],
618 self.checkout_path,
619 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000620 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000621 # Commit is not contained by any rev. See if the user is rebasing:
622 if self._IsRebasing():
623 # Punt to the user
624 raise gclient_utils.Error('\n____ %s%s\n'
625 '\tAlready in a conflict, i.e. (no branch).\n'
626 '\tFix the conflict and run gclient again.\n'
627 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
628 '\tSee man git-rebase for details.\n'
629 % (self.relpath, rev_str))
630 # Let's just save off the commit so we can proceed.
631 name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"])
632 self._Run(["branch", name])
633 print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
634
msb@chromium.org5bde4852009-12-14 16:47:12 +0000635 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000636 # Returns name of current branch or None for detached HEAD
637 branch = self._Run(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
638 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000639 return None
640 return branch
641
maruel@chromium.org2de10252010-02-08 01:10:39 +0000642 def _Run(self, args, cwd=None, redirect_stdout=True):
643 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000644 if cwd is None:
645 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000646 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000647 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000648 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000649 if cwd == None:
650 cwd = self.checkout_path
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000651 cmd = [scm.GIT.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000652 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000653 logging.debug(cmd)
654 try:
655 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
656 output = sp.communicate()[0]
657 except OSError:
658 raise gclient_utils.Error("git command '%s' failed to run." %
659 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000660 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000661 raise gclient_utils.Error('git command %s returned %d' %
662 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000663 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000664 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000665
666
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000667class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000668 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000669
670 def cleanup(self, options, args, file_list):
671 """Cleanup working copy."""
672 command = ['cleanup']
673 command.extend(args)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000674 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000675
676 def diff(self, options, args, file_list):
677 # NOTE: This function does not currently modify file_list.
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000678 path = os.path.join(self._root_dir, self.relpath)
679 if not os.path.isdir(path):
680 raise gclient_utils.Error('Directory %s is not present.' % path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000681 command = ['diff']
682 command.extend(args)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000683 scm.SVN.Run(command, path)
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.org5f3eee32009-09-17 00:34:30 +0000687 assert len(args) == 1
688 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
689 try:
690 os.makedirs(export_path)
691 except OSError:
692 pass
693 assert os.path.exists(export_path)
694 command = ['export', '--force', '.']
695 command.append(export_path)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000696 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000697
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000698 def pack(self, options, args, file_list):
699 """Generates a patch file which can be applied to the root of the
700 repository."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000701 path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000702 if not os.path.isdir(path):
703 raise gclient_utils.Error('Directory %s is not present.' % path)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000704 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]
tony@chromium.org99828122010-06-04 01:41:02 +0000743 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000744 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000745 return
746
747 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000748 from_info = scm.SVN.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000749 if not from_info:
750 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
751 "directory is present. Delete the directory "
752 "and try again." %
753 checkout_path)
754
maruel@chromium.org7753d242009-10-07 17:40:24 +0000755 if options.manually_grab_svn_rev:
756 # Retrieve the current HEAD version because svn is slow at null updates.
757 if not revision:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000758 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000759 revision = str(from_info_live['Revision'])
760 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000761
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000762 if from_info['URL'] != base_url:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000763 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000764 if not to_info.get('Repository Root') or not to_info.get('UUID'):
765 # The url is invalid or the server is not accessible, it's safer to bail
766 # out right now.
767 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000768 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
769 and (from_info['UUID'] == to_info['UUID']))
770 if can_switch:
771 print("\n_____ relocating %s to a new checkout" % self.relpath)
772 # We have different roots, so check if we can switch --relocate.
773 # Subversion only permits this if the repository UUIDs match.
774 # Perform the switch --relocate, then rewrite the from_url
775 # to reflect where we "are now." (This is the same way that
776 # Subversion itself handles the metadata when switch --relocate
777 # is used.) This makes the checks below for whether we
778 # can update to a revision or have to switch to a different
779 # branch work as expected.
780 # TODO(maruel): TEST ME !
781 command = ["switch", "--relocate",
782 from_info['Repository Root'],
783 to_info['Repository Root'],
784 self.relpath]
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000785 scm.SVN.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000786 from_info['URL'] = from_info['URL'].replace(
787 from_info['Repository Root'],
788 to_info['Repository Root'])
789 else:
tony@chromium.org92920412010-06-04 05:08:56 +0000790 if scm.SVN.CaptureStatus(checkout_path) and not options.force:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000791 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
792 "don't match and there is local changes "
793 "in %s. Delete the directory and "
794 "try again." % (url, checkout_path))
795 # Ok delete it.
796 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000797 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000798 # We need to checkout.
799 command = ['checkout', url, checkout_path]
tony@chromium.org99828122010-06-04 01:41:02 +0000800 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000801 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000802 return
803
804
805 # If the provided url has a revision number that matches the revision
806 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000807 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000808 if options.verbose or not forced_revision:
809 print("\n_____ %s%s" % (self.relpath, rev_str))
810 return
811
812 command = ["update", checkout_path]
tony@chromium.org99828122010-06-04 01:41:02 +0000813 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000814 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000815
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000816 def updatesingle(self, options, args, file_list):
817 checkout_path = os.path.join(self._root_dir, self.relpath)
818 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000819 if scm.SVN.AssertVersion("1.5")[0]:
820 if not os.path.exists(os.path.join(checkout_path, '.svn')):
821 # Create an empty checkout and then update the one file we want. Future
822 # operations will only apply to the one file we checked out.
823 command = ["checkout", "--depth", "empty", self.url, checkout_path]
824 scm.SVN.Run(command, self._root_dir)
825 if os.path.exists(os.path.join(checkout_path, filename)):
826 os.remove(os.path.join(checkout_path, filename))
827 command = ["update", filename]
828 scm.SVN.RunAndGetFileList(options, command, checkout_path, file_list)
829 # After the initial checkout, we can use update as if it were any other
830 # dep.
831 self.update(options, args, file_list)
832 else:
833 # If the installed version of SVN doesn't support --depth, fallback to
834 # just exporting the file. This has the downside that revision
835 # information is not stored next to the file, so we will have to
836 # re-export the file every time we sync.
837 if not os.path.exists(checkout_path):
838 os.makedirs(checkout_path)
839 command = ["export", os.path.join(self.url, filename),
840 os.path.join(checkout_path, filename)]
tony@chromium.org99828122010-06-04 01:41:02 +0000841 command = self.AddAdditionalFlags(command, options, options.revision)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000842 scm.SVN.Run(command, self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000843
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000844 def revert(self, options, args, file_list):
845 """Reverts local modifications. Subversion specific.
846
847 All reverted files will be appended to file_list, even if Subversion
848 doesn't know about them.
849 """
850 path = os.path.join(self._root_dir, self.relpath)
851 if not os.path.isdir(path):
852 # svn revert won't work if the directory doesn't exist. It needs to
853 # checkout instead.
854 print("\n_____ %s is missing, synching instead" % self.relpath)
855 # Don't reuse the args.
856 return self.update(options, [], file_list)
857
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000858 for file_status in scm.SVN.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000859 file_path = os.path.join(path, file_status[1])
860 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000861 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000862 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000863 continue
864
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000865 if logging.getLogger().isEnabledFor(logging.INFO):
866 logging.info('%s%s' % (file[0], file[1]))
867 else:
868 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000869 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000870 logging.error('No idea what is the status of %s.\n'
871 'You just found a bug in gclient, please ping '
872 'maruel@chromium.org ASAP!' % file_path)
873 # svn revert is really stupid. It fails on inconsistent line-endings,
874 # on switched directories, etc. So take no chance and delete everything!
875 try:
876 if not os.path.exists(file_path):
877 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000878 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000879 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000880 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000881 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000882 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000883 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000884 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000885 logging.error('no idea what is %s.\nYou just found a bug in gclient'
886 ', please ping maruel@chromium.org ASAP!' % file_path)
887 except EnvironmentError:
888 logging.error('Failed to remove %s.' % file_path)
889
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000890 try:
891 # svn revert is so broken we don't even use it. Using
892 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000893 scm.SVN.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
894 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000895 except OSError, e:
896 # Maybe the directory disapeared meanwhile. We don't want it to throw an
897 # exception.
898 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000899
msb@chromium.org0f282062009-11-06 20:14:02 +0000900 def revinfo(self, options, args, file_list):
901 """Display revision"""
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000902 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000903
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000904 def runhooks(self, options, args, file_list):
905 self.status(options, args, file_list)
906
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000907 def status(self, options, args, file_list):
908 """Display status information."""
909 path = os.path.join(self._root_dir, self.relpath)
910 command = ['status']
911 command.extend(args)
912 if not os.path.isdir(path):
913 # svn status won't work if the directory doesn't exist.
914 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
915 "does not exist."
916 % (' '.join(command), path))
917 # There's no file list to retrieve.
918 else:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000919 scm.SVN.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000920
921 def FullUrlForRelativeUrl(self, url):
922 # Find the forth '/' and strip from there. A bit hackish.
923 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000924
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000925 @staticmethod
926 def AddAdditionalFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000927 """Add additional flags to command depending on what options are set.
928 command should be a list of strings that represents an svn command.
929
930 This method returns a new list to be used as a command."""
931 new_command = command[:]
932 if revision:
933 new_command.extend(['--revision', str(revision).strip()])
934 # --force was added to 'svn update' in svn 1.5.
935 if options.force and scm.SVN.AssertVersion("1.5")[0]:
936 new_command.append('--force')
937 return new_command