blob: 928ffdf1c7b736403757ae8f5694ead825bbab1e [file] [log] [blame]
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +00001# Copyright (c) 2010 The Chromium Authors. All rights reserved.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00004
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00005"""Gclient-specific SCM-specific operations."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00006
maruel@chromium.org754960e2009-09-21 12:31:05 +00007import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00008import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00009import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000010import re
11import subprocess
maruel@chromium.orgfd876172010-04-30 14:01:05 +000012import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000014import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016
17
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000018class DiffFilterer(object):
19 """Simple class which tracks which file is being diffed and
20 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000021 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000022 index_string = "Index: "
23 original_prefix = "--- "
24 working_prefix = "+++ "
25
26 def __init__(self, relpath):
27 # Note that we always use '/' as the path separator to be
28 # consistent with svn's cygwin-style output on Windows
29 self._relpath = relpath.replace("\\", "/")
30 self._current_file = ""
31 self._replacement_file = ""
32
maruel@chromium.org6e29d572010-06-04 17:32:20 +000033 def SetCurrentFile(self, current_file):
34 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000035 # Note that we always use '/' as the path separator to be
36 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000037 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000038
39 def ReplaceAndPrint(self, line):
40 print(line.replace(self._current_file, self._replacement_file))
41
42 def Filter(self, line):
43 if (line.startswith(self.index_string)):
44 self.SetCurrentFile(line[len(self.index_string):])
45 self.ReplaceAndPrint(line)
46 else:
47 if (line.startswith(self.original_prefix) or
48 line.startswith(self.working_prefix)):
49 self.ReplaceAndPrint(line)
50 else:
51 print line
52
53
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000054### SCM abstraction layer
55
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000056# Factory Method for SCM wrapper creation
57
maruel@chromium.org9eda4112010-06-11 18:56:10 +000058def GetScmName(url):
59 if url:
60 url, _ = gclient_utils.SplitUrlRevision(url)
61 if (url.startswith('git://') or url.startswith('ssh://') or
62 url.endswith('.git')):
63 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000064 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000065 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000066 return 'svn'
67 return None
68
69
70def CreateSCM(url, root_dir=None, relpath=None):
71 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000072 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000073 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000074 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000075
maruel@chromium.org9eda4112010-06-11 18:56:10 +000076 scm_name = GetScmName(url)
77 if not scm_name in SCM_MAP:
78 raise gclient_utils.Error('No SCM found for url %s' % url)
79 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000080
81
82# SCMWrapper base class
83
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000084class SCMWrapper(object):
85 """Add necessary glue between all the supported SCM.
86
msb@chromium.orgd6504212010-01-13 17:34:31 +000087 This is the abstraction layer to bind to different SCM.
88 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000089 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000090 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000091 self._root_dir = root_dir
92 if self._root_dir:
93 self._root_dir = self._root_dir.replace('/', os.sep)
94 self.relpath = relpath
95 if self.relpath:
96 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000097 if self.relpath and self._root_dir:
98 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000099
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000100 def RunCommand(self, command, options, args, file_list=None):
101 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000102 if file_list is None:
103 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000104
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000105 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
106 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000107
108 if not command in commands:
109 raise gclient_utils.Error('Unknown command %s' % command)
110
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000111 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000112 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000113 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000114
115 return getattr(self, command)(options, args, file_list)
116
117
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000118class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000119 """Wrapper for Git"""
120
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000121 @staticmethod
122 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000123 """'Cleanup' the repo.
124
125 There's no real git equivalent for the svn cleanup command, do a no-op.
126 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000127
128 def diff(self, options, args, file_list):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000129 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
130 self._Run(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000131
132 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000133 """Export a clean directory tree into the given path.
134
135 Exports into the specified directory, creating the path if it does
136 already exist.
137 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000138 assert len(args) == 1
139 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
140 if not os.path.exists(export_path):
141 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000142 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
143 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000144
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000145 def pack(self, options, args, file_list):
146 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000147 repository.
148
149 The patch file is generated from a diff of the merge base of HEAD and
150 its upstream branch.
151 """
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000152 path = os.path.join(self._root_dir, self.relpath)
153 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
154 command = ['diff', merge_base]
155 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000156 scm.GIT.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000157
msb@chromium.orge28e4982009-09-25 20:51:45 +0000158 def update(self, options, args, file_list):
159 """Runs git to update or transparently checkout the working copy.
160
161 All updated files will be appended to file_list.
162
163 Raises:
164 Error: if can't get URL for relative path.
165 """
166
167 if args:
168 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
169
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000170 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000171
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000172 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000173 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000174 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000175 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000176 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000177 # Override the revision number.
178 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000179 if not revision:
180 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000181
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000182 rev_str = ' at %s' % revision
183 files = []
184
185 printed_path = False
186 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000187 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000188 print("\n_____ %s%s" % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000189 verbose = ['--verbose']
190 printed_path = True
191
192 if revision.startswith('refs/heads/'):
193 rev_type = "branch"
194 elif revision.startswith('origin/'):
195 # For compatability with old naming, translate 'origin' to 'refs/heads'
196 revision = revision.replace('origin/', 'refs/heads/')
197 rev_type = "branch"
198 else:
199 # hash is also a tag, only make a distinction at checkout
200 rev_type = "hash"
201
msb@chromium.orge28e4982009-09-25 20:51:45 +0000202 if not os.path.exists(self.checkout_path):
msb@chromium.org786fb682010-06-02 15:16:23 +0000203 self._Clone(revision, url, options.verbose)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000204 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000205 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000206 if not verbose:
207 # Make the output a little prettier. It's nice to have some whitespace
208 # between projects when cloning.
209 print ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000210 return
211
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000212 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
213 raise gclient_utils.Error('\n____ %s%s\n'
214 '\tPath is not a git repo. No .git dir.\n'
215 '\tTo resolve:\n'
216 '\t\trm -rf %s\n'
217 '\tAnd run gclient sync again\n'
218 % (self.relpath, rev_str, self.relpath))
219
msb@chromium.org5bde4852009-12-14 16:47:12 +0000220 cur_branch = self._GetCurrentBranch()
221
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000222 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000223 # 0) HEAD is detached. Probably from our initial clone.
224 # - make sure HEAD is contained by a named ref, then update.
225 # Cases 1-4. HEAD is a branch.
226 # 1) current branch is not tracking a remote branch (could be git-svn)
227 # - try to rebase onto the new hash or branch
228 # 2) current branch is tracking a remote branch with local committed
229 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000230 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000231 # 3) current branch is tracking a remote branch w/or w/out changes,
232 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000233 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000234 # 4) current branch is tracking a remote branch, switches to a different
235 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000236 # - exit
237
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000238 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
239 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000240 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
241 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000242 if cur_branch is None:
243 upstream_branch = None
244 current_type = "detached"
245 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000246 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000247 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
248 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
249 current_type = "hash"
250 logging.debug("Current branch is not tracking an upstream (remote)"
251 " branch.")
252 elif upstream_branch.startswith('refs/remotes'):
253 current_type = "branch"
254 else:
255 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000256
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000257 # Update the remotes first so we have all the refs.
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000258 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000259 try:
msb@chromium.org42ba8622010-07-20 18:47:18 +0000260 if rev_type == "branch":
261 remote_output, remote_err = scm.GIT.Capture(
262 ['fetch'] + verbose + ['origin', revision],
263 self.checkout_path,
264 print_error=False)
265 else:
266 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000267 ['remote'] + verbose + ['update'],
268 self.checkout_path,
269 print_error=False)
270 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000271 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000272 # Hackish but at that point, git is known to work so just checking for
273 # 502 in stderr should be fine.
274 if '502' in e.stderr:
275 print str(e)
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000276 print "Sleeping 15 seconds and retrying..."
277 time.sleep(15)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000278 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000279 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000280
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000281 if verbose:
282 print remote_output.strip()
283 # git remote update prints to stderr when used with --verbose
284 print remote_err.strip()
285
286 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000287 if options.force or options.reset:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000288 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
289
msb@chromium.org786fb682010-06-02 15:16:23 +0000290 if current_type == 'detached':
291 # case 0
292 self._CheckClean(rev_str)
293 self._CheckDetachedHead(rev_str)
294 self._Run(['checkout', '--quiet', '%s^0' % revision])
295 if not printed_path:
296 print("\n_____ %s%s" % (self.relpath, rev_str))
297 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000298 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000299 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000300 # Our git-svn branch (upstream_branch) is our upstream
301 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
302 newbase=revision, printed_path=printed_path)
303 printed_path = True
304 else:
305 # Can't find a merge-base since we don't know our upstream. That makes
306 # this command VERY likely to produce a rebase failure. For now we
307 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000308 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000309 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000310 upstream_branch = revision
311 self._AttemptRebase(upstream_branch, files=files,
312 verbose=options.verbose, printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000313 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000314 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000315 # case 2
316 self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
317 newbase=revision, printed_path=printed_path)
318 printed_path = True
319 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
320 # case 4
321 new_base = revision.replace('heads', 'remotes/origin')
322 if not printed_path:
323 print("\n_____ %s%s" % (self.relpath, rev_str))
324 switch_error = ("Switching upstream branch from %s to %s\n"
325 % (upstream_branch, new_base) +
326 "Please merge or rebase manually:\n" +
327 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
328 "OR git checkout -b <some new branch> %s" % new_base)
329 raise gclient_utils.Error(switch_error)
330 else:
331 # case 3 - the default case
332 files = self._Run(['diff', upstream_branch, '--name-only']).split()
333 if verbose:
334 print "Trying fast-forward merge to branch : %s" % upstream_branch
335 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000336 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
337 upstream_branch],
338 self.checkout_path,
339 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000340 except gclient_utils.CheckCallError, e:
341 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
342 if not printed_path:
343 print("\n_____ %s%s" % (self.relpath, rev_str))
344 printed_path = True
345 while True:
346 try:
347 action = str(raw_input("Cannot fast-forward merge, attempt to "
348 "rebase? (y)es / (q)uit / (s)kip : "))
349 except ValueError:
350 gclient_utils.Error('Invalid Character')
351 continue
352 if re.match(r'yes|y', action, re.I):
353 self._AttemptRebase(upstream_branch, files,
354 verbose=options.verbose,
355 printed_path=printed_path)
356 printed_path = True
357 break
358 elif re.match(r'quit|q', action, re.I):
359 raise gclient_utils.Error("Can't fast-forward, please merge or "
360 "rebase manually.\n"
361 "cd %s && git " % self.checkout_path
362 + "rebase %s" % upstream_branch)
363 elif re.match(r'skip|s', action, re.I):
364 print "Skipping %s" % self.relpath
365 return
366 else:
367 print "Input not recognized"
368 elif re.match("error: Your local changes to '.*' would be "
369 "overwritten by merge. Aborting.\nPlease, commit your "
370 "changes or stash them before you can merge.\n",
371 e.stderr):
372 if not printed_path:
373 print("\n_____ %s%s" % (self.relpath, rev_str))
374 printed_path = True
375 raise gclient_utils.Error(e.stderr)
376 else:
377 # Some other problem happened with the merge
378 logging.error("Error during fast-forward merge in %s!" % self.relpath)
379 print e.stderr
380 raise
381 else:
382 # Fast-forward merge was successful
383 if not re.match('Already up-to-date.', merge_output) or verbose:
384 if not printed_path:
385 print("\n_____ %s%s" % (self.relpath, rev_str))
386 printed_path = True
387 print merge_output.strip()
388 if merge_err:
389 print "Merge produced error output:\n%s" % merge_err.strip()
390 if not verbose:
391 # Make the output a little prettier. It's nice to have some
392 # whitespace between projects when syncing.
393 print ""
394
395 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000396
397 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000398 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000399 raise gclient_utils.Error('\n____ %s%s\n'
400 '\nConflict while rebasing this branch.\n'
401 'Fix the conflict and run gclient again.\n'
402 'See man git-rebase for details.\n'
403 % (self.relpath, rev_str))
404
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000405 if verbose:
406 print "Checked out revision %s" % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000407
408 def revert(self, options, args, file_list):
409 """Reverts local modifications.
410
411 All reverted files will be appended to file_list.
412 """
msb@chromium.org260c6532009-10-28 03:22:35 +0000413 path = os.path.join(self._root_dir, self.relpath)
414 if not os.path.isdir(path):
415 # revert won't work if the directory doesn't exist. It needs to
416 # checkout instead.
417 print("\n_____ %s is missing, synching instead" % self.relpath)
418 # Don't reuse the args.
419 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000420
421 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000422 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000423 if not deps_revision:
424 deps_revision = default_rev
425 if deps_revision.startswith('refs/heads/'):
426 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
427
428 files = self._Run(['diff', deps_revision, '--name-only']).split()
429 self._Run(['reset', '--hard', deps_revision], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000430 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
431
msb@chromium.org0f282062009-11-06 20:14:02 +0000432 def revinfo(self, options, args, file_list):
433 """Display revision"""
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000434 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000435
msb@chromium.orge28e4982009-09-25 20:51:45 +0000436 def runhooks(self, options, args, file_list):
437 self.status(options, args, file_list)
438
439 def status(self, options, args, file_list):
440 """Display status information."""
441 if not os.path.isdir(self.checkout_path):
442 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000443 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000444 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000445 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
446 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
447 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000448 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
449
msb@chromium.orge6f78352010-01-13 17:05:33 +0000450 def FullUrlForRelativeUrl(self, url):
451 # Strip from last '/'
452 # Equivalent to unix basename
453 base_url = self.url
454 return base_url[:base_url.rfind('/')] + url
455
msb@chromium.org786fb682010-06-02 15:16:23 +0000456 def _Clone(self, revision, url, verbose=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000457 """Clone a git repository from the given URL.
458
msb@chromium.org786fb682010-06-02 15:16:23 +0000459 Once we've cloned the repo, we checkout a working branch if the specified
460 revision is a branch head. If it is a tag or a specific commit, then we
461 leave HEAD detached as it makes future updates simpler -- in this case the
462 user should first create a new branch or switch to an existing branch before
463 making changes in the repo."""
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000464 if not verbose:
465 # git clone doesn't seem to insert a newline properly before printing
466 # to stdout
467 print ""
468
469 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000470 if revision.startswith('refs/heads/'):
471 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
472 detach_head = False
473 else:
474 clone_cmd.append('--no-checkout')
475 detach_head = True
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000476 if verbose:
477 clone_cmd.append('--verbose')
478 clone_cmd.extend([url, self.checkout_path])
479
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000480 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000481 try:
482 self._Run(clone_cmd, cwd=self._root_dir, redirect_stdout=False)
483 break
484 except gclient_utils.Error, e:
485 # TODO(maruel): Hackish, should be fixed by moving _Run() to
486 # CheckCall().
487 # Too bad we don't have access to the actual output.
488 # We should check for "transfer closed with NNN bytes remaining to
489 # read". In the meantime, just make sure .git exists.
490 if (e.args[0] == 'git command clone returned 128' and
491 os.path.exists(os.path.join(self.checkout_path, '.git'))):
492 print str(e)
493 print "Retrying..."
494 continue
495 raise e
496
msb@chromium.org786fb682010-06-02 15:16:23 +0000497 if detach_head:
498 # Squelch git's very verbose detached HEAD warning and use our own
499 self._Run(['checkout', '--quiet', '%s^0' % revision])
500 print \
501 "Checked out %s to a detached HEAD. Before making any commits\n" \
502 "in this repo, you should use 'git checkout <branch>' to switch to\n" \
503 "an existing branch or use 'git checkout origin -b <branch>' to\n" \
504 "create a new branch for your work." % revision
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000505
506 def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
507 branch=None, printed_path=False):
508 """Attempt to rebase onto either upstream or, if specified, newbase."""
509 files.extend(self._Run(['diff', upstream, '--name-only']).split())
510 revision = upstream
511 if newbase:
512 revision = newbase
513 if not printed_path:
514 print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath,
515 revision)
516 printed_path = True
517 else:
518 print "Attempting rebase onto %s..." % revision
519
520 # Build the rebase command here using the args
521 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
522 rebase_cmd = ['rebase']
523 if verbose:
524 rebase_cmd.append('--verbose')
525 if newbase:
526 rebase_cmd.extend(['--onto', newbase])
527 rebase_cmd.append(upstream)
528 if branch:
529 rebase_cmd.append(branch)
530
531 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000532 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
533 self.checkout_path,
534 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000535 except gclient_utils.CheckCallError, e:
536 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
537 re.match(r'cannot rebase: your index contains uncommitted changes',
538 e.stderr):
539 while True:
540 rebase_action = str(raw_input("Cannot rebase because of unstaged "
541 "changes.\n'git reset --hard HEAD' ?\n"
542 "WARNING: destroys any uncommitted "
543 "work in your current branch!"
544 " (y)es / (q)uit / (s)how : "))
545 if re.match(r'yes|y', rebase_action, re.I):
546 self._Run(['reset', '--hard', 'HEAD'], redirect_stdout=False)
547 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000548 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
549 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000550 break
551 elif re.match(r'quit|q', rebase_action, re.I):
552 raise gclient_utils.Error("Please merge or rebase manually\n"
553 "cd %s && git " % self.checkout_path
554 + "%s" % ' '.join(rebase_cmd))
555 elif re.match(r'show|s', rebase_action, re.I):
556 print "\n%s" % e.stderr.strip()
557 continue
558 else:
559 gclient_utils.Error("Input not recognized")
560 continue
561 elif re.search(r'^CONFLICT', e.stdout, re.M):
562 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
563 "Fix the conflict and run gclient again.\n"
564 "See 'man git-rebase' for details.\n")
565 else:
566 print e.stdout.strip()
567 print "Rebase produced error output:\n%s" % e.stderr.strip()
568 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
569 "manually.\ncd %s && git " %
570 self.checkout_path
571 + "%s" % ' '.join(rebase_cmd))
572
573 print rebase_output.strip()
574 if rebase_err:
575 print "Rebase produced error output:\n%s" % rebase_err.strip()
576 if not verbose:
577 # Make the output a little prettier. It's nice to have some
578 # whitespace between projects when syncing.
579 print ""
580
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000581 @staticmethod
582 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000583 (ok, current_version) = scm.GIT.AssertVersion(min_version)
584 if not ok:
585 raise gclient_utils.Error('git version %s < minimum required %s' %
586 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000587
msb@chromium.org786fb682010-06-02 15:16:23 +0000588 def _IsRebasing(self):
589 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
590 # have a plumbing command to determine whether a rebase is in progress, so
591 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
592 g = os.path.join(self.checkout_path, '.git')
593 return (
594 os.path.isdir(os.path.join(g, "rebase-merge")) or
595 os.path.isdir(os.path.join(g, "rebase-apply")))
596
597 def _CheckClean(self, rev_str):
598 # Make sure the tree is clean; see git-rebase.sh for reference
599 try:
600 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
601 self.checkout_path, print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000602 except gclient_utils.CheckCallError:
603 raise gclient_utils.Error('\n____ %s%s\n'
604 '\tYou have unstaged changes.\n'
605 '\tPlease commit, stash, or reset.\n'
606 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000607 try:
608 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
609 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
610 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000611 except gclient_utils.CheckCallError:
612 raise gclient_utils.Error('\n____ %s%s\n'
613 '\tYour index contains uncommitted changes\n'
614 '\tPlease commit, stash, or reset.\n'
615 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000616
617 def _CheckDetachedHead(self, rev_str):
618 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
619 # reference by a commit). If not, error out -- most likely a rebase is
620 # in progress, try to detect so we can give a better error.
621 try:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000622 _, _ = scm.GIT.Capture(
msb@chromium.org786fb682010-06-02 15:16:23 +0000623 ['name-rev', '--no-undefined', 'HEAD'],
624 self.checkout_path,
625 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000626 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000627 # Commit is not contained by any rev. See if the user is rebasing:
628 if self._IsRebasing():
629 # Punt to the user
630 raise gclient_utils.Error('\n____ %s%s\n'
631 '\tAlready in a conflict, i.e. (no branch).\n'
632 '\tFix the conflict and run gclient again.\n'
633 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
634 '\tSee man git-rebase for details.\n'
635 % (self.relpath, rev_str))
636 # Let's just save off the commit so we can proceed.
637 name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"])
638 self._Run(["branch", name])
639 print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
640
msb@chromium.org5bde4852009-12-14 16:47:12 +0000641 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000642 # Returns name of current branch or None for detached HEAD
643 branch = self._Run(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
644 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000645 return None
646 return branch
647
maruel@chromium.org2de10252010-02-08 01:10:39 +0000648 def _Run(self, args, cwd=None, redirect_stdout=True):
649 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000650 if cwd is None:
651 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000652 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000653 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000654 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000655 if cwd == None:
656 cwd = self.checkout_path
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000657 cmd = [scm.GIT.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000658 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000659 logging.debug(cmd)
660 try:
661 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
662 output = sp.communicate()[0]
663 except OSError:
664 raise gclient_utils.Error("git command '%s' failed to run." %
665 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000666 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000667 raise gclient_utils.Error('git command %s returned %d' %
668 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000669 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000670 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000671
672
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000673class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000674 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000675
676 def cleanup(self, options, args, file_list):
677 """Cleanup working copy."""
678 command = ['cleanup']
679 command.extend(args)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000680 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000681
682 def diff(self, options, args, file_list):
683 # NOTE: This function does not currently modify file_list.
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000684 path = os.path.join(self._root_dir, self.relpath)
685 if not os.path.isdir(path):
686 raise gclient_utils.Error('Directory %s is not present.' % path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000687 command = ['diff']
688 command.extend(args)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000689 scm.SVN.Run(command, path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000690
691 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000692 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000693 assert len(args) == 1
694 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
695 try:
696 os.makedirs(export_path)
697 except OSError:
698 pass
699 assert os.path.exists(export_path)
700 command = ['export', '--force', '.']
701 command.append(export_path)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000702 scm.SVN.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000703
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000704 def pack(self, options, args, file_list):
705 """Generates a patch file which can be applied to the root of the
706 repository."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000707 path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000708 if not os.path.isdir(path):
709 raise gclient_utils.Error('Directory %s is not present.' % path)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000710 command = ['diff']
711 command.extend(args)
712
713 filterer = DiffFilterer(self.relpath)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000714 scm.SVN.RunAndFilterOutput(command, path, False, False, filterer.Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000715
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000716 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000717 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000718
719 All updated files will be appended to file_list.
720
721 Raises:
722 Error: if can't get URL for relative path.
723 """
724 # Only update if git is not controlling the directory.
725 checkout_path = os.path.join(self._root_dir, self.relpath)
726 git_path = os.path.join(self._root_dir, self.relpath, '.git')
727 if os.path.exists(git_path):
728 print("________ found .git directory; skipping %s" % self.relpath)
729 return
730
731 if args:
732 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
733
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000734 url, revision = gclient_utils.SplitUrlRevision(self.url)
735 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000736 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000737 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000738 if options.revision:
739 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000740 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000741 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000742 forced_revision = True
743 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000744 rev_str = ' at %s' % revision
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]
tony@chromium.org99828122010-06-04 01:41:02 +0000749 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000750 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000751 return
752
753 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000754 from_info = scm.SVN.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000755 if not from_info:
756 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
757 "directory is present. Delete the directory "
758 "and try again." %
759 checkout_path)
760
maruel@chromium.org7753d242009-10-07 17:40:24 +0000761 if options.manually_grab_svn_rev:
762 # Retrieve the current HEAD version because svn is slow at null updates.
763 if not revision:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000764 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000765 revision = str(from_info_live['Revision'])
766 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000767
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000768 if from_info['URL'] != base_url:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000769 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000770 if not to_info.get('Repository Root') or not to_info.get('UUID'):
771 # The url is invalid or the server is not accessible, it's safer to bail
772 # out right now.
773 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000774 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
775 and (from_info['UUID'] == to_info['UUID']))
776 if can_switch:
777 print("\n_____ relocating %s to a new checkout" % self.relpath)
778 # We have different roots, so check if we can switch --relocate.
779 # Subversion only permits this if the repository UUIDs match.
780 # Perform the switch --relocate, then rewrite the from_url
781 # to reflect where we "are now." (This is the same way that
782 # Subversion itself handles the metadata when switch --relocate
783 # is used.) This makes the checks below for whether we
784 # can update to a revision or have to switch to a different
785 # branch work as expected.
786 # TODO(maruel): TEST ME !
787 command = ["switch", "--relocate",
788 from_info['Repository Root'],
789 to_info['Repository Root'],
790 self.relpath]
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000791 scm.SVN.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000792 from_info['URL'] = from_info['URL'].replace(
793 from_info['Repository Root'],
794 to_info['Repository Root'])
795 else:
tony@chromium.org92920412010-06-04 05:08:56 +0000796 if scm.SVN.CaptureStatus(checkout_path) and not options.force:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000797 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
798 "don't match and there is local changes "
799 "in %s. Delete the directory and "
800 "try again." % (url, checkout_path))
801 # Ok delete it.
802 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000803 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000804 # We need to checkout.
805 command = ['checkout', url, checkout_path]
tony@chromium.org99828122010-06-04 01:41:02 +0000806 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000807 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000808 return
809
810
811 # If the provided url has a revision number that matches the revision
812 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000813 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000814 if options.verbose or not forced_revision:
815 print("\n_____ %s%s" % (self.relpath, rev_str))
816 return
817
818 command = ["update", checkout_path]
tony@chromium.org99828122010-06-04 01:41:02 +0000819 command = self.AddAdditionalFlags(command, options, revision)
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000820 scm.SVN.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000821
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000822 def updatesingle(self, options, args, file_list):
823 checkout_path = os.path.join(self._root_dir, self.relpath)
824 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000825 if scm.SVN.AssertVersion("1.5")[0]:
826 if not os.path.exists(os.path.join(checkout_path, '.svn')):
827 # Create an empty checkout and then update the one file we want. Future
828 # operations will only apply to the one file we checked out.
829 command = ["checkout", "--depth", "empty", self.url, checkout_path]
830 scm.SVN.Run(command, self._root_dir)
831 if os.path.exists(os.path.join(checkout_path, filename)):
832 os.remove(os.path.join(checkout_path, filename))
833 command = ["update", filename]
834 scm.SVN.RunAndGetFileList(options, command, checkout_path, file_list)
835 # After the initial checkout, we can use update as if it were any other
836 # dep.
837 self.update(options, args, file_list)
838 else:
839 # If the installed version of SVN doesn't support --depth, fallback to
840 # just exporting the file. This has the downside that revision
841 # information is not stored next to the file, so we will have to
842 # re-export the file every time we sync.
843 if not os.path.exists(checkout_path):
844 os.makedirs(checkout_path)
845 command = ["export", os.path.join(self.url, filename),
846 os.path.join(checkout_path, filename)]
tony@chromium.org99828122010-06-04 01:41:02 +0000847 command = self.AddAdditionalFlags(command, options, options.revision)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000848 scm.SVN.Run(command, self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000849
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000850 def revert(self, options, args, file_list):
851 """Reverts local modifications. Subversion specific.
852
853 All reverted files will be appended to file_list, even if Subversion
854 doesn't know about them.
855 """
856 path = os.path.join(self._root_dir, self.relpath)
857 if not os.path.isdir(path):
858 # svn revert won't work if the directory doesn't exist. It needs to
859 # checkout instead.
860 print("\n_____ %s is missing, synching instead" % self.relpath)
861 # Don't reuse the args.
862 return self.update(options, [], file_list)
863
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000864 for file_status in scm.SVN.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000865 file_path = os.path.join(path, file_status[1])
866 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000867 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000868 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000869 continue
870
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000871 if logging.getLogger().isEnabledFor(logging.INFO):
872 logging.info('%s%s' % (file[0], file[1]))
873 else:
874 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000875 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000876 logging.error('No idea what is the status of %s.\n'
877 'You just found a bug in gclient, please ping '
878 'maruel@chromium.org ASAP!' % file_path)
879 # svn revert is really stupid. It fails on inconsistent line-endings,
880 # on switched directories, etc. So take no chance and delete everything!
881 try:
882 if not os.path.exists(file_path):
883 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000884 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000885 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000886 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000887 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000888 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000889 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000890 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000891 logging.error('no idea what is %s.\nYou just found a bug in gclient'
892 ', please ping maruel@chromium.org ASAP!' % file_path)
893 except EnvironmentError:
894 logging.error('Failed to remove %s.' % file_path)
895
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000896 try:
897 # svn revert is so broken we don't even use it. Using
898 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000899 scm.SVN.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
900 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000901 except OSError, e:
902 # Maybe the directory disapeared meanwhile. We don't want it to throw an
903 # exception.
904 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000905
msb@chromium.org0f282062009-11-06 20:14:02 +0000906 def revinfo(self, options, args, file_list):
907 """Display revision"""
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000908 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000909
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000910 def runhooks(self, options, args, file_list):
911 self.status(options, args, file_list)
912
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000913 def status(self, options, args, file_list):
914 """Display status information."""
915 path = os.path.join(self._root_dir, self.relpath)
916 command = ['status']
917 command.extend(args)
918 if not os.path.isdir(path):
919 # svn status won't work if the directory doesn't exist.
920 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
921 "does not exist."
922 % (' '.join(command), path))
923 # There's no file list to retrieve.
924 else:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000925 scm.SVN.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000926
927 def FullUrlForRelativeUrl(self, url):
928 # Find the forth '/' and strip from there. A bit hackish.
929 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000930
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000931 @staticmethod
932 def AddAdditionalFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000933 """Add additional flags to command depending on what options are set.
934 command should be a list of strings that represents an svn command.
935
936 This method returns a new list to be used as a command."""
937 new_command = command[:]
938 if revision:
939 new_command.extend(['--revision', str(revision).strip()])
940 # --force was added to 'svn update' in svn 1.5.
941 if options.force and scm.SVN.AssertVersion("1.5")[0]:
942 new_command.append('--force')
943 return new_command