blob: 74b0281952c530cb2a92e36526d2f15d5d01a46e [file] [log] [blame]
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +00001# Copyright (c) 2010 The Chromium Authors. All rights reserved.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00004
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00005"""Gclient-specific SCM-specific operations."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00006
maruel@chromium.org754960e2009-09-21 12:31:05 +00007import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00008import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00009import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000010import re
11import subprocess
maruel@chromium.org945405e2010-08-18 17:01:49 +000012import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000013import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000014
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000015import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000017
18
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000019class DiffFilterer(object):
20 """Simple class which tracks which file is being diffed and
21 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000022 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000023 index_string = "Index: "
24 original_prefix = "--- "
25 working_prefix = "+++ "
26
27 def __init__(self, relpath):
28 # Note that we always use '/' as the path separator to be
29 # consistent with svn's cygwin-style output on Windows
30 self._relpath = relpath.replace("\\", "/")
31 self._current_file = ""
32 self._replacement_file = ""
33
maruel@chromium.org6e29d572010-06-04 17:32:20 +000034 def SetCurrentFile(self, current_file):
35 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000036 # Note that we always use '/' as the path separator to be
37 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000038 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000039
40 def ReplaceAndPrint(self, line):
41 print(line.replace(self._current_file, self._replacement_file))
42
43 def Filter(self, line):
44 if (line.startswith(self.index_string)):
45 self.SetCurrentFile(line[len(self.index_string):])
46 self.ReplaceAndPrint(line)
47 else:
48 if (line.startswith(self.original_prefix) or
49 line.startswith(self.working_prefix)):
50 self.ReplaceAndPrint(line)
51 else:
52 print line
53
54
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000055### SCM abstraction layer
56
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000057# Factory Method for SCM wrapper creation
58
maruel@chromium.org9eda4112010-06-11 18:56:10 +000059def GetScmName(url):
60 if url:
61 url, _ = gclient_utils.SplitUrlRevision(url)
62 if (url.startswith('git://') or url.startswith('ssh://') or
63 url.endswith('.git')):
64 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000065 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000066 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000067 return 'svn'
68 return None
69
70
71def CreateSCM(url, root_dir=None, relpath=None):
72 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000073 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000074 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000075 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000076
maruel@chromium.org9eda4112010-06-11 18:56:10 +000077 scm_name = GetScmName(url)
78 if not scm_name in SCM_MAP:
79 raise gclient_utils.Error('No SCM found for url %s' % url)
80 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000081
82
83# SCMWrapper base class
84
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000085class SCMWrapper(object):
86 """Add necessary glue between all the supported SCM.
87
msb@chromium.orgd6504212010-01-13 17:34:31 +000088 This is the abstraction layer to bind to different SCM.
89 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000090 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000091 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000092 self._root_dir = root_dir
93 if self._root_dir:
94 self._root_dir = self._root_dir.replace('/', os.sep)
95 self.relpath = relpath
96 if self.relpath:
97 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000098 if self.relpath and self._root_dir:
99 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000100
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000101 def RunCommand(self, command, options, args, file_list=None):
102 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000103 if file_list is None:
104 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000105
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000106 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
107 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000108
109 if not command in commands:
110 raise gclient_utils.Error('Unknown command %s' % command)
111
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000112 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000113 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000114 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000115
116 return getattr(self, command)(options, args, file_list)
117
118
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000119class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000120 """Wrapper for Git"""
121
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000122 @staticmethod
123 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000124 """'Cleanup' the repo.
125
126 There's no real git equivalent for the svn cleanup command, do a no-op.
127 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000128
129 def diff(self, options, args, file_list):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000130 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
131 self._Run(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000132
133 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000134 """Export a clean directory tree into the given path.
135
136 Exports into the specified directory, creating the path if it does
137 already exist.
138 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000139 assert len(args) == 1
140 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
141 if not os.path.exists(export_path):
142 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000143 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
144 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000145
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000146 def pack(self, options, args, file_list):
147 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000148 repository.
149
150 The patch file is generated from a diff of the merge base of HEAD and
151 its upstream branch.
152 """
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000153 path = os.path.join(self._root_dir, self.relpath)
154 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
155 command = ['diff', merge_base]
156 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000157 scm.GIT.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000158
msb@chromium.orge28e4982009-09-25 20:51:45 +0000159 def update(self, options, args, file_list):
160 """Runs git to update or transparently checkout the working copy.
161
162 All updated files will be appended to file_list.
163
164 Raises:
165 Error: if can't get URL for relative path.
166 """
167
168 if args:
169 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
170
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000171 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000172
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000173 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000174 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000175 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000176 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000177 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000178 # Override the revision number.
179 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000180 if not revision:
181 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000182
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000183 rev_str = ' at %s' % revision
184 files = []
185
186 printed_path = False
187 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000188 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000189 print("\n_____ %s%s" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000190 verbose = ['--verbose']
191 printed_path = True
192
193 if revision.startswith('refs/heads/'):
194 rev_type = "branch"
195 elif revision.startswith('origin/'):
196 # For compatability with old naming, translate 'origin' to 'refs/heads'
197 revision = revision.replace('origin/', 'refs/heads/')
198 rev_type = "branch"
199 else:
200 # hash is also a tag, only make a distinction at checkout
201 rev_type = "hash"
202
msb@chromium.orge28e4982009-09-25 20:51:45 +0000203 if not os.path.exists(self.checkout_path):
msb@chromium.org786fb682010-06-02 15:16:23 +0000204 self._Clone(revision, url, options.verbose)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000205 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000206 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000207 if not verbose:
208 # Make the output a little prettier. It's nice to have some whitespace
209 # between projects when cloning.
210 print ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000211 return
212
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000213 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
214 raise gclient_utils.Error('\n____ %s%s\n'
215 '\tPath is not a git repo. No .git dir.\n'
216 '\tTo resolve:\n'
217 '\t\trm -rf %s\n'
218 '\tAnd run gclient sync again\n'
219 % (self.relpath, rev_str, self.relpath))
220
msb@chromium.org5bde4852009-12-14 16:47:12 +0000221 cur_branch = self._GetCurrentBranch()
222
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000223 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000224 # 0) HEAD is detached. Probably from our initial clone.
225 # - make sure HEAD is contained by a named ref, then update.
226 # Cases 1-4. HEAD is a branch.
227 # 1) current branch is not tracking a remote branch (could be git-svn)
228 # - try to rebase onto the new hash or branch
229 # 2) current branch is tracking a remote branch with local committed
230 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000231 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000232 # 3) current branch is tracking a remote branch w/or w/out changes,
233 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000234 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000235 # 4) current branch is tracking a remote branch, switches to a different
236 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000237 # - exit
238
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000239 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
240 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000241 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
242 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000243 if cur_branch is None:
244 upstream_branch = None
245 current_type = "detached"
246 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000247 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000248 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
249 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
250 current_type = "hash"
251 logging.debug("Current branch is not tracking an upstream (remote)"
252 " branch.")
253 elif upstream_branch.startswith('refs/remotes'):
254 current_type = "branch"
255 else:
256 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000257
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000258 # Update the remotes first so we have all the refs.
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000259 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000260 try:
msb@chromium.org4a3bc282010-07-20 22:44:36 +0000261 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000262 ['remote'] + verbose + ['update'],
263 self.checkout_path,
264 print_error=False)
265 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000266 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000267 # Hackish but at that point, git is known to work so just checking for
268 # 502 in stderr should be fine.
269 if '502' in e.stderr:
270 print str(e)
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000271 print "Sleeping 15 seconds and retrying..."
272 time.sleep(15)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000273 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000274 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000275
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000276 if verbose:
277 print remote_output.strip()
278 # git remote update prints to stderr when used with --verbose
279 print remote_err.strip()
280
281 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000282 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000283 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
284
msb@chromium.org786fb682010-06-02 15:16:23 +0000285 if current_type == 'detached':
286 # case 0
287 self._CheckClean(rev_str)
288 self._CheckDetachedHead(rev_str)
289 self._Run(['checkout', '--quiet', '%s^0' % revision])
290 if not printed_path:
291 print("\n_____ %s%s" % (self.relpath, rev_str))
292 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000293 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000294 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000295 # Our git-svn branch (upstream_branch) is our upstream
296 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
297 newbase=revision, printed_path=printed_path)
298 printed_path = True
299 else:
300 # Can't find a merge-base since we don't know our upstream. That makes
301 # this command VERY likely to produce a rebase failure. For now we
302 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000303 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000304 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000305 upstream_branch = revision
306 self._AttemptRebase(upstream_branch, files=files,
307 verbose=options.verbose, printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000308 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000309 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000310 # case 2
311 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
312 newbase=revision, printed_path=printed_path)
313 printed_path = True
314 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
315 # case 4
316 new_base = revision.replace('heads', 'remotes/origin')
317 if not printed_path:
318 print("\n_____ %s%s" % (self.relpath, rev_str))
319 switch_error = ("Switching upstream branch from %s to %s\n"
320 % (upstream_branch, new_base) +
321 "Please merge or rebase manually:\n" +
322 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
323 "OR git checkout -b <some new branch> %s" % new_base)
324 raise gclient_utils.Error(switch_error)
325 else:
326 # case 3 - the default case
327 files = self._Run(['diff', upstream_branch, '--name-only']).split()
328 if verbose:
329 print "Trying fast-forward merge to branch : %s" % upstream_branch
330 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000331 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
332 upstream_branch],
333 self.checkout_path,
334 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000335 except gclient_utils.CheckCallError, e:
336 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
337 if not printed_path:
338 print("\n_____ %s%s" % (self.relpath, rev_str))
339 printed_path = True
340 while True:
341 try:
342 action = str(raw_input("Cannot fast-forward merge, attempt to "
343 "rebase? (y)es / (q)uit / (s)kip : "))
344 except ValueError:
345 gclient_utils.Error('Invalid Character')
346 continue
347 if re.match(r'yes|y', action, re.I):
348 self._AttemptRebase(upstream_branch, files,
349 verbose=options.verbose,
350 printed_path=printed_path)
351 printed_path = True
352 break
353 elif re.match(r'quit|q', action, re.I):
354 raise gclient_utils.Error("Can't fast-forward, please merge or "
355 "rebase manually.\n"
356 "cd %s && git " % self.checkout_path
357 + "rebase %s" % upstream_branch)
358 elif re.match(r'skip|s', action, re.I):
359 print "Skipping %s" % self.relpath
360 return
361 else:
362 print "Input not recognized"
363 elif re.match("error: Your local changes to '.*' would be "
364 "overwritten by merge. Aborting.\nPlease, commit your "
365 "changes or stash them before you can merge.\n",
366 e.stderr):
367 if not printed_path:
368 print("\n_____ %s%s" % (self.relpath, rev_str))
369 printed_path = True
370 raise gclient_utils.Error(e.stderr)
371 else:
372 # Some other problem happened with the merge
373 logging.error("Error during fast-forward merge in %s!" % self.relpath)
374 print e.stderr
375 raise
376 else:
377 # Fast-forward merge was successful
378 if not re.match('Already up-to-date.', merge_output) or verbose:
379 if not printed_path:
380 print("\n_____ %s%s" % (self.relpath, rev_str))
381 printed_path = True
382 print merge_output.strip()
383 if merge_err:
384 print "Merge produced error output:\n%s" % merge_err.strip()
385 if not verbose:
386 # Make the output a little prettier. It's nice to have some
387 # whitespace between projects when syncing.
388 print ""
389
390 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000391
392 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000393 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000394 raise gclient_utils.Error('\n____ %s%s\n'
395 '\nConflict while rebasing this branch.\n'
396 'Fix the conflict and run gclient again.\n'
397 'See man git-rebase for details.\n'
398 % (self.relpath, rev_str))
399
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000400 if verbose:
401 print "Checked out revision %s" % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000402
403 def revert(self, options, args, file_list):
404 """Reverts local modifications.
405
406 All reverted files will be appended to file_list.
407 """
msb@chromium.org260c6532009-10-28 03:22:35 +0000408 path = os.path.join(self._root_dir, self.relpath)
409 if not os.path.isdir(path):
410 # revert won't work if the directory doesn't exist. It needs to
411 # checkout instead.
412 print("\n_____ %s is missing, synching instead" % self.relpath)
413 # Don't reuse the args.
414 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000415
416 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000417 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000418 if not deps_revision:
419 deps_revision = default_rev
420 if deps_revision.startswith('refs/heads/'):
421 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
422
423 files = self._Run(['diff', deps_revision, '--name-only']).split()
424 self._Run(['reset', '--hard', deps_revision], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000425 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
426
msb@chromium.org0f282062009-11-06 20:14:02 +0000427 def revinfo(self, options, args, file_list):
428 """Display revision"""
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."""
436 if not os.path.isdir(self.checkout_path):
437 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000438 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000439 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000440 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
441 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
442 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000443 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
444
msb@chromium.orge6f78352010-01-13 17:05:33 +0000445 def FullUrlForRelativeUrl(self, url):
446 # Strip from last '/'
447 # Equivalent to unix basename
448 base_url = self.url
449 return base_url[:base_url.rfind('/')] + url
450
msb@chromium.org786fb682010-06-02 15:16:23 +0000451 def _Clone(self, revision, url, verbose=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000452 """Clone a git repository from the given URL.
453
msb@chromium.org786fb682010-06-02 15:16:23 +0000454 Once we've cloned the repo, we checkout a working branch if the specified
455 revision is a branch head. If it is a tag or a specific commit, then we
456 leave HEAD detached as it makes future updates simpler -- in this case the
457 user should first create a new branch or switch to an existing branch before
458 making changes in the repo."""
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000459 if not verbose:
460 # git clone doesn't seem to insert a newline properly before printing
461 # to stdout
462 print ""
463
464 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000465 if revision.startswith('refs/heads/'):
466 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
467 detach_head = False
468 else:
469 clone_cmd.append('--no-checkout')
470 detach_head = True
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000471 if verbose:
472 clone_cmd.append('--verbose')
473 clone_cmd.extend([url, self.checkout_path])
474
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000475 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000476 try:
477 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
478 break
479 except gclient_utils.Error, e:
480 # TODO(maruel): Hackish, should be fixed by moving _Run() to
481 # CheckCall().
482 # Too bad we don't have access to the actual output.
483 # We should check for "transfer closed with NNN bytes remaining to
484 # read". In the meantime, just make sure .git exists.
485 if (e.args[0] == 'git command clone returned 128' and
486 os.path.exists(os.path.join(self.checkout_path, '.git'))):
487 print str(e)
488 print "Retrying..."
489 continue
490 raise e
491
msb@chromium.org786fb682010-06-02 15:16:23 +0000492 if detach_head:
493 # Squelch git's very verbose detached HEAD warning and use our own
494 self._Run(['checkout', '--quiet', '%s^0' % revision])
495 print \
496 "Checked out %s to a detached HEAD. Before making any commits\n" \
497 "in this repo, you should use 'git checkout <branch>' to switch to\n" \
498 "an existing branch or use 'git checkout origin -b <branch>' to\n" \
499 "create a new branch for your work." % revision
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000500
501 def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
502 branch=None, printed_path=False):
503 """Attempt to rebase onto either upstream or, if specified, newbase."""
504 files.extend(self._Run(['diff', upstream, '--name-only']).split())
505 revision = upstream
506 if newbase:
507 revision = newbase
508 if not printed_path:
509 print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath,
510 revision)
511 printed_path = True
512 else:
513 print "Attempting rebase onto %s..." % revision
514
515 # Build the rebase command here using the args
516 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
517 rebase_cmd = ['rebase']
518 if verbose:
519 rebase_cmd.append('--verbose')
520 if newbase:
521 rebase_cmd.extend(['--onto', newbase])
522 rebase_cmd.append(upstream)
523 if branch:
524 rebase_cmd.append(branch)
525
526 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000527 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
528 self.checkout_path,
529 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000530 except gclient_utils.CheckCallError, e:
531 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
532 re.match(r'cannot rebase: your index contains uncommitted changes',
533 e.stderr):
534 while True:
535 rebase_action = str(raw_input("Cannot rebase because of unstaged "
536 "changes.\n'git reset --hard HEAD' ?\n"
537 "WARNING: destroys any uncommitted "
538 "work in your current branch!"
539 " (y)es / (q)uit / (s)how : "))
540 if re.match(r'yes|y', rebase_action, re.I):
541 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
542 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000543 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
544 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000545 break
546 elif re.match(r'quit|q', rebase_action, re.I):
547 raise gclient_utils.Error("Please merge or rebase manually\n"
548 "cd %s && git " % self.checkout_path
549 + "%s" % ' '.join(rebase_cmd))
550 elif re.match(r'show|s', rebase_action, re.I):
551 print "\n%s" % e.stderr.strip()
552 continue
553 else:
554 gclient_utils.Error("Input not recognized")
555 continue
556 elif re.search(r'^CONFLICT', e.stdout, re.M):
557 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
558 "Fix the conflict and run gclient again.\n"
559 "See 'man git-rebase' for details.\n")
560 else:
561 print e.stdout.strip()
562 print "Rebase produced error output:\n%s" % e.stderr.strip()
563 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
564 "manually.\ncd %s && git " %
565 self.checkout_path
566 + "%s" % ' '.join(rebase_cmd))
567
568 print rebase_output.strip()
569 if rebase_err:
570 print "Rebase produced error output:\n%s" % rebase_err.strip()
571 if not verbose:
572 # Make the output a little prettier. It's nice to have some
573 # whitespace between projects when syncing.
574 print ""
575
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000576 @staticmethod
577 def _CheckMinVersion(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)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000597 except gclient_utils.CheckCallError:
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))
msb@chromium.org786fb682010-06-02 15:16:23 +0000602 try:
603 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
604 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
605 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000606 except gclient_utils.CheckCallError:
607 raise gclient_utils.Error('\n____ %s%s\n'
608 '\tYour index contains uncommitted changes\n'
609 '\tPlease commit, stash, or reset.\n'
610 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000611
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:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000617 _, _ = scm.GIT.Capture(
msb@chromium.org786fb682010-06-02 15:16:23 +0000618 ['name-rev', '--no-undefined', 'HEAD'],
619 self.checkout_path,
620 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000621 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000622 # 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."""
673 command = ['cleanup']
674 command.extend(args)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000675 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000676
677 def diff(self, options, args, file_list):
678 # NOTE: This function does not currently modify file_list.
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000679 path = os.path.join(self._root_dir, self.relpath)
680 if not os.path.isdir(path):
681 raise gclient_utils.Error('Directory %s is not present.' % path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000682 command = ['diff']
683 command.extend(args)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000684 scm.SVN.Run(command, path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000685
686 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000687 """Export a clean directory tree into the given path."""
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."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000702 path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000703 if not os.path.isdir(path):
704 raise gclient_utils.Error('Directory %s is not present.' % path)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000705 command = ['diff']
706 command.extend(args)
707
708 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000709 scm.SVN.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000710
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000711 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000712 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000713
714 All updated files will be appended to file_list.
715
716 Raises:
717 Error: if can't get URL for relative path.
718 """
719 # Only update if git is not controlling the directory.
720 checkout_path = os.path.join(self._root_dir, self.relpath)
721 git_path = os.path.join(self._root_dir, self.relpath, '.git')
722 if os.path.exists(git_path):
723 print("________ found .git directory; skipping %s" % self.relpath)
724 return
725
726 if args:
727 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
728
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000729 # revision is the revision to match. It is None if no revision is specified,
730 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000731 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000732 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000733 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000734 if options.revision:
735 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000736 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000737 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000738 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000739 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000740 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000741 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000742 else:
743 forced_revision = False
744 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000745
746 if not os.path.exists(checkout_path):
747 # We need to checkout.
748 command = ['checkout', url, checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000749 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org03807072010-08-16 17:18:44 +0000750 scm.SVN.RunAndGetFileList(options.verbose, command, self._root_dir,
751 file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000752 return
753
754 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000755 from_info = scm.SVN.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000756 if not from_info:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000757 raise gclient_utils.Error(('Can\'t update/checkout %r if an unversioned '
758 'directory is present. Delete the directory '
759 'and try again.') %
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000760 checkout_path)
761
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000762 # Look for locked directories.
763 dir_info = scm.SVN.CaptureStatus(os.path.join(checkout_path, '.'))
764 if [True for d in dir_info if d[0][2] == 'L' and d[1] == checkout_path]:
765 # The current directory is locked, clean it up.
766 scm.SVN.Run(['cleanup'], checkout_path)
767
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000768 # Retrieve the current HEAD version because svn is slow at null updates.
769 if options.manually_grab_svn_rev and not revision:
770 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
771 revision = str(from_info_live['Revision'])
772 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000773
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000774 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000775 # The repository url changed, need to switch.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000776 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000777 if not to_info.get('Repository Root') or not to_info.get('UUID'):
778 # The url is invalid or the server is not accessible, it's safer to bail
779 # out right now.
780 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000781 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
782 and (from_info['UUID'] == to_info['UUID']))
783 if can_switch:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000784 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000785 # We have different roots, so check if we can switch --relocate.
786 # Subversion only permits this if the repository UUIDs match.
787 # Perform the switch --relocate, then rewrite the from_url
788 # to reflect where we "are now." (This is the same way that
789 # Subversion itself handles the metadata when switch --relocate
790 # is used.) This makes the checks below for whether we
791 # can update to a revision or have to switch to a different
792 # branch work as expected.
793 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000794 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000795 from_info['Repository Root'],
796 to_info['Repository Root'],
797 self.relpath]
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000798 scm.SVN.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000799 from_info['URL'] = from_info['URL'].replace(
800 from_info['Repository Root'],
801 to_info['Repository Root'])
802 else:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000803 if not options.force:
804 # Look for local modifications but ignore unversioned files.
805 for status in scm.SVN.CaptureStatus(checkout_path):
806 if status[0] != '?':
807 raise gclient_utils.Error(
808 ('Can\'t switch the checkout to %s; UUID don\'t match and '
809 'there is local changes in %s. Delete the directory and '
810 'try again.') % (url, checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000811 # Ok delete it.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000812 print('\n_____ switching %s to a new checkout' % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000813 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000814 # We need to checkout.
815 command = ['checkout', url, checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000816 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org03807072010-08-16 17:18:44 +0000817 scm.SVN.RunAndGetFileList(options.verbose, command, self._root_dir,
818 file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000819 return
820
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000821 # If the provided url has a revision number that matches the revision
822 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000823 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000824 if options.verbose or not forced_revision:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000825 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000826 return
827
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000828 command = ['update', checkout_path]
829 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org03807072010-08-16 17:18:44 +0000830 scm.SVN.RunAndGetFileList(options.verbose, command, self._root_dir,
831 file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000832
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000833 def updatesingle(self, options, args, file_list):
834 checkout_path = os.path.join(self._root_dir, self.relpath)
835 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000836 if scm.SVN.AssertVersion("1.5")[0]:
837 if not os.path.exists(os.path.join(checkout_path, '.svn')):
838 # Create an empty checkout and then update the one file we want. Future
839 # operations will only apply to the one file we checked out.
840 command = ["checkout", "--depth", "empty", self.url, checkout_path]
841 scm.SVN.Run(command, self._root_dir)
842 if os.path.exists(os.path.join(checkout_path, filename)):
843 os.remove(os.path.join(checkout_path, filename))
844 command = ["update", filename]
maruel@chromium.org03807072010-08-16 17:18:44 +0000845 scm.SVN.RunAndGetFileList(options.verbose, command, checkout_path,
846 file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000847 # After the initial checkout, we can use update as if it were any other
848 # dep.
849 self.update(options, args, file_list)
850 else:
851 # If the installed version of SVN doesn't support --depth, fallback to
852 # just exporting the file. This has the downside that revision
853 # information is not stored next to the file, so we will have to
854 # re-export the file every time we sync.
855 if not os.path.exists(checkout_path):
856 os.makedirs(checkout_path)
857 command = ["export", os.path.join(self.url, filename),
858 os.path.join(checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000859 command = self._AddAdditionalUpdateFlags(command, options,
860 options.revision)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000861 scm.SVN.Run(command, self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000862
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000863 def revert(self, options, args, file_list):
864 """Reverts local modifications. Subversion specific.
865
866 All reverted files will be appended to file_list, even if Subversion
867 doesn't know about them.
868 """
869 path = os.path.join(self._root_dir, self.relpath)
870 if not os.path.isdir(path):
871 # svn revert won't work if the directory doesn't exist. It needs to
872 # checkout instead.
873 print("\n_____ %s is missing, synching instead" % self.relpath)
874 # Don't reuse the args.
875 return self.update(options, [], file_list)
876
maruel@chromium.org945405e2010-08-18 17:01:49 +0000877 # Do a flush of sys.stdout every 10 secs or so otherwise it may never be
878 # flushed fast enough for buildbot.
879 last_flushed_at = time.time()
880 sys.stdout.flush()
881
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000882 for file_status in scm.SVN.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000883 file_path = os.path.join(path, file_status[1])
884 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000885 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000886 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000887 continue
888
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000889 if logging.getLogger().isEnabledFor(logging.INFO):
890 logging.info('%s%s' % (file[0], file[1]))
891 else:
892 print(file_path)
maruel@chromium.org945405e2010-08-18 17:01:49 +0000893 # Flush at least 10 seconds between line writes. We wait at least 10
894 # seconds to avoid overloading the reader that called us with output,
895 # which can slow busy readers down.
896 if (time.time() - last_flushed_at) > 10:
897 last_flushed_at = time.time()
898 sys.stdout.flush()
899
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000900 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000901 logging.error('No idea what is the status of %s.\n'
902 'You just found a bug in gclient, please ping '
903 'maruel@chromium.org ASAP!' % file_path)
904 # svn revert is really stupid. It fails on inconsistent line-endings,
905 # on switched directories, etc. So take no chance and delete everything!
906 try:
907 if not os.path.exists(file_path):
908 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000909 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000910 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000911 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000912 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000913 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000914 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000915 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000916 logging.error('no idea what is %s.\nYou just found a bug in gclient'
917 ', please ping maruel@chromium.org ASAP!' % file_path)
918 except EnvironmentError:
919 logging.error('Failed to remove %s.' % file_path)
920
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000921 try:
922 # svn revert is so broken we don't even use it. Using
923 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org03807072010-08-16 17:18:44 +0000924 scm.SVN.RunAndGetFileList(options.verbose,
925 ['update', '--revision', 'BASE'], path,
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000926 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000927 except OSError, e:
928 # Maybe the directory disapeared meanwhile. We don't want it to throw an
929 # exception.
930 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000931
msb@chromium.org0f282062009-11-06 20:14:02 +0000932 def revinfo(self, options, args, file_list):
933 """Display revision"""
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000934 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000935
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000936 def runhooks(self, options, args, file_list):
937 self.status(options, args, file_list)
938
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000939 def status(self, options, args, file_list):
940 """Display status information."""
941 path = os.path.join(self._root_dir, self.relpath)
942 command = ['status']
943 command.extend(args)
944 if not os.path.isdir(path):
945 # svn status won't work if the directory doesn't exist.
946 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
947 "does not exist."
948 % (' '.join(command), path))
949 # There's no file list to retrieve.
950 else:
maruel@chromium.org03807072010-08-16 17:18:44 +0000951 scm.SVN.RunAndGetFileList(options.verbose, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000952
953 def FullUrlForRelativeUrl(self, url):
954 # Find the forth '/' and strip from there. A bit hackish.
955 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000956
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000957 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000958 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000959 """Add additional flags to command depending on what options are set.
960 command should be a list of strings that represents an svn command.
961
962 This method returns a new list to be used as a command."""
963 new_command = command[:]
964 if revision:
965 new_command.extend(['--revision', str(revision).strip()])
966 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000967 if ((options.force or options.manually_grab_svn_rev) and
968 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000969 new_command.append('--force')
970 return new_command