blob: bbed0950e870850750beaf9ed98863cb3912cfde [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
maruel@chromium.org945405e2010-08-18 17:01:49 +000011import sys
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
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000026 def __init__(self, relpath, stdout):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000027 # 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 = ""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000032 self._stdout = stdout
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000033
maruel@chromium.org6e29d572010-06-04 17:32:20 +000034 def SetCurrentFile(self, current_file):
35 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000036 # Note that we always use '/' as the path separator to be
37 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000038 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000039
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000040 def _Replace(self, line):
41 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000042
43 def Filter(self, line):
44 if (line.startswith(self.index_string)):
45 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000046 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000047 else:
48 if (line.startswith(self.original_prefix) or
49 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000050 line = self._Replace(line)
51 self._stdout.write(line + '\n')
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000052
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.org6cafa132010-09-07 14:17:26 +0000129 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000130 self._Run(['diff', merge_base], options)
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.org37e89872010-09-07 16:11:33 +0000142 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
143 options)
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.org6cafa132010-09-07 14:17:26 +0000152 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000153 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000154 ['git', 'diff', merge_base],
155 cwd=self.checkout_path,
156 filter_fn=DiffFilterer(self.relpath, options.stdout).Filter,
157 stdout=options.stdout)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000158
msb@chromium.orge28e4982009-09-25 20:51:45 +0000159 def update(self, options, args, file_list):
160 """Runs git to update or transparently checkout the working copy.
161
162 All updated files will be appended to file_list.
163
164 Raises:
165 Error: if can't get URL for relative path.
166 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000167 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:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000188 options.stdout.write("\n_____ %s%s\n" % (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):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000203 self._Clone(revision, url, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000204 files = self._Capture(['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.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000209 options.stdout.write('\n')
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.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000258 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000259 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000260 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000261 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000262 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000263 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000264 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000265 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000266 # Hackish but at that point, git is known to work so just checking for
267 # 502 in stderr should be fine.
268 if '502' in e.stderr:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000269 options.stdout.write(str(e) + '\n')
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000270 options.stdout.write('Sleeping %.1f seconds and retrying...\n' %
271 backoff_time)
272 time.sleep(backoff_time)
273 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000274 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000275 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000276
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000277 if verbose:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000278 options.stdout.write(remote_output)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000279
280 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000281 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000282 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000283
msb@chromium.org786fb682010-06-02 15:16:23 +0000284 if current_type == 'detached':
285 # case 0
286 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000287 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000288 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000289 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000290 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000291 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000292 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000293 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000294 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000295 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000296 newbase=revision, printed_path=printed_path)
297 printed_path = True
298 else:
299 # Can't find a merge-base since we don't know our upstream. That makes
300 # this command VERY likely to produce a rebase failure. For now we
301 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000302 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000303 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000304 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000305 self._AttemptRebase(upstream_branch, files, options,
306 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000307 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000308 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000309 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000310 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000311 newbase=revision, printed_path=printed_path)
312 printed_path = True
313 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
314 # case 4
315 new_base = revision.replace('heads', 'remotes/origin')
316 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000317 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000318 switch_error = ("Switching upstream branch from %s to %s\n"
319 % (upstream_branch, new_base) +
320 "Please merge or rebase manually:\n" +
321 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
322 "OR git checkout -b <some new branch> %s" % new_base)
323 raise gclient_utils.Error(switch_error)
324 else:
325 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000326 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000327 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000328 options.stdout.write('Trying fast-forward merge to branch : %s\n' %
329 upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000330 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000331 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
332 cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000333 except gclient_utils.CheckCallError, e:
334 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
335 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000336 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000337 printed_path = True
338 while True:
339 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000340 # TODO(maruel): That can't work with --jobs.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000341 action = str(raw_input("Cannot fast-forward merge, attempt to "
342 "rebase? (y)es / (q)uit / (s)kip : "))
343 except ValueError:
344 gclient_utils.Error('Invalid Character')
345 continue
346 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000347 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000348 printed_path=printed_path)
349 printed_path = True
350 break
351 elif re.match(r'quit|q', action, re.I):
352 raise gclient_utils.Error("Can't fast-forward, please merge or "
353 "rebase manually.\n"
354 "cd %s && git " % self.checkout_path
355 + "rebase %s" % upstream_branch)
356 elif re.match(r'skip|s', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000357 options.stdout.write('Skipping %s\n' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000358 return
359 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000360 options.stdout.write('Input not recognized\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000361 elif re.match("error: Your local changes to '.*' would be "
362 "overwritten by merge. Aborting.\nPlease, commit your "
363 "changes or stash them before you can merge.\n",
364 e.stderr):
365 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000366 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000367 printed_path = True
368 raise gclient_utils.Error(e.stderr)
369 else:
370 # Some other problem happened with the merge
371 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000372 options.stdout.write(e.stderr + '\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000373 raise
374 else:
375 # Fast-forward merge was successful
376 if not re.match('Already up-to-date.', merge_output) or verbose:
377 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000378 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000379 printed_path = True
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000380 options.stdout.write(merge_output)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000381 if not verbose:
382 # Make the output a little prettier. It's nice to have some
383 # whitespace between projects when syncing.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000384 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000385
386 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000387
388 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000389 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000390 raise gclient_utils.Error('\n____ %s%s\n'
391 '\nConflict while rebasing this branch.\n'
392 'Fix the conflict and run gclient again.\n'
393 'See man git-rebase for details.\n'
394 % (self.relpath, rev_str))
395
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000396 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000397 options.stdout.write('Checked out revision %s\n' %
398 self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000399
400 def revert(self, options, args, file_list):
401 """Reverts local modifications.
402
403 All reverted files will be appended to file_list.
404 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000405 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000406 # revert won't work if the directory doesn't exist. It needs to
407 # checkout instead.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000408 options.stdout.write('\n_____ %s is missing, synching instead\n' %
409 self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000410 # Don't reuse the args.
411 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000412
413 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000414 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000415 if not deps_revision:
416 deps_revision = default_rev
417 if deps_revision.startswith('refs/heads/'):
418 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
419
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000420 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000421 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000422 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
423
msb@chromium.org0f282062009-11-06 20:14:02 +0000424 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000425 """Returns revision"""
426 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000427
msb@chromium.orge28e4982009-09-25 20:51:45 +0000428 def runhooks(self, options, args, file_list):
429 self.status(options, args, file_list)
430
431 def status(self, options, args, file_list):
432 """Display status information."""
433 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000434 options.stdout.write(
435 ('\n________ couldn\'t run status in %s:\nThe directory '
436 'does not exist.\n') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000437 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000438 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000439 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000440 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000441 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
442
msb@chromium.orge6f78352010-01-13 17:05:33 +0000443 def FullUrlForRelativeUrl(self, url):
444 # Strip from last '/'
445 # Equivalent to unix basename
446 base_url = self.url
447 return base_url[:base_url.rfind('/')] + url
448
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000449 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000450 """Clone a git repository from the given URL.
451
msb@chromium.org786fb682010-06-02 15:16:23 +0000452 Once we've cloned the repo, we checkout a working branch if the specified
453 revision is a branch head. If it is a tag or a specific commit, then we
454 leave HEAD detached as it makes future updates simpler -- in this case the
455 user should first create a new branch or switch to an existing branch before
456 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000457 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000458 # git clone doesn't seem to insert a newline properly before printing
459 # to stdout
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000460 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000461
462 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000463 if revision.startswith('refs/heads/'):
464 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
465 detach_head = False
466 else:
467 clone_cmd.append('--no-checkout')
468 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000469 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470 clone_cmd.append('--verbose')
471 clone_cmd.extend([url, self.checkout_path])
472
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000473 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000474 try:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000475 self._Run(clone_cmd, options, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000476 break
477 except gclient_utils.Error, e:
478 # TODO(maruel): Hackish, should be fixed by moving _Run() to
479 # CheckCall().
480 # Too bad we don't have access to the actual output.
481 # We should check for "transfer closed with NNN bytes remaining to
482 # read". In the meantime, just make sure .git exists.
483 if (e.args[0] == 'git command clone returned 128' and
484 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000485 options.stdout.write(str(e) + '\n')
486 options.stdout.write('Retrying...\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000487 continue
488 raise e
489
msb@chromium.org786fb682010-06-02 15:16:23 +0000490 if detach_head:
491 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000492 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000493 options.stdout.write(
494 ('Checked out %s to a detached HEAD. Before making any commits\n'
495 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
496 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
497 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000498
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000499 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000500 branch=None, printed_path=False):
501 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000502 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000503 revision = upstream
504 if newbase:
505 revision = newbase
506 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000507 options.stdout.write('\n_____ %s : Attempting rebase onto %s...\n' % (
508 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000509 printed_path = True
510 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000511 options.stdout.write('Attempting rebase onto %s...\n' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000512
513 # Build the rebase command here using the args
514 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
515 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000516 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000517 rebase_cmd.append('--verbose')
518 if newbase:
519 rebase_cmd.extend(['--onto', newbase])
520 rebase_cmd.append(upstream)
521 if branch:
522 rebase_cmd.append(branch)
523
524 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000525 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000526 except gclient_utils.CheckCallError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000527 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
528 re.match(r'cannot rebase: your index contains uncommitted changes',
529 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000530 while True:
531 rebase_action = str(raw_input("Cannot rebase because of unstaged "
532 "changes.\n'git reset --hard HEAD' ?\n"
533 "WARNING: destroys any uncommitted "
534 "work in your current branch!"
535 " (y)es / (q)uit / (s)how : "))
536 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000537 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000538 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000539 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000540 break
541 elif re.match(r'quit|q', rebase_action, re.I):
542 raise gclient_utils.Error("Please merge or rebase manually\n"
543 "cd %s && git " % self.checkout_path
544 + "%s" % ' '.join(rebase_cmd))
545 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000546 options.stdout.write('\n%s\n' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000547 continue
548 else:
549 gclient_utils.Error("Input not recognized")
550 continue
551 elif re.search(r'^CONFLICT', e.stdout, re.M):
552 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
553 "Fix the conflict and run gclient again.\n"
554 "See 'man git-rebase' for details.\n")
555 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000556 options.stdout.write(e.stdout.strip() + '\n')
557 options.stdout.write('Rebase produced error output:\n%s\n' %
558 e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000559 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
560 "manually.\ncd %s && git " %
561 self.checkout_path
562 + "%s" % ' '.join(rebase_cmd))
563
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000564 options.stdout.write(rebase_output)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000565 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000566 # Make the output a little prettier. It's nice to have some
567 # whitespace between projects when syncing.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000568 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000569
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000570 @staticmethod
571 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000572 (ok, current_version) = scm.GIT.AssertVersion(min_version)
573 if not ok:
574 raise gclient_utils.Error('git version %s < minimum required %s' %
575 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000576
msb@chromium.org786fb682010-06-02 15:16:23 +0000577 def _IsRebasing(self):
578 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
579 # have a plumbing command to determine whether a rebase is in progress, so
580 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
581 g = os.path.join(self.checkout_path, '.git')
582 return (
583 os.path.isdir(os.path.join(g, "rebase-merge")) or
584 os.path.isdir(os.path.join(g, "rebase-apply")))
585
586 def _CheckClean(self, rev_str):
587 # Make sure the tree is clean; see git-rebase.sh for reference
588 try:
589 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000590 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000591 except gclient_utils.CheckCallError:
592 raise gclient_utils.Error('\n____ %s%s\n'
593 '\tYou have unstaged changes.\n'
594 '\tPlease commit, stash, or reset.\n'
595 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000596 try:
597 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000598 '--ignore-submodules', 'HEAD', '--'],
599 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000600 except gclient_utils.CheckCallError:
601 raise gclient_utils.Error('\n____ %s%s\n'
602 '\tYour index contains uncommitted changes\n'
603 '\tPlease commit, stash, or reset.\n'
604 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000605
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000606 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000607 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
608 # reference by a commit). If not, error out -- most likely a rebase is
609 # in progress, try to detect so we can give a better error.
610 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000611 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
612 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000613 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000614 # Commit is not contained by any rev. See if the user is rebasing:
615 if self._IsRebasing():
616 # Punt to the user
617 raise gclient_utils.Error('\n____ %s%s\n'
618 '\tAlready in a conflict, i.e. (no branch).\n'
619 '\tFix the conflict and run gclient again.\n'
620 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
621 '\tSee man git-rebase for details.\n'
622 % (self.relpath, rev_str))
623 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000624 name = ('saved-by-gclient-' +
625 self._Capture(['rev-parse', '--short', 'HEAD']))
626 self._Capture(['branch', name])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000627 options.stdout.write(
628 '\n_____ found an unreferenced commit and saved it as \'%s\'\n' %
629 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000630
msb@chromium.org5bde4852009-12-14 16:47:12 +0000631 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000632 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000633 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000634 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000635 return None
636 return branch
637
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000638 def _Capture(self, args):
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000639 return gclient_utils.CheckCall(
640 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000641
maruel@chromium.org37e89872010-09-07 16:11:33 +0000642 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000643 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000644 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
645 always=options.verbose, stdout=options.stdout, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000646
647
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000648class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000649 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000650
651 def cleanup(self, options, args, file_list):
652 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000653 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000654
655 def diff(self, options, args, file_list):
656 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000657 if not os.path.isdir(self.checkout_path):
658 raise gclient_utils.Error('Directory %s is not present.' %
659 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000660 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000661
662 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000663 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000664 assert len(args) == 1
665 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
666 try:
667 os.makedirs(export_path)
668 except OSError:
669 pass
670 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000671 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000672
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000673 def pack(self, options, args, file_list):
674 """Generates a patch file which can be applied to the root of the
675 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000676 if not os.path.isdir(self.checkout_path):
677 raise gclient_utils.Error('Directory %s is not present.' %
678 self.checkout_path)
679 gclient_utils.CheckCallAndFilter(
680 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
681 cwd=self.checkout_path,
682 print_stdout=False,
683 filter_fn=DiffFilterer(self.relpath, options.stdout).Filter,
maruel@chromium.org559c3f82010-08-23 19:26:08 +0000684 stdout=options.stdout)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000685
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000686 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000687 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000688
689 All updated files will be appended to file_list.
690
691 Raises:
692 Error: if can't get URL for relative path.
693 """
694 # Only update if git is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000695 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000696 if os.path.exists(git_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000697 options.stdout.write('________ found .git directory; skipping %s\n' %
698 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000699 return
700
701 if args:
702 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
703
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000704 # revision is the revision to match. It is None if no revision is specified,
705 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000706 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000707 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000708 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000709 if options.revision:
710 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000711 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000712 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000713 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000714 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000715 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000716 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000717 else:
718 forced_revision = False
719 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000720
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000721 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000722 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000723 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000724 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000725 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000726 return
727
728 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000729 try:
730 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
731 except gclient_utils.Error:
732 raise gclient_utils.Error(
733 ('Can\'t update/checkout %s if an unversioned directory is present. '
734 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000735
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000736 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000737 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
738 if [True for d in dir_info
739 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000740 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000741 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000742
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000743 # Retrieve the current HEAD version because svn is slow at null updates.
744 if options.manually_grab_svn_rev and not revision:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000745 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000746 revision = str(from_info_live['Revision'])
747 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000748
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000749 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000750 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000751 try:
752 to_info = scm.SVN.CaptureInfo(url)
753 except gclient_utils.Error:
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000754 # The url is invalid or the server is not accessible, it's safer to bail
755 # out right now.
756 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000757 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
758 and (from_info['UUID'] == to_info['UUID']))
759 if can_switch:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000760 options.stdout.write('\n_____ relocating %s to a new checkout\n' %
761 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000762 # We have different roots, so check if we can switch --relocate.
763 # Subversion only permits this if the repository UUIDs match.
764 # Perform the switch --relocate, then rewrite the from_url
765 # to reflect where we "are now." (This is the same way that
766 # Subversion itself handles the metadata when switch --relocate
767 # is used.) This makes the checks below for whether we
768 # can update to a revision or have to switch to a different
769 # branch work as expected.
770 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000771 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000772 from_info['Repository Root'],
773 to_info['Repository Root'],
774 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000775 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000776 from_info['URL'] = from_info['URL'].replace(
777 from_info['Repository Root'],
778 to_info['Repository Root'])
779 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000780 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000781 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000782 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000783 if status[0] != '?':
784 raise gclient_utils.Error(
785 ('Can\'t switch the checkout to %s; UUID don\'t match and '
786 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000787 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000788 # Ok delete it.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000789 options.stdout.write('\n_____ switching %s to a new checkout\n' %
790 self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000791 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000792 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000793 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000794 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000795 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000796 return
797
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000798 # If the provided url has a revision number that matches the revision
799 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000800 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000801 if options.verbose or not forced_revision:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000802 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000803 return
804
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000805 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000806 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000807 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000808
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000809 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000810 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000811 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000812 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000813 # Create an empty checkout and then update the one file we want. Future
814 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000815 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000816 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000817 if os.path.exists(os.path.join(self.checkout_path, filename)):
818 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000819 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000820 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000821 # After the initial checkout, we can use update as if it were any other
822 # dep.
823 self.update(options, args, file_list)
824 else:
825 # If the installed version of SVN doesn't support --depth, fallback to
826 # just exporting the file. This has the downside that revision
827 # information is not stored next to the file, so we will have to
828 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000829 if not os.path.exists(self.checkout_path):
830 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000831 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000832 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000833 command = self._AddAdditionalUpdateFlags(command, options,
834 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000835 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000836
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000837 def revert(self, options, args, file_list):
838 """Reverts local modifications. Subversion specific.
839
840 All reverted files will be appended to file_list, even if Subversion
841 doesn't know about them.
842 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000843 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000844 # svn revert won't work if the directory doesn't exist. It needs to
845 # checkout instead.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000846 options.stdout.write('\n_____ %s is missing, synching instead\n' %
847 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000848 # Don't reuse the args.
849 return self.update(options, [], file_list)
850
maruel@chromium.org945405e2010-08-18 17:01:49 +0000851 # Do a flush of sys.stdout every 10 secs or so otherwise it may never be
852 # flushed fast enough for buildbot.
853 last_flushed_at = time.time()
854 sys.stdout.flush()
855
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000856 for file_status in scm.SVN.CaptureStatus(self.checkout_path):
857 file_path = os.path.join(self.checkout_path, file_status[1])
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000858 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000859 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000860 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000861 continue
862
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000863 if logging.getLogger().isEnabledFor(logging.INFO):
864 logging.info('%s%s' % (file[0], file[1]))
865 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000866 options.stdout.write(file_path + '\n')
maruel@chromium.org945405e2010-08-18 17:01:49 +0000867 # Flush at least 10 seconds between line writes. We wait at least 10
868 # seconds to avoid overloading the reader that called us with output,
869 # which can slow busy readers down.
870 if (time.time() - last_flushed_at) > 10:
871 last_flushed_at = time.time()
872 sys.stdout.flush()
873
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000874 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000875 logging.error('No idea what is the status of %s.\n'
876 'You just found a bug in gclient, please ping '
877 'maruel@chromium.org ASAP!' % file_path)
878 # svn revert is really stupid. It fails on inconsistent line-endings,
879 # on switched directories, etc. So take no chance and delete everything!
880 try:
881 if not os.path.exists(file_path):
882 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000883 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000884 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000885 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000886 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000887 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000888 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000889 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000890 logging.error('no idea what is %s.\nYou just found a bug in gclient'
891 ', please ping maruel@chromium.org ASAP!' % file_path)
892 except EnvironmentError:
893 logging.error('Failed to remove %s.' % file_path)
894
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000895 try:
896 # svn revert is so broken we don't even use it. Using
897 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000898 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
899 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000900 except OSError, e:
901 # Maybe the directory disapeared meanwhile. We don't want it to throw an
902 # exception.
903 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000904
msb@chromium.org0f282062009-11-06 20:14:02 +0000905 def revinfo(self, options, args, file_list):
906 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000907 try:
908 return scm.SVN.CaptureRevision(self.checkout_path)
909 except gclient_utils.Error:
910 return None
msb@chromium.org0f282062009-11-06 20:14:02 +0000911
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000912 def runhooks(self, options, args, file_list):
913 self.status(options, args, file_list)
914
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000915 def status(self, options, args, file_list):
916 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000917 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000918 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000919 # svn status won't work if the directory doesn't exist.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000920 options.stdout.write(
921 ('\n________ couldn\'t run \'%s\' in \'%s\':\nThe directory '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000922 'does not exist.') % (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000923 # There's no file list to retrieve.
924 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000925 self._RunAndGetFileList(command, options, 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.org669600d2010-09-01 19:06:31 +0000931 def _Run(self, args, options, **kwargs):
932 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000933 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000934 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
935 always=options.verbose, stdout=options.stdout, **kwargs)
936
937 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
938 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000939 cwd = cwd or self.checkout_path
maruel@chromium.org669600d2010-09-01 19:06:31 +0000940 scm.SVN.RunAndGetFileList(options.verbose, args, cwd=cwd,
941 file_list=file_list, stdout=options.stdout)
942
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000943 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000944 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000945 """Add additional flags to command depending on what options are set.
946 command should be a list of strings that represents an svn command.
947
948 This method returns a new list to be used as a command."""
949 new_command = command[:]
950 if revision:
951 new_command.extend(['--revision', str(revision).strip()])
952 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000953 if ((options.force or options.manually_grab_svn_rev) and
954 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000955 new_command.append('--force')
956 return new_command