blob: c460a76d6cc3b86a593d4806f87c270e53f47f0a [file] [log] [blame]
[email protected]95f0f4e2010-05-22 00:55:261# Copyright (c) 2010 The Chromium Authors. All rights reserved.
[email protected]5aeb7dd2009-11-17 18:09:012# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
[email protected]5f3eee32009-09-17 00:34:304
[email protected]d5800f12009-11-12 20:03:435"""Gclient-specific SCM-specific operations."""
[email protected]5f3eee32009-09-17 00:34:306
[email protected]754960e2009-09-21 12:31:057import logging
[email protected]5f3eee32009-09-17 00:34:308import os
[email protected]ee4071d2009-12-22 22:25:379import posixpath
[email protected]5f3eee32009-09-17 00:34:3010import re
[email protected]fd876172010-04-30 14:01:0511import time
[email protected]5f3eee32009-09-17 00:34:3012
[email protected]5aeb7dd2009-11-17 18:09:0113import scm
[email protected]5f3eee32009-09-17 00:34:3014import gclient_utils
[email protected]5f3eee32009-09-17 00:34:3015
16
[email protected]ee4071d2009-12-22 22:25:3717class DiffFilterer(object):
18 """Simple class which tracks which file is being diffed and
19 replaces instances of its file name in the original and
[email protected]d6504212010-01-13 17:34:3120 working copy lines of the svn/git diff output."""
[email protected]ee4071d2009-12-22 22:25:3721 index_string = "Index: "
22 original_prefix = "--- "
23 working_prefix = "+++ "
24
[email protected]77e4eca2010-09-21 13:23:0725 def __init__(self, relpath):
[email protected]ee4071d2009-12-22 22:25:3726 # Note that we always use '/' as the path separator to be
27 # consistent with svn's cygwin-style output on Windows
28 self._relpath = relpath.replace("\\", "/")
29 self._current_file = ""
30 self._replacement_file = ""
31
[email protected]6e29d572010-06-04 17:32:2032 def SetCurrentFile(self, current_file):
33 self._current_file = current_file
[email protected]ee4071d2009-12-22 22:25:3734 # Note that we always use '/' as the path separator to be
35 # consistent with svn's cygwin-style output on Windows
[email protected]6e29d572010-06-04 17:32:2036 self._replacement_file = posixpath.join(self._relpath, current_file)
[email protected]ee4071d2009-12-22 22:25:3737
[email protected]f5d37bf2010-09-02 00:50:3438 def _Replace(self, line):
39 return line.replace(self._current_file, self._replacement_file)
[email protected]ee4071d2009-12-22 22:25:3740
41 def Filter(self, line):
42 if (line.startswith(self.index_string)):
43 self.SetCurrentFile(line[len(self.index_string):])
[email protected]f5d37bf2010-09-02 00:50:3444 line = self._Replace(line)
[email protected]ee4071d2009-12-22 22:25:3745 else:
46 if (line.startswith(self.original_prefix) or
47 line.startswith(self.working_prefix)):
[email protected]f5d37bf2010-09-02 00:50:3448 line = self._Replace(line)
[email protected]77e4eca2010-09-21 13:23:0749 print(line)
[email protected]ee4071d2009-12-22 22:25:3750
51
[email protected]5f3eee32009-09-17 00:34:3052### SCM abstraction layer
53
[email protected]cb5442b2009-09-22 16:51:2454# Factory Method for SCM wrapper creation
55
[email protected]9eda4112010-06-11 18:56:1056def GetScmName(url):
57 if url:
58 url, _ = gclient_utils.SplitUrlRevision(url)
59 if (url.startswith('git://') or url.startswith('ssh://') or
60 url.endswith('.git')):
61 return 'git'
[email protected]b74dca22010-06-11 20:10:4062 elif (url.startswith('http://') or url.startswith('https://') or
[email protected]54a07a22010-06-14 19:07:3963 url.startswith('svn://') or url.startswith('svn+ssh://')):
[email protected]9eda4112010-06-11 18:56:1064 return 'svn'
65 return None
66
67
68def CreateSCM(url, root_dir=None, relpath=None):
69 SCM_MAP = {
[email protected]cb5442b2009-09-22 16:51:2470 'svn' : SVNWrapper,
[email protected]e28e4982009-09-25 20:51:4571 'git' : GitWrapper,
[email protected]cb5442b2009-09-22 16:51:2472 }
[email protected]e28e4982009-09-25 20:51:4573
[email protected]9eda4112010-06-11 18:56:1074 scm_name = GetScmName(url)
75 if not scm_name in SCM_MAP:
76 raise gclient_utils.Error('No SCM found for url %s' % url)
77 return SCM_MAP[scm_name](url, root_dir, relpath)
[email protected]cb5442b2009-09-22 16:51:2478
79
80# SCMWrapper base class
81
[email protected]5f3eee32009-09-17 00:34:3082class SCMWrapper(object):
83 """Add necessary glue between all the supported SCM.
84
[email protected]d6504212010-01-13 17:34:3185 This is the abstraction layer to bind to different SCM.
86 """
[email protected]9eda4112010-06-11 18:56:1087 def __init__(self, url=None, root_dir=None, relpath=None):
[email protected]5f3eee32009-09-17 00:34:3088 self.url = url
[email protected]5e73b0c2009-09-18 19:47:4889 self._root_dir = root_dir
90 if self._root_dir:
91 self._root_dir = self._root_dir.replace('/', os.sep)
92 self.relpath = relpath
93 if self.relpath:
94 self.relpath = self.relpath.replace('/', os.sep)
[email protected]e28e4982009-09-25 20:51:4595 if self.relpath and self._root_dir:
96 self.checkout_path = os.path.join(self._root_dir, self.relpath)
[email protected]5f3eee32009-09-17 00:34:3097
[email protected]5f3eee32009-09-17 00:34:3098 def RunCommand(self, command, options, args, file_list=None):
99 # file_list will have all files that are modified appended to it.
[email protected]de754ac2009-09-17 18:04:50100 if file_list is None:
101 file_list = []
[email protected]5f3eee32009-09-17 00:34:30102
[email protected]4b5b1772010-04-08 01:52:56103 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
104 'revinfo', 'status', 'diff', 'pack', 'runhooks']
[email protected]5f3eee32009-09-17 00:34:30105
106 if not command in commands:
107 raise gclient_utils.Error('Unknown command %s' % command)
108
[email protected]cb5442b2009-09-22 16:51:24109 if not command in dir(self):
[email protected]ee4071d2009-12-22 22:25:37110 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
[email protected]9eda4112010-06-11 18:56:10111 command, self.__class__.__name__))
[email protected]cb5442b2009-09-22 16:51:24112
113 return getattr(self, command)(options, args, file_list)
114
115
[email protected]55e724e2010-03-11 19:36:49116class GitWrapper(SCMWrapper):
[email protected]e28e4982009-09-25 20:51:45117 """Wrapper for Git"""
118
[email protected]6e29d572010-06-04 17:32:20119 @staticmethod
120 def cleanup(options, args, file_list):
[email protected]d8a63782010-01-25 17:47:05121 """'Cleanup' the repo.
122
123 There's no real git equivalent for the svn cleanup command, do a no-op.
124 """
[email protected]e28e4982009-09-25 20:51:45125
126 def diff(self, options, args, file_list):
[email protected]6cafa132010-09-07 14:17:26127 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
[email protected]37e89872010-09-07 16:11:33128 self._Run(['diff', merge_base], options)
[email protected]e28e4982009-09-25 20:51:45129
130 def export(self, options, args, file_list):
[email protected]d6504212010-01-13 17:34:31131 """Export a clean directory tree into the given path.
132
133 Exports into the specified directory, creating the path if it does
134 already exist.
135 """
[email protected]e28e4982009-09-25 20:51:45136 assert len(args) == 1
137 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
138 if not os.path.exists(export_path):
139 os.makedirs(export_path)
[email protected]37e89872010-09-07 16:11:33140 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
141 options)
[email protected]e28e4982009-09-25 20:51:45142
[email protected]ee4071d2009-12-22 22:25:37143 def pack(self, options, args, file_list):
144 """Generates a patch file which can be applied to the root of the
[email protected]d6504212010-01-13 17:34:31145 repository.
146
147 The patch file is generated from a diff of the merge base of HEAD and
148 its upstream branch.
149 """
[email protected]6cafa132010-09-07 14:17:26150 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
[email protected]17d01792010-09-01 18:07:10151 gclient_utils.CheckCallAndFilter(
[email protected]8469bf92010-09-03 19:03:15152 ['git', 'diff', merge_base],
153 cwd=self.checkout_path,
[email protected]77e4eca2010-09-21 13:23:07154 filter_fn=DiffFilterer(self.relpath).Filter)
[email protected]ee4071d2009-12-22 22:25:37155
[email protected]e28e4982009-09-25 20:51:45156 def update(self, options, args, file_list):
157 """Runs git to update or transparently checkout the working copy.
158
159 All updated files will be appended to file_list.
160
161 Raises:
162 Error: if can't get URL for relative path.
163 """
[email protected]e28e4982009-09-25 20:51:45164 if args:
165 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
166
[email protected]ece406f2010-02-23 17:29:15167 self._CheckMinVersion("1.6.6")
[email protected]923a0372009-12-11 20:42:43168
[email protected]d90ba3f2010-02-23 14:42:57169 default_rev = "refs/heads/master"
[email protected]7080e942010-03-15 15:06:16170 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]ac915bb2009-11-13 17:03:01171 rev_str = ""
[email protected]7080e942010-03-15 15:06:16172 revision = deps_revision
[email protected]e28e4982009-09-25 20:51:45173 if options.revision:
[email protected]ac915bb2009-11-13 17:03:01174 # Override the revision number.
175 revision = str(options.revision)
[email protected]d90ba3f2010-02-23 14:42:57176 if not revision:
177 revision = default_rev
[email protected]e28e4982009-09-25 20:51:45178
[email protected]d90ba3f2010-02-23 14:42:57179 rev_str = ' at %s' % revision
180 files = []
181
182 printed_path = False
183 verbose = []
[email protected]b1a22bf2009-11-07 02:33:50184 if options.verbose:
[email protected]77e4eca2010-09-21 13:23:07185 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57186 verbose = ['--verbose']
187 printed_path = True
188
189 if revision.startswith('refs/heads/'):
190 rev_type = "branch"
191 elif revision.startswith('origin/'):
192 # For compatability with old naming, translate 'origin' to 'refs/heads'
193 revision = revision.replace('origin/', 'refs/heads/')
194 rev_type = "branch"
195 else:
196 # hash is also a tag, only make a distinction at checkout
197 rev_type = "hash"
198
[email protected]e28e4982009-09-25 20:51:45199 if not os.path.exists(self.checkout_path):
[email protected]f5d37bf2010-09-02 00:50:34200 self._Clone(revision, url, options)
[email protected]6cafa132010-09-07 14:17:26201 files = self._Capture(['ls-files']).split()
[email protected]e28e4982009-09-25 20:51:45202 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]d90ba3f2010-02-23 14:42:57203 if not verbose:
204 # Make the output a little prettier. It's nice to have some whitespace
205 # between projects when cloning.
[email protected]77e4eca2010-09-21 13:23:07206 print('')
[email protected]e28e4982009-09-25 20:51:45207 return
208
[email protected]e4af1ab2010-01-13 21:26:09209 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
210 raise gclient_utils.Error('\n____ %s%s\n'
211 '\tPath is not a git repo. No .git dir.\n'
212 '\tTo resolve:\n'
213 '\t\trm -rf %s\n'
214 '\tAnd run gclient sync again\n'
215 % (self.relpath, rev_str, self.relpath))
216
[email protected]5bde4852009-12-14 16:47:12217 cur_branch = self._GetCurrentBranch()
218
[email protected]d90ba3f2010-02-23 14:42:57219 # Cases:
[email protected]786fb682010-06-02 15:16:23220 # 0) HEAD is detached. Probably from our initial clone.
221 # - make sure HEAD is contained by a named ref, then update.
222 # Cases 1-4. HEAD is a branch.
223 # 1) current branch is not tracking a remote branch (could be git-svn)
224 # - try to rebase onto the new hash or branch
225 # 2) current branch is tracking a remote branch with local committed
226 # changes, but the DEPS file switched to point to a hash
[email protected]d90ba3f2010-02-23 14:42:57227 # - rebase those changes on top of the hash
[email protected]786fb682010-06-02 15:16:23228 # 3) current branch is tracking a remote branch w/or w/out changes,
229 # no switch
[email protected]d90ba3f2010-02-23 14:42:57230 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
[email protected]786fb682010-06-02 15:16:23231 # 4) current branch is tracking a remote branch, switches to a different
232 # remote branch
[email protected]d90ba3f2010-02-23 14:42:57233 # - exit
234
[email protected]81e012c2010-04-29 16:07:24235 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
236 # a tracking branch
[email protected]d90ba3f2010-02-23 14:42:57237 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
238 # or it returns None if it couldn't find an upstream
[email protected]786fb682010-06-02 15:16:23239 if cur_branch is None:
240 upstream_branch = None
241 current_type = "detached"
242 logging.debug("Detached HEAD")
[email protected]d90ba3f2010-02-23 14:42:57243 else:
[email protected]786fb682010-06-02 15:16:23244 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
245 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
246 current_type = "hash"
247 logging.debug("Current branch is not tracking an upstream (remote)"
248 " branch.")
249 elif upstream_branch.startswith('refs/remotes'):
250 current_type = "branch"
251 else:
252 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
[email protected]d90ba3f2010-02-23 14:42:57253
[email protected]0b1c2462010-03-02 00:48:14254 # Update the remotes first so we have all the refs.
[email protected]2aee22982010-09-03 14:15:25255 backoff_time = 5
[email protected]fd876172010-04-30 14:01:05256 for _ in range(10):
[email protected]0b1c2462010-03-02 00:48:14257 try:
[email protected]ad80e3b2010-09-09 14:18:28258 remote_output = scm.GIT.Capture(
[email protected]0b1c2462010-03-02 00:48:14259 ['remote'] + verbose + ['update'],
[email protected]ad80e3b2010-09-09 14:18:28260 cwd=self.checkout_path)
[email protected]0b1c2462010-03-02 00:48:14261 break
[email protected]982984e2010-05-11 20:57:49262 except gclient_utils.CheckCallError, e:
[email protected]0b1c2462010-03-02 00:48:14263 # Hackish but at that point, git is known to work so just checking for
264 # 502 in stderr should be fine.
265 if '502' in e.stderr:
[email protected]77e4eca2010-09-21 13:23:07266 print(str(e))
267 print('Sleeping %.1f seconds and retrying...' % backoff_time)
[email protected]2aee22982010-09-03 14:15:25268 time.sleep(backoff_time)
269 backoff_time *= 1.3
[email protected]0b1c2462010-03-02 00:48:14270 continue
[email protected]fd876172010-04-30 14:01:05271 raise
[email protected]0b1c2462010-03-02 00:48:14272
[email protected]d90ba3f2010-02-23 14:42:57273 if verbose:
[email protected]77e4eca2010-09-21 13:23:07274 print(remote_output.strip())
[email protected]d90ba3f2010-02-23 14:42:57275
276 # This is a big hammer, debatable if it should even be here...
[email protected]793796d2010-02-19 17:27:41277 if options.force or options.reset:
[email protected]37e89872010-09-07 16:11:33278 self._Run(['reset', '--hard', 'HEAD'], options)
[email protected]d90ba3f2010-02-23 14:42:57279
[email protected]786fb682010-06-02 15:16:23280 if current_type == 'detached':
281 # case 0
282 self._CheckClean(rev_str)
[email protected]f5d37bf2010-09-02 00:50:34283 self._CheckDetachedHead(rev_str, options)
[email protected]6cafa132010-09-07 14:17:26284 self._Capture(['checkout', '--quiet', '%s^0' % revision])
[email protected]786fb682010-06-02 15:16:23285 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07286 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23287 elif current_type == 'hash':
[email protected]d90ba3f2010-02-23 14:42:57288 # case 1
[email protected]55e724e2010-03-11 19:36:49289 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
[email protected]d90ba3f2010-02-23 14:42:57290 # Our git-svn branch (upstream_branch) is our upstream
[email protected]f5d37bf2010-09-02 00:50:34291 self._AttemptRebase(upstream_branch, files, options,
[email protected]d90ba3f2010-02-23 14:42:57292 newbase=revision, printed_path=printed_path)
293 printed_path = True
294 else:
295 # Can't find a merge-base since we don't know our upstream. That makes
296 # this command VERY likely to produce a rebase failure. For now we
297 # assume origin is our upstream since that's what the old behavior was.
[email protected]3b29de12010-03-08 18:34:28298 upstream_branch = 'origin'
[email protected]7080e942010-03-15 15:06:16299 if options.revision or deps_revision:
[email protected]3b29de12010-03-08 18:34:28300 upstream_branch = revision
[email protected]f5d37bf2010-09-02 00:50:34301 self._AttemptRebase(upstream_branch, files, options,
302 printed_path=printed_path)
[email protected]d90ba3f2010-02-23 14:42:57303 printed_path = True
[email protected]55e724e2010-03-11 19:36:49304 elif rev_type == 'hash':
[email protected]d90ba3f2010-02-23 14:42:57305 # case 2
[email protected]f5d37bf2010-09-02 00:50:34306 self._AttemptRebase(upstream_branch, files, options,
[email protected]d90ba3f2010-02-23 14:42:57307 newbase=revision, printed_path=printed_path)
308 printed_path = True
309 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
310 # case 4
311 new_base = revision.replace('heads', 'remotes/origin')
312 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07313 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57314 switch_error = ("Switching upstream branch from %s to %s\n"
315 % (upstream_branch, new_base) +
316 "Please merge or rebase manually:\n" +
317 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
318 "OR git checkout -b <some new branch> %s" % new_base)
319 raise gclient_utils.Error(switch_error)
320 else:
321 # case 3 - the default case
[email protected]6cafa132010-09-07 14:17:26322 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
[email protected]d90ba3f2010-02-23 14:42:57323 if verbose:
[email protected]77e4eca2010-09-21 13:23:07324 print('Trying fast-forward merge to branch : %s' % upstream_branch)
[email protected]d90ba3f2010-02-23 14:42:57325 try:
[email protected]ad80e3b2010-09-09 14:18:28326 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
327 cwd=self.checkout_path)
[email protected]d90ba3f2010-02-23 14:42:57328 except gclient_utils.CheckCallError, e:
329 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
330 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07331 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57332 printed_path = True
333 while True:
334 try:
[email protected]ad80e3b2010-09-09 14:18:28335 # TODO(maruel): That can't work with --jobs.
[email protected]d90ba3f2010-02-23 14:42:57336 action = str(raw_input("Cannot fast-forward merge, attempt to "
337 "rebase? (y)es / (q)uit / (s)kip : "))
338 except ValueError:
339 gclient_utils.Error('Invalid Character')
340 continue
341 if re.match(r'yes|y', action, re.I):
[email protected]f5d37bf2010-09-02 00:50:34342 self._AttemptRebase(upstream_branch, files, options,
[email protected]d90ba3f2010-02-23 14:42:57343 printed_path=printed_path)
344 printed_path = True
345 break
346 elif re.match(r'quit|q', action, re.I):
347 raise gclient_utils.Error("Can't fast-forward, please merge or "
348 "rebase manually.\n"
349 "cd %s && git " % self.checkout_path
350 + "rebase %s" % upstream_branch)
351 elif re.match(r'skip|s', action, re.I):
[email protected]77e4eca2010-09-21 13:23:07352 print('Skipping %s' % self.relpath)
[email protected]d90ba3f2010-02-23 14:42:57353 return
354 else:
[email protected]77e4eca2010-09-21 13:23:07355 print('Input not recognized')
[email protected]d90ba3f2010-02-23 14:42:57356 elif re.match("error: Your local changes to '.*' would be "
357 "overwritten by merge. Aborting.\nPlease, commit your "
358 "changes or stash them before you can merge.\n",
359 e.stderr):
360 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07361 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57362 printed_path = True
363 raise gclient_utils.Error(e.stderr)
364 else:
365 # Some other problem happened with the merge
366 logging.error("Error during fast-forward merge in %s!" % self.relpath)
[email protected]77e4eca2010-09-21 13:23:07367 print(e.stderr)
[email protected]d90ba3f2010-02-23 14:42:57368 raise
369 else:
370 # Fast-forward merge was successful
371 if not re.match('Already up-to-date.', merge_output) or verbose:
372 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07373 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]d90ba3f2010-02-23 14:42:57374 printed_path = True
[email protected]77e4eca2010-09-21 13:23:07375 print(merge_output.strip())
[email protected]d90ba3f2010-02-23 14:42:57376 if not verbose:
377 # Make the output a little prettier. It's nice to have some
378 # whitespace between projects when syncing.
[email protected]77e4eca2010-09-21 13:23:07379 print('')
[email protected]d90ba3f2010-02-23 14:42:57380
381 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]5bde4852009-12-14 16:47:12382
383 # If the rebase generated a conflict, abort and ask user to fix
[email protected]786fb682010-06-02 15:16:23384 if self._IsRebasing():
[email protected]5bde4852009-12-14 16:47:12385 raise gclient_utils.Error('\n____ %s%s\n'
386 '\nConflict while rebasing this branch.\n'
387 'Fix the conflict and run gclient again.\n'
388 'See man git-rebase for details.\n'
389 % (self.relpath, rev_str))
390
[email protected]d90ba3f2010-02-23 14:42:57391 if verbose:
[email protected]77e4eca2010-09-21 13:23:07392 print('Checked out revision %s' % self.revinfo(options, (), None))
[email protected]e28e4982009-09-25 20:51:45393
394 def revert(self, options, args, file_list):
395 """Reverts local modifications.
396
397 All reverted files will be appended to file_list.
398 """
[email protected]8469bf92010-09-03 19:03:15399 if not os.path.isdir(self.checkout_path):
[email protected]260c6532009-10-28 03:22:35400 # revert won't work if the directory doesn't exist. It needs to
401 # checkout instead.
[email protected]77e4eca2010-09-21 13:23:07402 print('\n_____ %s is missing, synching instead' % self.relpath)
[email protected]260c6532009-10-28 03:22:35403 # Don't reuse the args.
404 return self.update(options, [], file_list)
[email protected]b2b46312010-04-30 20:58:03405
406 default_rev = "refs/heads/master"
[email protected]6e29d572010-06-04 17:32:20407 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]b2b46312010-04-30 20:58:03408 if not deps_revision:
409 deps_revision = default_rev
410 if deps_revision.startswith('refs/heads/'):
411 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
412
[email protected]6cafa132010-09-07 14:17:26413 files = self._Capture(['diff', deps_revision, '--name-only']).split()
[email protected]37e89872010-09-07 16:11:33414 self._Run(['reset', '--hard', deps_revision], options)
[email protected]e28e4982009-09-25 20:51:45415 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
416
[email protected]0f282062009-11-06 20:14:02417 def revinfo(self, options, args, file_list):
[email protected]6cafa132010-09-07 14:17:26418 """Returns revision"""
419 return self._Capture(['rev-parse', 'HEAD'])
[email protected]0f282062009-11-06 20:14:02420
[email protected]e28e4982009-09-25 20:51:45421 def runhooks(self, options, args, file_list):
422 self.status(options, args, file_list)
423
424 def status(self, options, args, file_list):
425 """Display status information."""
426 if not os.path.isdir(self.checkout_path):
[email protected]77e4eca2010-09-21 13:23:07427 print(('\n________ couldn\'t run status in %s:\n'
428 'The directory does not exist.') % self.checkout_path)
[email protected]e28e4982009-09-25 20:51:45429 else:
[email protected]6cafa132010-09-07 14:17:26430 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
[email protected]37e89872010-09-07 16:11:33431 self._Run(['diff', '--name-status', merge_base], options)
[email protected]6cafa132010-09-07 14:17:26432 files = self._Capture(['diff', '--name-only', merge_base]).split()
[email protected]e28e4982009-09-25 20:51:45433 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
434
[email protected]e6f78352010-01-13 17:05:33435 def FullUrlForRelativeUrl(self, url):
436 # Strip from last '/'
437 # Equivalent to unix basename
438 base_url = self.url
439 return base_url[:base_url.rfind('/')] + url
440
[email protected]f5d37bf2010-09-02 00:50:34441 def _Clone(self, revision, url, options):
[email protected]d90ba3f2010-02-23 14:42:57442 """Clone a git repository from the given URL.
443
[email protected]786fb682010-06-02 15:16:23444 Once we've cloned the repo, we checkout a working branch if the specified
445 revision is a branch head. If it is a tag or a specific commit, then we
446 leave HEAD detached as it makes future updates simpler -- in this case the
447 user should first create a new branch or switch to an existing branch before
448 making changes in the repo."""
[email protected]f5d37bf2010-09-02 00:50:34449 if not options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57450 # git clone doesn't seem to insert a newline properly before printing
451 # to stdout
[email protected]77e4eca2010-09-21 13:23:07452 print('')
[email protected]d90ba3f2010-02-23 14:42:57453
454 clone_cmd = ['clone']
[email protected]786fb682010-06-02 15:16:23455 if revision.startswith('refs/heads/'):
456 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
457 detach_head = False
458 else:
459 clone_cmd.append('--no-checkout')
460 detach_head = True
[email protected]f5d37bf2010-09-02 00:50:34461 if options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57462 clone_cmd.append('--verbose')
463 clone_cmd.extend([url, self.checkout_path])
464
[email protected]55e724e2010-03-11 19:36:49465 for _ in range(3):
[email protected]d90ba3f2010-02-23 14:42:57466 try:
[email protected]37e89872010-09-07 16:11:33467 self._Run(clone_cmd, options, cwd=self._root_dir)
[email protected]d90ba3f2010-02-23 14:42:57468 break
469 except gclient_utils.Error, e:
470 # TODO(maruel): Hackish, should be fixed by moving _Run() to
471 # CheckCall().
472 # Too bad we don't have access to the actual output.
473 # We should check for "transfer closed with NNN bytes remaining to
474 # read". In the meantime, just make sure .git exists.
475 if (e.args[0] == 'git command clone returned 128' and
476 os.path.exists(os.path.join(self.checkout_path, '.git'))):
[email protected]77e4eca2010-09-21 13:23:07477 print(str(e))
478 print('Retrying...')
[email protected]d90ba3f2010-02-23 14:42:57479 continue
480 raise e
481
[email protected]786fb682010-06-02 15:16:23482 if detach_head:
483 # Squelch git's very verbose detached HEAD warning and use our own
[email protected]6cafa132010-09-07 14:17:26484 self._Capture(['checkout', '--quiet', '%s^0' % revision])
[email protected]77e4eca2010-09-21 13:23:07485 print(
[email protected]f5d37bf2010-09-02 00:50:34486 ('Checked out %s to a detached HEAD. Before making any commits\n'
487 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
488 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
489 'create a new branch for your work.') % revision)
[email protected]d90ba3f2010-02-23 14:42:57490
[email protected]f5d37bf2010-09-02 00:50:34491 def _AttemptRebase(self, upstream, files, options, newbase=None,
[email protected]d90ba3f2010-02-23 14:42:57492 branch=None, printed_path=False):
493 """Attempt to rebase onto either upstream or, if specified, newbase."""
[email protected]6cafa132010-09-07 14:17:26494 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
[email protected]d90ba3f2010-02-23 14:42:57495 revision = upstream
496 if newbase:
497 revision = newbase
498 if not printed_path:
[email protected]77e4eca2010-09-21 13:23:07499 print('\n_____ %s : Attempting rebase onto %s...' % (
[email protected]f5d37bf2010-09-02 00:50:34500 self.relpath, revision))
[email protected]d90ba3f2010-02-23 14:42:57501 printed_path = True
502 else:
[email protected]77e4eca2010-09-21 13:23:07503 print('Attempting rebase onto %s...' % revision)
[email protected]d90ba3f2010-02-23 14:42:57504
505 # Build the rebase command here using the args
506 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
507 rebase_cmd = ['rebase']
[email protected]f5d37bf2010-09-02 00:50:34508 if options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57509 rebase_cmd.append('--verbose')
510 if newbase:
511 rebase_cmd.extend(['--onto', newbase])
512 rebase_cmd.append(upstream)
513 if branch:
514 rebase_cmd.append(branch)
515
516 try:
[email protected]ad80e3b2010-09-09 14:18:28517 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
[email protected]d90ba3f2010-02-23 14:42:57518 except gclient_utils.CheckCallError, e:
[email protected]ad80e3b2010-09-09 14:18:28519 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
520 re.match(r'cannot rebase: your index contains uncommitted changes',
521 e.stderr)):
[email protected]d90ba3f2010-02-23 14:42:57522 while True:
523 rebase_action = str(raw_input("Cannot rebase because of unstaged "
524 "changes.\n'git reset --hard HEAD' ?\n"
525 "WARNING: destroys any uncommitted "
526 "work in your current branch!"
527 " (y)es / (q)uit / (s)how : "))
528 if re.match(r'yes|y', rebase_action, re.I):
[email protected]37e89872010-09-07 16:11:33529 self._Run(['reset', '--hard', 'HEAD'], options)
[email protected]d90ba3f2010-02-23 14:42:57530 # Should this be recursive?
[email protected]ad80e3b2010-09-09 14:18:28531 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
[email protected]d90ba3f2010-02-23 14:42:57532 break
533 elif re.match(r'quit|q', rebase_action, re.I):
534 raise gclient_utils.Error("Please merge or rebase manually\n"
535 "cd %s && git " % self.checkout_path
536 + "%s" % ' '.join(rebase_cmd))
537 elif re.match(r'show|s', rebase_action, re.I):
[email protected]77e4eca2010-09-21 13:23:07538 print('\n%s' % e.stderr.strip())
[email protected]d90ba3f2010-02-23 14:42:57539 continue
540 else:
541 gclient_utils.Error("Input not recognized")
542 continue
543 elif re.search(r'^CONFLICT', e.stdout, re.M):
544 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
545 "Fix the conflict and run gclient again.\n"
546 "See 'man git-rebase' for details.\n")
547 else:
[email protected]77e4eca2010-09-21 13:23:07548 print(e.stdout.strip())
549 print('Rebase produced error output:\n%s' % e.stderr.strip())
[email protected]d90ba3f2010-02-23 14:42:57550 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
551 "manually.\ncd %s && git " %
552 self.checkout_path
553 + "%s" % ' '.join(rebase_cmd))
554
[email protected]77e4eca2010-09-21 13:23:07555 print(rebase_output.strip())
[email protected]f5d37bf2010-09-02 00:50:34556 if not options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57557 # Make the output a little prettier. It's nice to have some
558 # whitespace between projects when syncing.
[email protected]77e4eca2010-09-21 13:23:07559 print('')
[email protected]d90ba3f2010-02-23 14:42:57560
[email protected]6e29d572010-06-04 17:32:20561 @staticmethod
562 def _CheckMinVersion(min_version):
[email protected]d0f854a2010-03-11 19:35:53563 (ok, current_version) = scm.GIT.AssertVersion(min_version)
564 if not ok:
565 raise gclient_utils.Error('git version %s < minimum required %s' %
566 (current_version, min_version))
[email protected]923a0372009-12-11 20:42:43567
[email protected]786fb682010-06-02 15:16:23568 def _IsRebasing(self):
569 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
570 # have a plumbing command to determine whether a rebase is in progress, so
571 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
572 g = os.path.join(self.checkout_path, '.git')
573 return (
574 os.path.isdir(os.path.join(g, "rebase-merge")) or
575 os.path.isdir(os.path.join(g, "rebase-apply")))
576
577 def _CheckClean(self, rev_str):
578 # Make sure the tree is clean; see git-rebase.sh for reference
579 try:
580 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
[email protected]ad80e3b2010-09-09 14:18:28581 cwd=self.checkout_path)
[email protected]6e29d572010-06-04 17:32:20582 except gclient_utils.CheckCallError:
583 raise gclient_utils.Error('\n____ %s%s\n'
584 '\tYou have unstaged changes.\n'
585 '\tPlease commit, stash, or reset.\n'
586 % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23587 try:
588 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
[email protected]ad80e3b2010-09-09 14:18:28589 '--ignore-submodules', 'HEAD', '--'],
590 cwd=self.checkout_path)
[email protected]6e29d572010-06-04 17:32:20591 except gclient_utils.CheckCallError:
592 raise gclient_utils.Error('\n____ %s%s\n'
593 '\tYour index contains uncommitted changes\n'
594 '\tPlease commit, stash, or reset.\n'
595 % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23596
[email protected]f5d37bf2010-09-02 00:50:34597 def _CheckDetachedHead(self, rev_str, options):
[email protected]786fb682010-06-02 15:16:23598 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
599 # reference by a commit). If not, error out -- most likely a rebase is
600 # in progress, try to detect so we can give a better error.
601 try:
[email protected]ad80e3b2010-09-09 14:18:28602 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
603 cwd=self.checkout_path)
[email protected]6e29d572010-06-04 17:32:20604 except gclient_utils.CheckCallError:
[email protected]786fb682010-06-02 15:16:23605 # Commit is not contained by any rev. See if the user is rebasing:
606 if self._IsRebasing():
607 # Punt to the user
608 raise gclient_utils.Error('\n____ %s%s\n'
609 '\tAlready in a conflict, i.e. (no branch).\n'
610 '\tFix the conflict and run gclient again.\n'
611 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
612 '\tSee man git-rebase for details.\n'
613 % (self.relpath, rev_str))
614 # Let's just save off the commit so we can proceed.
[email protected]6cafa132010-09-07 14:17:26615 name = ('saved-by-gclient-' +
616 self._Capture(['rev-parse', '--short', 'HEAD']))
617 self._Capture(['branch', name])
[email protected]77e4eca2010-09-21 13:23:07618 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
[email protected]f5d37bf2010-09-02 00:50:34619 name)
[email protected]786fb682010-06-02 15:16:23620
[email protected]5bde4852009-12-14 16:47:12621 def _GetCurrentBranch(self):
[email protected]786fb682010-06-02 15:16:23622 # Returns name of current branch or None for detached HEAD
[email protected]6cafa132010-09-07 14:17:26623 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
[email protected]786fb682010-06-02 15:16:23624 if branch == 'HEAD':
[email protected]5bde4852009-12-14 16:47:12625 return None
626 return branch
627
[email protected]6cafa132010-09-07 14:17:26628 def _Capture(self, args):
[email protected]ad80e3b2010-09-09 14:18:28629 return gclient_utils.CheckCall(
630 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
[email protected]6cafa132010-09-07 14:17:26631
[email protected]37e89872010-09-07 16:11:33632 def _Run(self, args, options, **kwargs):
[email protected]6cafa132010-09-07 14:17:26633 kwargs.setdefault('cwd', self.checkout_path)
[email protected]37e89872010-09-07 16:11:33634 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
[email protected]77e4eca2010-09-21 13:23:07635 always=options.verbose, **kwargs)
[email protected]e28e4982009-09-25 20:51:45636
637
[email protected]55e724e2010-03-11 19:36:49638class SVNWrapper(SCMWrapper):
[email protected]cb5442b2009-09-22 16:51:24639 """ Wrapper for SVN """
[email protected]5f3eee32009-09-17 00:34:30640
641 def cleanup(self, options, args, file_list):
642 """Cleanup working copy."""
[email protected]669600d2010-09-01 19:06:31643 self._Run(['cleanup'] + args, options)
[email protected]5f3eee32009-09-17 00:34:30644
645 def diff(self, options, args, file_list):
646 # NOTE: This function does not currently modify file_list.
[email protected]8469bf92010-09-03 19:03:15647 if not os.path.isdir(self.checkout_path):
648 raise gclient_utils.Error('Directory %s is not present.' %
649 self.checkout_path)
[email protected]669600d2010-09-01 19:06:31650 self._Run(['diff'] + args, options)
[email protected]5f3eee32009-09-17 00:34:30651
652 def export(self, options, args, file_list):
[email protected]d6504212010-01-13 17:34:31653 """Export a clean directory tree into the given path."""
[email protected]5f3eee32009-09-17 00:34:30654 assert len(args) == 1
655 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
656 try:
657 os.makedirs(export_path)
658 except OSError:
659 pass
660 assert os.path.exists(export_path)
[email protected]669600d2010-09-01 19:06:31661 self._Run(['export', '--force', '.', export_path], options)
[email protected]5f3eee32009-09-17 00:34:30662
[email protected]ee4071d2009-12-22 22:25:37663 def pack(self, options, args, file_list):
664 """Generates a patch file which can be applied to the root of the
665 repository."""
[email protected]8469bf92010-09-03 19:03:15666 if not os.path.isdir(self.checkout_path):
667 raise gclient_utils.Error('Directory %s is not present.' %
668 self.checkout_path)
669 gclient_utils.CheckCallAndFilter(
670 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
671 cwd=self.checkout_path,
672 print_stdout=False,
[email protected]77e4eca2010-09-21 13:23:07673 filter_fn=DiffFilterer(self.relpath).Filter)
[email protected]ee4071d2009-12-22 22:25:37674
[email protected]5f3eee32009-09-17 00:34:30675 def update(self, options, args, file_list):
[email protected]d6504212010-01-13 17:34:31676 """Runs svn to update or transparently checkout the working copy.
[email protected]5f3eee32009-09-17 00:34:30677
678 All updated files will be appended to file_list.
679
680 Raises:
681 Error: if can't get URL for relative path.
682 """
[email protected]21dca0e2010-10-05 00:55:12683 # Only update if git or hg is not controlling the directory.
[email protected]8469bf92010-09-03 19:03:15684 git_path = os.path.join(self.checkout_path, '.git')
[email protected]5f3eee32009-09-17 00:34:30685 if os.path.exists(git_path):
[email protected]77e4eca2010-09-21 13:23:07686 print('________ found .git directory; skipping %s' % self.relpath)
[email protected]5f3eee32009-09-17 00:34:30687 return
688
[email protected]21dca0e2010-10-05 00:55:12689 hg_path = os.path.join(self.checkout_path, '.hg')
690 if os.path.exists(hg_path):
691 print('________ found .hg directory; skipping %s' % self.relpath)
692 return
693
[email protected]5f3eee32009-09-17 00:34:30694 if args:
695 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
696
[email protected]8e0e9262010-08-17 19:20:27697 # revision is the revision to match. It is None if no revision is specified,
698 # i.e. the 'deps ain't pinned'.
[email protected]ac915bb2009-11-13 17:03:01699 url, revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]8e0e9262010-08-17 19:20:27700 # Keep the original unpinned url for reference in case the repo is switched.
[email protected]ac915bb2009-11-13 17:03:01701 base_url = url
[email protected]5f3eee32009-09-17 00:34:30702 if options.revision:
703 # Override the revision number.
[email protected]ac915bb2009-11-13 17:03:01704 revision = str(options.revision)
[email protected]5f3eee32009-09-17 00:34:30705 if revision:
[email protected]ac915bb2009-11-13 17:03:01706 forced_revision = True
[email protected]8e0e9262010-08-17 19:20:27707 # Reconstruct the url.
[email protected]ac915bb2009-11-13 17:03:01708 url = '%s@%s' % (url, revision)
[email protected]770ff9e2009-09-23 17:18:18709 rev_str = ' at %s' % revision
[email protected]8e0e9262010-08-17 19:20:27710 else:
711 forced_revision = False
712 rev_str = ''
[email protected]5f3eee32009-09-17 00:34:30713
[email protected]8469bf92010-09-03 19:03:15714 if not os.path.exists(self.checkout_path):
[email protected]5f3eee32009-09-17 00:34:30715 # We need to checkout.
[email protected]8469bf92010-09-03 19:03:15716 command = ['checkout', url, self.checkout_path]
[email protected]8e0e9262010-08-17 19:20:27717 command = self._AddAdditionalUpdateFlags(command, options, revision)
[email protected]669600d2010-09-01 19:06:31718 self._RunAndGetFileList(command, options, file_list, self._root_dir)
[email protected]5f3eee32009-09-17 00:34:30719 return
720
721 # Get the existing scm url and the revision number of the current checkout.
[email protected]54019f32010-09-09 13:50:11722 try:
723 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
724 except gclient_utils.Error:
725 raise gclient_utils.Error(
726 ('Can\'t update/checkout %s if an unversioned directory is present. '
727 'Delete the directory and try again.') % self.checkout_path)
[email protected]5f3eee32009-09-17 00:34:30728
[email protected]e407c9a2010-08-09 19:11:37729 # Look for locked directories.
[email protected]8469bf92010-09-03 19:03:15730 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
731 if [True for d in dir_info
732 if d[0][2] == 'L' and d[1] == self.checkout_path]:
[email protected]e407c9a2010-08-09 19:11:37733 # The current directory is locked, clean it up.
[email protected]669600d2010-09-01 19:06:31734 self._Run(['cleanup'], options)
[email protected]e407c9a2010-08-09 19:11:37735
[email protected]8e0e9262010-08-17 19:20:27736 # Retrieve the current HEAD version because svn is slow at null updates.
737 if options.manually_grab_svn_rev and not revision:
[email protected]54019f32010-09-09 13:50:11738 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
[email protected]8e0e9262010-08-17 19:20:27739 revision = str(from_info_live['Revision'])
740 rev_str = ' at %s' % revision
[email protected]5f3eee32009-09-17 00:34:30741
[email protected]ac915bb2009-11-13 17:03:01742 if from_info['URL'] != base_url:
[email protected]8e0e9262010-08-17 19:20:27743 # The repository url changed, need to switch.
[email protected]54019f32010-09-09 13:50:11744 try:
745 to_info = scm.SVN.CaptureInfo(url)
746 except gclient_utils.Error:
[email protected]e2ce0c72009-09-23 16:14:18747 # The url is invalid or the server is not accessible, it's safer to bail
748 # out right now.
749 raise gclient_utils.Error('This url is unreachable: %s' % url)
[email protected]5f3eee32009-09-17 00:34:30750 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
751 and (from_info['UUID'] == to_info['UUID']))
752 if can_switch:
[email protected]77e4eca2010-09-21 13:23:07753 print('\n_____ relocating %s to a new checkout' % self.relpath)
[email protected]5f3eee32009-09-17 00:34:30754 # We have different roots, so check if we can switch --relocate.
755 # Subversion only permits this if the repository UUIDs match.
756 # Perform the switch --relocate, then rewrite the from_url
757 # to reflect where we "are now." (This is the same way that
758 # Subversion itself handles the metadata when switch --relocate
759 # is used.) This makes the checks below for whether we
760 # can update to a revision or have to switch to a different
761 # branch work as expected.
762 # TODO(maruel): TEST ME !
[email protected]8e0e9262010-08-17 19:20:27763 command = ['switch', '--relocate',
[email protected]5f3eee32009-09-17 00:34:30764 from_info['Repository Root'],
765 to_info['Repository Root'],
766 self.relpath]
[email protected]669600d2010-09-01 19:06:31767 self._Run(command, options, cwd=self._root_dir)
[email protected]5f3eee32009-09-17 00:34:30768 from_info['URL'] = from_info['URL'].replace(
769 from_info['Repository Root'],
770 to_info['Repository Root'])
771 else:
[email protected]3294f522010-08-18 19:54:57772 if not options.force and not options.reset:
[email protected]86f0f952010-08-10 17:17:19773 # Look for local modifications but ignore unversioned files.
[email protected]8469bf92010-09-03 19:03:15774 for status in scm.SVN.CaptureStatus(self.checkout_path):
[email protected]86f0f952010-08-10 17:17:19775 if status[0] != '?':
776 raise gclient_utils.Error(
777 ('Can\'t switch the checkout to %s; UUID don\'t match and '
778 'there is local changes in %s. Delete the directory and '
[email protected]8469bf92010-09-03 19:03:15779 'try again.') % (url, self.checkout_path))
[email protected]5f3eee32009-09-17 00:34:30780 # Ok delete it.
[email protected]77e4eca2010-09-21 13:23:07781 print('\n_____ switching %s to a new checkout' % self.relpath)
[email protected]8469bf92010-09-03 19:03:15782 gclient_utils.RemoveDirectory(self.checkout_path)
[email protected]5f3eee32009-09-17 00:34:30783 # We need to checkout.
[email protected]8469bf92010-09-03 19:03:15784 command = ['checkout', url, self.checkout_path]
[email protected]8e0e9262010-08-17 19:20:27785 command = self._AddAdditionalUpdateFlags(command, options, revision)
[email protected]669600d2010-09-01 19:06:31786 self._RunAndGetFileList(command, options, file_list, self._root_dir)
[email protected]5f3eee32009-09-17 00:34:30787 return
788
[email protected]5f3eee32009-09-17 00:34:30789 # If the provided url has a revision number that matches the revision
790 # number of the existing directory, then we don't need to bother updating.
[email protected]2e0c6852009-09-24 00:02:07791 if not options.force and str(from_info['Revision']) == revision:
[email protected]5f3eee32009-09-17 00:34:30792 if options.verbose or not forced_revision:
[email protected]77e4eca2010-09-21 13:23:07793 print('\n_____ %s%s' % (self.relpath, rev_str))
[email protected]5f3eee32009-09-17 00:34:30794 return
795
[email protected]8469bf92010-09-03 19:03:15796 command = ['update', self.checkout_path]
[email protected]8e0e9262010-08-17 19:20:27797 command = self._AddAdditionalUpdateFlags(command, options, revision)
[email protected]669600d2010-09-01 19:06:31798 self._RunAndGetFileList(command, options, file_list, self._root_dir)
[email protected]5f3eee32009-09-17 00:34:30799
[email protected]4b5b1772010-04-08 01:52:56800 def updatesingle(self, options, args, file_list):
[email protected]4b5b1772010-04-08 01:52:56801 filename = args.pop()
[email protected]57564662010-04-14 02:35:12802 if scm.SVN.AssertVersion("1.5")[0]:
[email protected]8469bf92010-09-03 19:03:15803 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
[email protected]57564662010-04-14 02:35:12804 # Create an empty checkout and then update the one file we want. Future
805 # operations will only apply to the one file we checked out.
[email protected]8469bf92010-09-03 19:03:15806 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
[email protected]669600d2010-09-01 19:06:31807 self._Run(command, options, cwd=self._root_dir)
[email protected]8469bf92010-09-03 19:03:15808 if os.path.exists(os.path.join(self.checkout_path, filename)):
809 os.remove(os.path.join(self.checkout_path, filename))
[email protected]57564662010-04-14 02:35:12810 command = ["update", filename]
[email protected]669600d2010-09-01 19:06:31811 self._RunAndGetFileList(command, options, file_list)
[email protected]57564662010-04-14 02:35:12812 # After the initial checkout, we can use update as if it were any other
813 # dep.
814 self.update(options, args, file_list)
815 else:
816 # If the installed version of SVN doesn't support --depth, fallback to
817 # just exporting the file. This has the downside that revision
818 # information is not stored next to the file, so we will have to
819 # re-export the file every time we sync.
[email protected]8469bf92010-09-03 19:03:15820 if not os.path.exists(self.checkout_path):
821 os.makedirs(self.checkout_path)
[email protected]57564662010-04-14 02:35:12822 command = ["export", os.path.join(self.url, filename),
[email protected]8469bf92010-09-03 19:03:15823 os.path.join(self.checkout_path, filename)]
[email protected]8e0e9262010-08-17 19:20:27824 command = self._AddAdditionalUpdateFlags(command, options,
825 options.revision)
[email protected]669600d2010-09-01 19:06:31826 self._Run(command, options, cwd=self._root_dir)
[email protected]4b5b1772010-04-08 01:52:56827
[email protected]5f3eee32009-09-17 00:34:30828 def revert(self, options, args, file_list):
829 """Reverts local modifications. Subversion specific.
830
831 All reverted files will be appended to file_list, even if Subversion
832 doesn't know about them.
833 """
[email protected]8469bf92010-09-03 19:03:15834 if not os.path.isdir(self.checkout_path):
[email protected]5f3eee32009-09-17 00:34:30835 # svn revert won't work if the directory doesn't exist. It needs to
836 # checkout instead.
[email protected]77e4eca2010-09-21 13:23:07837 print('\n_____ %s is missing, synching instead' % self.relpath)
[email protected]5f3eee32009-09-17 00:34:30838 # Don't reuse the args.
839 return self.update(options, [], file_list)
840
[email protected]07ab60e2011-02-08 21:54:00841 def printcb(file_status):
842 file_list.append(file_status[1])
[email protected]aa3dd472009-09-21 19:02:48843 if logging.getLogger().isEnabledFor(logging.INFO):
[email protected]07ab60e2011-02-08 21:54:00844 logging.info('%s%s' % (file_status[0], file_status[1]))
[email protected]aa3dd472009-09-21 19:02:48845 else:
[email protected]07ab60e2011-02-08 21:54:00846 print(os.path.join(self.checkout_path, file_status[1]))
847 scm.SVN.Revert(self.checkout_path, callback=printcb)
[email protected]aa3dd472009-09-21 19:02:48848
[email protected]810a50b2009-10-05 23:03:18849 try:
850 # svn revert is so broken we don't even use it. Using
851 # "svn up --revision BASE" achieve the same effect.
[email protected]07ab60e2011-02-08 21:54:00852 # file_list will contain duplicates.
[email protected]669600d2010-09-01 19:06:31853 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
854 file_list)
[email protected]810a50b2009-10-05 23:03:18855 except OSError, e:
[email protected]07ab60e2011-02-08 21:54:00856 # Maybe the directory disapeared meanwhile. Do not throw an exception.
[email protected]810a50b2009-10-05 23:03:18857 logging.error('Failed to update:\n%s' % str(e))
[email protected]5f3eee32009-09-17 00:34:30858
[email protected]0f282062009-11-06 20:14:02859 def revinfo(self, options, args, file_list):
860 """Display revision"""
[email protected]54019f32010-09-09 13:50:11861 try:
862 return scm.SVN.CaptureRevision(self.checkout_path)
863 except gclient_utils.Error:
864 return None
[email protected]0f282062009-11-06 20:14:02865
[email protected]cb5442b2009-09-22 16:51:24866 def runhooks(self, options, args, file_list):
867 self.status(options, args, file_list)
868
[email protected]5f3eee32009-09-17 00:34:30869 def status(self, options, args, file_list):
870 """Display status information."""
[email protected]669600d2010-09-01 19:06:31871 command = ['status'] + args
[email protected]8469bf92010-09-03 19:03:15872 if not os.path.isdir(self.checkout_path):
[email protected]5f3eee32009-09-17 00:34:30873 # svn status won't work if the directory doesn't exist.
[email protected]77e4eca2010-09-21 13:23:07874 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
875 'The directory does not exist.') %
876 (' '.join(command), self.checkout_path))
[email protected]5f3eee32009-09-17 00:34:30877 # There's no file list to retrieve.
878 else:
[email protected]669600d2010-09-01 19:06:31879 self._RunAndGetFileList(command, options, file_list)
[email protected]e6f78352010-01-13 17:05:33880
881 def FullUrlForRelativeUrl(self, url):
882 # Find the forth '/' and strip from there. A bit hackish.
883 return '/'.join(self.url.split('/')[:4]) + url
[email protected]99828122010-06-04 01:41:02884
[email protected]669600d2010-09-01 19:06:31885 def _Run(self, args, options, **kwargs):
886 """Runs a commands that goes to stdout."""
[email protected]8469bf92010-09-03 19:03:15887 kwargs.setdefault('cwd', self.checkout_path)
[email protected]669600d2010-09-01 19:06:31888 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
[email protected]77e4eca2010-09-21 13:23:07889 always=options.verbose, **kwargs)
[email protected]669600d2010-09-01 19:06:31890
891 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
892 """Runs a commands that goes to stdout and grabs the file listed."""
[email protected]8469bf92010-09-03 19:03:15893 cwd = cwd or self.checkout_path
[email protected]ce117f62011-01-17 20:04:25894 scm.SVN.RunAndGetFileList(
895 options.verbose,
896 args + ['--ignore-externals'],
897 cwd=cwd,
[email protected]77e4eca2010-09-21 13:23:07898 file_list=file_list)
[email protected]669600d2010-09-01 19:06:31899
[email protected]6e29d572010-06-04 17:32:20900 @staticmethod
[email protected]8e0e9262010-08-17 19:20:27901 def _AddAdditionalUpdateFlags(command, options, revision):
[email protected]99828122010-06-04 01:41:02902 """Add additional flags to command depending on what options are set.
903 command should be a list of strings that represents an svn command.
904
905 This method returns a new list to be used as a command."""
906 new_command = command[:]
907 if revision:
908 new_command.extend(['--revision', str(revision).strip()])
909 # --force was added to 'svn update' in svn 1.5.
[email protected]8e0e9262010-08-17 19:20:27910 if ((options.force or options.manually_grab_svn_rev) and
911 scm.SVN.AssertVersion("1.5")[0]):
[email protected]99828122010-06-04 01:41:02912 new_command.append('--force')
913 return new_command