blob: 50d9be7cf410aebc76d69d565a550054b84fa353 [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.org559c3f82010-08-23 19:26:08 +0000157 scm.GIT.RunAndFilterOutput(command, path, False, False, filterer.Filter,
158 stdout=options.stdout)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000159
msb@chromium.orge28e4982009-09-25 20:51:45 +0000160 def update(self, options, args, file_list):
161 """Runs git to update or transparently checkout the working copy.
162
163 All updated files will be appended to file_list.
164
165 Raises:
166 Error: if can't get URL for relative path.
167 """
168
169 if args:
170 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
171
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000172 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000173
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000174 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000175 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000176 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000177 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000178 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000179 # Override the revision number.
180 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000181 if not revision:
182 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000183
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000184 rev_str = ' at %s' % revision
185 files = []
186
187 printed_path = False
188 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000189 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000190 print("\n_____ %s%s" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000191 verbose = ['--verbose']
192 printed_path = True
193
194 if revision.startswith('refs/heads/'):
195 rev_type = "branch"
196 elif revision.startswith('origin/'):
197 # For compatability with old naming, translate 'origin' to 'refs/heads'
198 revision = revision.replace('origin/', 'refs/heads/')
199 rev_type = "branch"
200 else:
201 # hash is also a tag, only make a distinction at checkout
202 rev_type = "hash"
203
msb@chromium.orge28e4982009-09-25 20:51:45 +0000204 if not os.path.exists(self.checkout_path):
msb@chromium.org786fb682010-06-02 15:16:23 +0000205 self._Clone(revision, url, options.verbose)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000206 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000207 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000208 if not verbose:
209 # Make the output a little prettier. It's nice to have some whitespace
210 # between projects when cloning.
211 print ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000212 return
213
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000214 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
215 raise gclient_utils.Error('\n____ %s%s\n'
216 '\tPath is not a git repo. No .git dir.\n'
217 '\tTo resolve:\n'
218 '\t\trm -rf %s\n'
219 '\tAnd run gclient sync again\n'
220 % (self.relpath, rev_str, self.relpath))
221
msb@chromium.org5bde4852009-12-14 16:47:12 +0000222 cur_branch = self._GetCurrentBranch()
223
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000224 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000225 # 0) HEAD is detached. Probably from our initial clone.
226 # - make sure HEAD is contained by a named ref, then update.
227 # Cases 1-4. HEAD is a branch.
228 # 1) current branch is not tracking a remote branch (could be git-svn)
229 # - try to rebase onto the new hash or branch
230 # 2) current branch is tracking a remote branch with local committed
231 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000232 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000233 # 3) current branch is tracking a remote branch w/or w/out changes,
234 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000235 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000236 # 4) current branch is tracking a remote branch, switches to a different
237 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000238 # - exit
239
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000240 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
241 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000242 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
243 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000244 if cur_branch is None:
245 upstream_branch = None
246 current_type = "detached"
247 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000248 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000249 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
250 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
251 current_type = "hash"
252 logging.debug("Current branch is not tracking an upstream (remote)"
253 " branch.")
254 elif upstream_branch.startswith('refs/remotes'):
255 current_type = "branch"
256 else:
257 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000258
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000259 # Update the remotes first so we have all the refs.
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000260 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000261 try:
msb@chromium.org4a3bc282010-07-20 22:44:36 +0000262 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000263 ['remote'] + verbose + ['update'],
264 self.checkout_path,
265 print_error=False)
266 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000267 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000268 # Hackish but at that point, git is known to work so just checking for
269 # 502 in stderr should be fine.
270 if '502' in e.stderr:
271 print str(e)
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000272 print "Sleeping 15 seconds and retrying..."
273 time.sleep(15)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000274 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000275 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000276
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000277 if verbose:
278 print remote_output.strip()
279 # git remote update prints to stderr when used with --verbose
280 print remote_err.strip()
281
282 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000283 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000284 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
285
msb@chromium.org786fb682010-06-02 15:16:23 +0000286 if current_type == 'detached':
287 # case 0
288 self._CheckClean(rev_str)
289 self._CheckDetachedHead(rev_str)
290 self._Run(['checkout', '--quiet', '%s^0' % revision])
291 if not printed_path:
292 print("\n_____ %s%s" % (self.relpath, rev_str))
293 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000294 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000295 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000296 # Our git-svn branch (upstream_branch) is our upstream
297 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
298 newbase=revision, printed_path=printed_path)
299 printed_path = True
300 else:
301 # Can't find a merge-base since we don't know our upstream. That makes
302 # this command VERY likely to produce a rebase failure. For now we
303 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000304 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000305 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000306 upstream_branch = revision
307 self._AttemptRebase(upstream_branch, files=files,
308 verbose=options.verbose, printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000309 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000310 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000311 # case 2
312 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
313 newbase=revision, printed_path=printed_path)
314 printed_path = True
315 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
316 # case 4
317 new_base = revision.replace('heads', 'remotes/origin')
318 if not printed_path:
319 print("\n_____ %s%s" % (self.relpath, rev_str))
320 switch_error = ("Switching upstream branch from %s to %s\n"
321 % (upstream_branch, new_base) +
322 "Please merge or rebase manually:\n" +
323 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
324 "OR git checkout -b <some new branch> %s" % new_base)
325 raise gclient_utils.Error(switch_error)
326 else:
327 # case 3 - the default case
328 files = self._Run(['diff', upstream_branch, '--name-only']).split()
329 if verbose:
330 print "Trying fast-forward merge to branch : %s" % upstream_branch
331 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000332 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
333 upstream_branch],
334 self.checkout_path,
335 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000336 except gclient_utils.CheckCallError, e:
337 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
338 if not printed_path:
339 print("\n_____ %s%s" % (self.relpath, rev_str))
340 printed_path = True
341 while True:
342 try:
343 action = str(raw_input("Cannot fast-forward merge, attempt to "
344 "rebase? (y)es / (q)uit / (s)kip : "))
345 except ValueError:
346 gclient_utils.Error('Invalid Character')
347 continue
348 if re.match(r'yes|y', action, re.I):
349 self._AttemptRebase(upstream_branch, files,
350 verbose=options.verbose,
351 printed_path=printed_path)
352 printed_path = True
353 break
354 elif re.match(r'quit|q', action, re.I):
355 raise gclient_utils.Error("Can't fast-forward, please merge or "
356 "rebase manually.\n"
357 "cd %s && git " % self.checkout_path
358 + "rebase %s" % upstream_branch)
359 elif re.match(r'skip|s', action, re.I):
360 print "Skipping %s" % self.relpath
361 return
362 else:
363 print "Input not recognized"
364 elif re.match("error: Your local changes to '.*' would be "
365 "overwritten by merge. Aborting.\nPlease, commit your "
366 "changes or stash them before you can merge.\n",
367 e.stderr):
368 if not printed_path:
369 print("\n_____ %s%s" % (self.relpath, rev_str))
370 printed_path = True
371 raise gclient_utils.Error(e.stderr)
372 else:
373 # Some other problem happened with the merge
374 logging.error("Error during fast-forward merge in %s!" % self.relpath)
375 print e.stderr
376 raise
377 else:
378 # Fast-forward merge was successful
379 if not re.match('Already up-to-date.', merge_output) or verbose:
380 if not printed_path:
381 print("\n_____ %s%s" % (self.relpath, rev_str))
382 printed_path = True
383 print merge_output.strip()
384 if merge_err:
385 print "Merge produced error output:\n%s" % merge_err.strip()
386 if not verbose:
387 # Make the output a little prettier. It's nice to have some
388 # whitespace between projects when syncing.
389 print ""
390
391 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000392
393 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000394 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000395 raise gclient_utils.Error('\n____ %s%s\n'
396 '\nConflict while rebasing this branch.\n'
397 'Fix the conflict and run gclient again.\n'
398 'See man git-rebase for details.\n'
399 % (self.relpath, rev_str))
400
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000401 if verbose:
402 print "Checked out revision %s" % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000403
404 def revert(self, options, args, file_list):
405 """Reverts local modifications.
406
407 All reverted files will be appended to file_list.
408 """
msb@chromium.org260c6532009-10-28 03:22:35 +0000409 path = os.path.join(self._root_dir, self.relpath)
410 if not os.path.isdir(path):
411 # revert won't work if the directory doesn't exist. It needs to
412 # checkout instead.
413 print("\n_____ %s is missing, synching instead" % self.relpath)
414 # Don't reuse the args.
415 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000416
417 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000418 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000419 if not deps_revision:
420 deps_revision = default_rev
421 if deps_revision.startswith('refs/heads/'):
422 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
423
424 files = self._Run(['diff', deps_revision, '--name-only']).split()
425 self._Run(['reset', '--hard', deps_revision], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000426 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
427
msb@chromium.org0f282062009-11-06 20:14:02 +0000428 def revinfo(self, options, args, file_list):
429 """Display revision"""
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000430 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000431
msb@chromium.orge28e4982009-09-25 20:51:45 +0000432 def runhooks(self, options, args, file_list):
433 self.status(options, args, file_list)
434
435 def status(self, options, args, file_list):
436 """Display status information."""
437 if not os.path.isdir(self.checkout_path):
438 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000439 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000440 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000441 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
442 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
443 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000444 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
445
msb@chromium.orge6f78352010-01-13 17:05:33 +0000446 def FullUrlForRelativeUrl(self, url):
447 # Strip from last '/'
448 # Equivalent to unix basename
449 base_url = self.url
450 return base_url[:base_url.rfind('/')] + url
451
msb@chromium.org786fb682010-06-02 15:16:23 +0000452 def _Clone(self, revision, url, verbose=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000453 """Clone a git repository from the given URL.
454
msb@chromium.org786fb682010-06-02 15:16:23 +0000455 Once we've cloned the repo, we checkout a working branch if the specified
456 revision is a branch head. If it is a tag or a specific commit, then we
457 leave HEAD detached as it makes future updates simpler -- in this case the
458 user should first create a new branch or switch to an existing branch before
459 making changes in the repo."""
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000460 if not verbose:
461 # git clone doesn't seem to insert a newline properly before printing
462 # to stdout
463 print ""
464
465 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000466 if revision.startswith('refs/heads/'):
467 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
468 detach_head = False
469 else:
470 clone_cmd.append('--no-checkout')
471 detach_head = True
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000472 if verbose:
473 clone_cmd.append('--verbose')
474 clone_cmd.extend([url, self.checkout_path])
475
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000476 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000477 try:
478 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
479 break
480 except gclient_utils.Error, e:
481 # TODO(maruel): Hackish, should be fixed by moving _Run() to
482 # CheckCall().
483 # Too bad we don't have access to the actual output.
484 # We should check for "transfer closed with NNN bytes remaining to
485 # read". In the meantime, just make sure .git exists.
486 if (e.args[0] == 'git command clone returned 128' and
487 os.path.exists(os.path.join(self.checkout_path, '.git'))):
488 print str(e)
489 print "Retrying..."
490 continue
491 raise e
492
msb@chromium.org786fb682010-06-02 15:16:23 +0000493 if detach_head:
494 # Squelch git's very verbose detached HEAD warning and use our own
495 self._Run(['checkout', '--quiet', '%s^0' % revision])
496 print \
497 "Checked out %s to a detached HEAD. Before making any commits\n" \
498 "in this repo, you should use 'git checkout <branch>' to switch to\n" \
499 "an existing branch or use 'git checkout origin -b <branch>' to\n" \
500 "create a new branch for your work." % revision
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000501
502 def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
503 branch=None, printed_path=False):
504 """Attempt to rebase onto either upstream or, if specified, newbase."""
505 files.extend(self._Run(['diff', upstream, '--name-only']).split())
506 revision = upstream
507 if newbase:
508 revision = newbase
509 if not printed_path:
510 print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath,
511 revision)
512 printed_path = True
513 else:
514 print "Attempting rebase onto %s..." % revision
515
516 # Build the rebase command here using the args
517 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
518 rebase_cmd = ['rebase']
519 if verbose:
520 rebase_cmd.append('--verbose')
521 if newbase:
522 rebase_cmd.extend(['--onto', newbase])
523 rebase_cmd.append(upstream)
524 if branch:
525 rebase_cmd.append(branch)
526
527 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000528 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
529 self.checkout_path,
530 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000531 except gclient_utils.CheckCallError, e:
532 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
533 re.match(r'cannot rebase: your index contains uncommitted changes',
534 e.stderr):
535 while True:
536 rebase_action = str(raw_input("Cannot rebase because of unstaged "
537 "changes.\n'git reset --hard HEAD' ?\n"
538 "WARNING: destroys any uncommitted "
539 "work in your current branch!"
540 " (y)es / (q)uit / (s)how : "))
541 if re.match(r'yes|y', rebase_action, re.I):
542 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
543 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000544 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
545 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000546 break
547 elif re.match(r'quit|q', rebase_action, re.I):
548 raise gclient_utils.Error("Please merge or rebase manually\n"
549 "cd %s && git " % self.checkout_path
550 + "%s" % ' '.join(rebase_cmd))
551 elif re.match(r'show|s', rebase_action, re.I):
552 print "\n%s" % e.stderr.strip()
553 continue
554 else:
555 gclient_utils.Error("Input not recognized")
556 continue
557 elif re.search(r'^CONFLICT', e.stdout, re.M):
558 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
559 "Fix the conflict and run gclient again.\n"
560 "See 'man git-rebase' for details.\n")
561 else:
562 print e.stdout.strip()
563 print "Rebase produced error output:\n%s" % e.stderr.strip()
564 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
565 "manually.\ncd %s && git " %
566 self.checkout_path
567 + "%s" % ' '.join(rebase_cmd))
568
569 print rebase_output.strip()
570 if rebase_err:
571 print "Rebase produced error output:\n%s" % rebase_err.strip()
572 if not verbose:
573 # Make the output a little prettier. It's nice to have some
574 # whitespace between projects when syncing.
575 print ""
576
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000577 @staticmethod
578 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000579 (ok, current_version) = scm.GIT.AssertVersion(min_version)
580 if not ok:
581 raise gclient_utils.Error('git version %s < minimum required %s' %
582 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000583
msb@chromium.org786fb682010-06-02 15:16:23 +0000584 def _IsRebasing(self):
585 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
586 # have a plumbing command to determine whether a rebase is in progress, so
587 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
588 g = os.path.join(self.checkout_path, '.git')
589 return (
590 os.path.isdir(os.path.join(g, "rebase-merge")) or
591 os.path.isdir(os.path.join(g, "rebase-apply")))
592
593 def _CheckClean(self, rev_str):
594 # Make sure the tree is clean; see git-rebase.sh for reference
595 try:
596 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
597 self.checkout_path, print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000598 except gclient_utils.CheckCallError:
599 raise gclient_utils.Error('\n____ %s%s\n'
600 '\tYou have unstaged changes.\n'
601 '\tPlease commit, stash, or reset.\n'
602 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000603 try:
604 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
605 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
606 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000607 except gclient_utils.CheckCallError:
608 raise gclient_utils.Error('\n____ %s%s\n'
609 '\tYour index contains uncommitted changes\n'
610 '\tPlease commit, stash, or reset.\n'
611 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000612
613 def _CheckDetachedHead(self, rev_str):
614 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
615 # reference by a commit). If not, error out -- most likely a rebase is
616 # in progress, try to detect so we can give a better error.
617 try:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000618 _, _ = scm.GIT.Capture(
msb@chromium.org786fb682010-06-02 15:16:23 +0000619 ['name-rev', '--no-undefined', 'HEAD'],
620 self.checkout_path,
621 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000622 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000623 # Commit is not contained by any rev. See if the user is rebasing:
624 if self._IsRebasing():
625 # Punt to the user
626 raise gclient_utils.Error('\n____ %s%s\n'
627 '\tAlready in a conflict, i.e. (no branch).\n'
628 '\tFix the conflict and run gclient again.\n'
629 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
630 '\tSee man git-rebase for details.\n'
631 % (self.relpath, rev_str))
632 # Let's just save off the commit so we can proceed.
633 name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"])
634 self._Run(["branch", name])
635 print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
636
msb@chromium.org5bde4852009-12-14 16:47:12 +0000637 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000638 # Returns name of current branch or None for detached HEAD
639 branch = self._Run(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
640 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000641 return None
642 return branch
643
maruel@chromium.org2de10252010-02-08 01:10:39 +0000644 def _Run(self, args, cwd=None, redirect_stdout=True):
645 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000646 if cwd is None:
647 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000648 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000649 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000650 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000651 if cwd == None:
652 cwd = self.checkout_path
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000653 cmd = [scm.GIT.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000654 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000655 logging.debug(cmd)
656 try:
maruel@chromium.org3a292682010-08-23 18:54:55 +0000657 sp = gclient_utils.Popen(cmd, cwd=cwd, stdout=stdout)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000658 output = sp.communicate()[0]
659 except OSError:
660 raise gclient_utils.Error("git command '%s' failed to run." %
661 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000662 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000663 raise gclient_utils.Error('git command %s returned %d' %
664 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000665 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000666 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000667
668
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000669class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000670 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000671
672 def cleanup(self, options, args, file_list):
673 """Cleanup working copy."""
674 command = ['cleanup']
675 command.extend(args)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000676 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000677
678 def diff(self, options, args, file_list):
679 # NOTE: This function does not currently modify file_list.
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000680 path = os.path.join(self._root_dir, self.relpath)
681 if not os.path.isdir(path):
682 raise gclient_utils.Error('Directory %s is not present.' % path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000683 command = ['diff']
684 command.extend(args)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000685 scm.SVN.Run(command, path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000686
687 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000688 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000689 assert len(args) == 1
690 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
691 try:
692 os.makedirs(export_path)
693 except OSError:
694 pass
695 assert os.path.exists(export_path)
696 command = ['export', '--force', '.']
697 command.append(export_path)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000698 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000699
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000700 def pack(self, options, args, file_list):
701 """Generates a patch file which can be applied to the root of the
702 repository."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000703 path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000704 if not os.path.isdir(path):
705 raise gclient_utils.Error('Directory %s is not present.' % path)
kbr@chromium.org802933d2010-08-19 17:53:24 +0000706 command = ['diff', '-x', '--ignore-eol-style']
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000707 command.extend(args)
708
709 filterer = DiffFilterer(self.relpath)
maruel@chromium.org559c3f82010-08-23 19:26:08 +0000710 scm.SVN.RunAndFilterOutput(command, path, False, False, filterer.Filter,
711 stdout=options.stdout)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000712
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000713 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000714 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000715
716 All updated files will be appended to file_list.
717
718 Raises:
719 Error: if can't get URL for relative path.
720 """
721 # Only update if git is not controlling the directory.
722 checkout_path = os.path.join(self._root_dir, self.relpath)
723 git_path = os.path.join(self._root_dir, self.relpath, '.git')
724 if os.path.exists(git_path):
725 print("________ found .git directory; skipping %s" % self.relpath)
726 return
727
728 if args:
729 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
730
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000731 # revision is the revision to match. It is None if no revision is specified,
732 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000733 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000734 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000735 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000736 if options.revision:
737 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000738 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000739 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000740 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000741 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000742 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000743 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000744 else:
745 forced_revision = False
746 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000747
748 if not os.path.exists(checkout_path):
749 # We need to checkout.
750 command = ['checkout', url, checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000751 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org03807072010-08-16 17:18:44 +0000752 scm.SVN.RunAndGetFileList(options.verbose, command, self._root_dir,
753 file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000754 return
755
756 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000757 from_info = scm.SVN.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000758 if not from_info:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000759 raise gclient_utils.Error(('Can\'t update/checkout %r if an unversioned '
760 'directory is present. Delete the directory '
761 'and try again.') %
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000762 checkout_path)
763
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000764 # Look for locked directories.
765 dir_info = scm.SVN.CaptureStatus(os.path.join(checkout_path, '.'))
766 if [True for d in dir_info if d[0][2] == 'L' and d[1] == checkout_path]:
767 # The current directory is locked, clean it up.
768 scm.SVN.Run(['cleanup'], checkout_path)
769
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000770 # Retrieve the current HEAD version because svn is slow at null updates.
771 if options.manually_grab_svn_rev and not revision:
772 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
773 revision = str(from_info_live['Revision'])
774 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000775
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000776 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000777 # The repository url changed, need to switch.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000778 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000779 if not to_info.get('Repository Root') or not to_info.get('UUID'):
780 # The url is invalid or the server is not accessible, it's safer to bail
781 # out right now.
782 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000783 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
784 and (from_info['UUID'] == to_info['UUID']))
785 if can_switch:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000786 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000787 # We have different roots, so check if we can switch --relocate.
788 # Subversion only permits this if the repository UUIDs match.
789 # Perform the switch --relocate, then rewrite the from_url
790 # to reflect where we "are now." (This is the same way that
791 # Subversion itself handles the metadata when switch --relocate
792 # is used.) This makes the checks below for whether we
793 # can update to a revision or have to switch to a different
794 # branch work as expected.
795 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000796 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000797 from_info['Repository Root'],
798 to_info['Repository Root'],
799 self.relpath]
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000800 scm.SVN.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000801 from_info['URL'] = from_info['URL'].replace(
802 from_info['Repository Root'],
803 to_info['Repository Root'])
804 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000805 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000806 # Look for local modifications but ignore unversioned files.
807 for status in scm.SVN.CaptureStatus(checkout_path):
808 if status[0] != '?':
809 raise gclient_utils.Error(
810 ('Can\'t switch the checkout to %s; UUID don\'t match and '
811 'there is local changes in %s. Delete the directory and '
812 'try again.') % (url, checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000813 # Ok delete it.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000814 print('\n_____ switching %s to a new checkout' % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000815 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000816 # We need to checkout.
817 command = ['checkout', url, checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000818 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org03807072010-08-16 17:18:44 +0000819 scm.SVN.RunAndGetFileList(options.verbose, command, self._root_dir,
820 file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000821 return
822
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000823 # If the provided url has a revision number that matches the revision
824 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000825 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000826 if options.verbose or not forced_revision:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000827 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000828 return
829
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000830 command = ['update', checkout_path]
831 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org03807072010-08-16 17:18:44 +0000832 scm.SVN.RunAndGetFileList(options.verbose, command, self._root_dir,
833 file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000834
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000835 def updatesingle(self, options, args, file_list):
836 checkout_path = os.path.join(self._root_dir, self.relpath)
837 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000838 if scm.SVN.AssertVersion("1.5")[0]:
839 if not os.path.exists(os.path.join(checkout_path, '.svn')):
840 # Create an empty checkout and then update the one file we want. Future
841 # operations will only apply to the one file we checked out.
842 command = ["checkout", "--depth", "empty", self.url, checkout_path]
843 scm.SVN.Run(command, self._root_dir)
844 if os.path.exists(os.path.join(checkout_path, filename)):
845 os.remove(os.path.join(checkout_path, filename))
846 command = ["update", filename]
maruel@chromium.org03807072010-08-16 17:18:44 +0000847 scm.SVN.RunAndGetFileList(options.verbose, command, checkout_path,
848 file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000849 # After the initial checkout, we can use update as if it were any other
850 # dep.
851 self.update(options, args, file_list)
852 else:
853 # If the installed version of SVN doesn't support --depth, fallback to
854 # just exporting the file. This has the downside that revision
855 # information is not stored next to the file, so we will have to
856 # re-export the file every time we sync.
857 if not os.path.exists(checkout_path):
858 os.makedirs(checkout_path)
859 command = ["export", os.path.join(self.url, filename),
860 os.path.join(checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000861 command = self._AddAdditionalUpdateFlags(command, options,
862 options.revision)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000863 scm.SVN.Run(command, self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000864
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000865 def revert(self, options, args, file_list):
866 """Reverts local modifications. Subversion specific.
867
868 All reverted files will be appended to file_list, even if Subversion
869 doesn't know about them.
870 """
871 path = os.path.join(self._root_dir, self.relpath)
872 if not os.path.isdir(path):
873 # svn revert won't work if the directory doesn't exist. It needs to
874 # checkout instead.
875 print("\n_____ %s is missing, synching instead" % self.relpath)
876 # Don't reuse the args.
877 return self.update(options, [], file_list)
878
maruel@chromium.org945405e2010-08-18 17:01:49 +0000879 # Do a flush of sys.stdout every 10 secs or so otherwise it may never be
880 # flushed fast enough for buildbot.
881 last_flushed_at = time.time()
882 sys.stdout.flush()
883
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000884 for file_status in scm.SVN.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000885 file_path = os.path.join(path, file_status[1])
886 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000887 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000888 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000889 continue
890
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000891 if logging.getLogger().isEnabledFor(logging.INFO):
892 logging.info('%s%s' % (file[0], file[1]))
893 else:
894 print(file_path)
maruel@chromium.org945405e2010-08-18 17:01:49 +0000895 # Flush at least 10 seconds between line writes. We wait at least 10
896 # seconds to avoid overloading the reader that called us with output,
897 # which can slow busy readers down.
898 if (time.time() - last_flushed_at) > 10:
899 last_flushed_at = time.time()
900 sys.stdout.flush()
901
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000902 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000903 logging.error('No idea what is the status of %s.\n'
904 'You just found a bug in gclient, please ping '
905 'maruel@chromium.org ASAP!' % file_path)
906 # svn revert is really stupid. It fails on inconsistent line-endings,
907 # on switched directories, etc. So take no chance and delete everything!
908 try:
909 if not os.path.exists(file_path):
910 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000911 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000912 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000913 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000914 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000915 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000916 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000917 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000918 logging.error('no idea what is %s.\nYou just found a bug in gclient'
919 ', please ping maruel@chromium.org ASAP!' % file_path)
920 except EnvironmentError:
921 logging.error('Failed to remove %s.' % file_path)
922
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000923 try:
924 # svn revert is so broken we don't even use it. Using
925 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org03807072010-08-16 17:18:44 +0000926 scm.SVN.RunAndGetFileList(options.verbose,
927 ['update', '--revision', 'BASE'], path,
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000928 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000929 except OSError, e:
930 # Maybe the directory disapeared meanwhile. We don't want it to throw an
931 # exception.
932 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000933
msb@chromium.org0f282062009-11-06 20:14:02 +0000934 def revinfo(self, options, args, file_list):
935 """Display revision"""
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000936 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000937
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000938 def runhooks(self, options, args, file_list):
939 self.status(options, args, file_list)
940
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000941 def status(self, options, args, file_list):
942 """Display status information."""
943 path = os.path.join(self._root_dir, self.relpath)
944 command = ['status']
945 command.extend(args)
946 if not os.path.isdir(path):
947 # svn status won't work if the directory doesn't exist.
948 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
949 "does not exist."
950 % (' '.join(command), path))
951 # There's no file list to retrieve.
952 else:
maruel@chromium.org03807072010-08-16 17:18:44 +0000953 scm.SVN.RunAndGetFileList(options.verbose, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000954
955 def FullUrlForRelativeUrl(self, url):
956 # Find the forth '/' and strip from there. A bit hackish.
957 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000958
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000959 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000960 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000961 """Add additional flags to command depending on what options are set.
962 command should be a list of strings that represents an svn command.
963
964 This method returns a new list to be used as a command."""
965 new_command = command[:]
966 if revision:
967 new_command.extend(['--revision', str(revision).strip()])
968 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000969 if ((options.force or options.manually_grab_svn_rev) and
970 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000971 new_command.append('--force')
972 return new_command