blob: b6ee8a08ac6e3798b6177e77133a2eba3b0be17c [file] [log] [blame]
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +00001# Copyright (c) 2010 The Chromium Authors. All rights reserved.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00004
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00005"""Gclient-specific SCM-specific operations."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00006
maruel@chromium.org754960e2009-09-21 12:31:05 +00007import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00008import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00009import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000010import re
11import subprocess
maruel@chromium.org945405e2010-08-18 17:01:49 +000012import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000013import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000014
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000015import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000017
18
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000019class DiffFilterer(object):
20 """Simple class which tracks which file is being diffed and
21 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000022 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000023 index_string = "Index: "
24 original_prefix = "--- "
25 working_prefix = "+++ "
26
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000027 def __init__(self, relpath, stdout):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000028 # Note that we always use '/' as the path separator to be
29 # consistent with svn's cygwin-style output on Windows
30 self._relpath = relpath.replace("\\", "/")
31 self._current_file = ""
32 self._replacement_file = ""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000033 self._stdout = stdout
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000034
maruel@chromium.org6e29d572010-06-04 17:32:20 +000035 def SetCurrentFile(self, current_file):
36 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000037 # Note that we always use '/' as the path separator to be
38 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000039 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000040
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000041 def _Replace(self, line):
42 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000043
44 def Filter(self, line):
45 if (line.startswith(self.index_string)):
46 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000047 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000048 else:
49 if (line.startswith(self.original_prefix) or
50 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000051 line = self._Replace(line)
52 self._stdout.write(line + '\n')
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000053
54
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000055### SCM abstraction layer
56
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000057# Factory Method for SCM wrapper creation
58
maruel@chromium.org9eda4112010-06-11 18:56:10 +000059def GetScmName(url):
60 if url:
61 url, _ = gclient_utils.SplitUrlRevision(url)
62 if (url.startswith('git://') or url.startswith('ssh://') or
63 url.endswith('.git')):
64 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000065 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000066 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000067 return 'svn'
68 return None
69
70
71def CreateSCM(url, root_dir=None, relpath=None):
72 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000073 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000074 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000075 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000076
maruel@chromium.org9eda4112010-06-11 18:56:10 +000077 scm_name = GetScmName(url)
78 if not scm_name in SCM_MAP:
79 raise gclient_utils.Error('No SCM found for url %s' % url)
80 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000081
82
83# SCMWrapper base class
84
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000085class SCMWrapper(object):
86 """Add necessary glue between all the supported SCM.
87
msb@chromium.orgd6504212010-01-13 17:34:31 +000088 This is the abstraction layer to bind to different SCM.
89 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000090 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000091 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000092 self._root_dir = root_dir
93 if self._root_dir:
94 self._root_dir = self._root_dir.replace('/', os.sep)
95 self.relpath = relpath
96 if self.relpath:
97 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000098 if self.relpath and self._root_dir:
99 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000100
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000101 def RunCommand(self, command, options, args, file_list=None):
102 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000103 if file_list is None:
104 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000105
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000106 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
107 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000108
109 if not command in commands:
110 raise gclient_utils.Error('Unknown command %s' % command)
111
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000112 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000113 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000114 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000115
116 return getattr(self, command)(options, args, file_list)
117
118
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000119class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000120 """Wrapper for Git"""
121
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000122 @staticmethod
123 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000124 """'Cleanup' the repo.
125
126 There's no real git equivalent for the svn cleanup command, do a no-op.
127 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000128
129 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000130 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
131 self._Run(['diff', merge_base])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000132
133 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000134 """Export a clean directory tree into the given path.
135
136 Exports into the specified directory, creating the path if it does
137 already exist.
138 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000139 assert len(args) == 1
140 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
141 if not os.path.exists(export_path):
142 os.makedirs(export_path)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000143 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path])
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:
msb@chromium.org4a3bc282010-07-20 22:44:36 +0000261 remote_output, remote_err = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000262 ['remote'] + verbose + ['update'],
263 self.checkout_path,
264 print_error=False)
265 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000266 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000267 # Hackish but at that point, git is known to work so just checking for
268 # 502 in stderr should be fine.
269 if '502' in e.stderr:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000270 options.stdout.write(str(e) + '\n')
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000271 options.stdout.write('Sleeping %.1f seconds and retrying...\n' %
272 backoff_time)
273 time.sleep(backoff_time)
274 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000275 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000276 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000277
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000278 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000279 options.stdout.write(remote_output.strip() + '\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000280 # git remote update prints to stderr when used with --verbose
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000281 options.stdout.write(remote_err.strip() + '\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000282
283 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000284 if options.force or options.reset:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000285 self._Run(['reset', '--hard', 'HEAD'])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000286
msb@chromium.org786fb682010-06-02 15:16:23 +0000287 if current_type == 'detached':
288 # case 0
289 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000290 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000291 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000292 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000293 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000294 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000295 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000296 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000297 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000298 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000299 newbase=revision, printed_path=printed_path)
300 printed_path = True
301 else:
302 # Can't find a merge-base since we don't know our upstream. That makes
303 # this command VERY likely to produce a rebase failure. For now we
304 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000305 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000306 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000307 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000308 self._AttemptRebase(upstream_branch, files, options,
309 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000310 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000311 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000312 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000313 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000314 newbase=revision, printed_path=printed_path)
315 printed_path = True
316 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
317 # case 4
318 new_base = revision.replace('heads', 'remotes/origin')
319 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000320 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000321 switch_error = ("Switching upstream branch from %s to %s\n"
322 % (upstream_branch, new_base) +
323 "Please merge or rebase manually:\n" +
324 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
325 "OR git checkout -b <some new branch> %s" % new_base)
326 raise gclient_utils.Error(switch_error)
327 else:
328 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000329 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000330 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000331 options.stdout.write('Trying fast-forward merge to branch : %s\n' %
332 upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000333 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000334 merge_output, merge_err = scm.GIT.Capture(['merge', '--ff-only',
335 upstream_branch],
336 self.checkout_path,
337 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000338 except gclient_utils.CheckCallError, e:
339 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
340 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000341 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000342 printed_path = True
343 while True:
344 try:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000345 # TODO(maruel): That can't work.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000346 action = str(raw_input("Cannot fast-forward merge, attempt to "
347 "rebase? (y)es / (q)uit / (s)kip : "))
348 except ValueError:
349 gclient_utils.Error('Invalid Character')
350 continue
351 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000352 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000353 printed_path=printed_path)
354 printed_path = True
355 break
356 elif re.match(r'quit|q', action, re.I):
357 raise gclient_utils.Error("Can't fast-forward, please merge or "
358 "rebase manually.\n"
359 "cd %s && git " % self.checkout_path
360 + "rebase %s" % upstream_branch)
361 elif re.match(r'skip|s', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000362 options.stdout.write('Skipping %s\n' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000363 return
364 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000365 options.stdout.write('Input not recognized\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000366 elif re.match("error: Your local changes to '.*' would be "
367 "overwritten by merge. Aborting.\nPlease, commit your "
368 "changes or stash them before you can merge.\n",
369 e.stderr):
370 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000371 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000372 printed_path = True
373 raise gclient_utils.Error(e.stderr)
374 else:
375 # Some other problem happened with the merge
376 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000377 options.stdout.write(e.stderr + '\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000378 raise
379 else:
380 # Fast-forward merge was successful
381 if not re.match('Already up-to-date.', merge_output) or verbose:
382 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000383 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000384 printed_path = True
385 print merge_output.strip()
386 if merge_err:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000387 options.stdout.write('Merge produced error output:\n%s\n' %
388 merge_err.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000389 if not verbose:
390 # Make the output a little prettier. It's nice to have some
391 # whitespace between projects when syncing.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000392 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000393
394 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000395
396 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000397 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000398 raise gclient_utils.Error('\n____ %s%s\n'
399 '\nConflict while rebasing this branch.\n'
400 'Fix the conflict and run gclient again.\n'
401 'See man git-rebase for details.\n'
402 % (self.relpath, rev_str))
403
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000404 if verbose:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000405 options.stdout.write('Checked out revision %s\n' %
406 self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000407
408 def revert(self, options, args, file_list):
409 """Reverts local modifications.
410
411 All reverted files will be appended to file_list.
412 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000413 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000414 # revert won't work if the directory doesn't exist. It needs to
415 # checkout instead.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000416 options.stdout.write('\n_____ %s is missing, synching instead\n' %
417 self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000418 # Don't reuse the args.
419 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000420
421 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000422 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000423 if not deps_revision:
424 deps_revision = default_rev
425 if deps_revision.startswith('refs/heads/'):
426 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
427
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000428 files = self._Capture(['diff', deps_revision, '--name-only']).split()
429 self._Run(['reset', '--hard', deps_revision])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000430 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
431
msb@chromium.org0f282062009-11-06 20:14:02 +0000432 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000433 """Returns revision"""
434 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000435
msb@chromium.orge28e4982009-09-25 20:51:45 +0000436 def runhooks(self, options, args, file_list):
437 self.status(options, args, file_list)
438
439 def status(self, options, args, file_list):
440 """Display status information."""
441 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000442 options.stdout.write(
443 ('\n________ couldn\'t run status in %s:\nThe directory '
444 'does not exist.\n') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000445 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000446 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
447 self._Run(['diff', '--name-status', merge_base])
448 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000449 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
450
msb@chromium.orge6f78352010-01-13 17:05:33 +0000451 def FullUrlForRelativeUrl(self, url):
452 # Strip from last '/'
453 # Equivalent to unix basename
454 base_url = self.url
455 return base_url[:base_url.rfind('/')] + url
456
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000457 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000458 """Clone a git repository from the given URL.
459
msb@chromium.org786fb682010-06-02 15:16:23 +0000460 Once we've cloned the repo, we checkout a working branch if the specified
461 revision is a branch head. If it is a tag or a specific commit, then we
462 leave HEAD detached as it makes future updates simpler -- in this case the
463 user should first create a new branch or switch to an existing branch before
464 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000465 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000466 # git clone doesn't seem to insert a newline properly before printing
467 # to stdout
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000468 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000469
470 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000471 if revision.startswith('refs/heads/'):
472 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
473 detach_head = False
474 else:
475 clone_cmd.append('--no-checkout')
476 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000477 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000478 clone_cmd.append('--verbose')
479 clone_cmd.extend([url, self.checkout_path])
480
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000481 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000482 try:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000483 self._Run(clone_cmd, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000484 break
485 except gclient_utils.Error, e:
486 # TODO(maruel): Hackish, should be fixed by moving _Run() to
487 # CheckCall().
488 # Too bad we don't have access to the actual output.
489 # We should check for "transfer closed with NNN bytes remaining to
490 # read". In the meantime, just make sure .git exists.
491 if (e.args[0] == 'git command clone returned 128' and
492 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000493 options.stdout.write(str(e) + '\n')
494 options.stdout.write('Retrying...\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000495 continue
496 raise e
497
msb@chromium.org786fb682010-06-02 15:16:23 +0000498 if detach_head:
499 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000500 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000501 options.stdout.write(
502 ('Checked out %s to a detached HEAD. Before making any commits\n'
503 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
504 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
505 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000506
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000507 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000508 branch=None, printed_path=False):
509 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000510 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000511 revision = upstream
512 if newbase:
513 revision = newbase
514 if not printed_path:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000515 options.stdout.write('\n_____ %s : Attempting rebase onto %s...\n' % (
516 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000517 printed_path = True
518 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000519 options.stdout.write('Attempting rebase onto %s...\n' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000520
521 # Build the rebase command here using the args
522 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
523 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000524 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000525 rebase_cmd.append('--verbose')
526 if newbase:
527 rebase_cmd.extend(['--onto', newbase])
528 rebase_cmd.append(upstream)
529 if branch:
530 rebase_cmd.append(branch)
531
532 try:
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000533 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
534 self.checkout_path,
535 print_error=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000536 except gclient_utils.CheckCallError, e:
537 if re.match(r'cannot rebase: you have unstaged changes', e.stderr) or \
538 re.match(r'cannot rebase: your index contains uncommitted changes',
539 e.stderr):
540 while True:
541 rebase_action = str(raw_input("Cannot rebase because of unstaged "
542 "changes.\n'git reset --hard HEAD' ?\n"
543 "WARNING: destroys any uncommitted "
544 "work in your current branch!"
545 " (y)es / (q)uit / (s)how : "))
546 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000547 self._Run(['reset', '--hard', 'HEAD'])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000548 # Should this be recursive?
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000549 rebase_output, rebase_err = scm.GIT.Capture(rebase_cmd,
550 self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000551 break
552 elif re.match(r'quit|q', rebase_action, re.I):
553 raise gclient_utils.Error("Please merge or rebase manually\n"
554 "cd %s && git " % self.checkout_path
555 + "%s" % ' '.join(rebase_cmd))
556 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000557 options.stdout.write('\n%s\n' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000558 continue
559 else:
560 gclient_utils.Error("Input not recognized")
561 continue
562 elif re.search(r'^CONFLICT', e.stdout, re.M):
563 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
564 "Fix the conflict and run gclient again.\n"
565 "See 'man git-rebase' for details.\n")
566 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000567 options.stdout.write(e.stdout.strip() + '\n')
568 options.stdout.write('Rebase produced error output:\n%s\n' %
569 e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000570 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
571 "manually.\ncd %s && git " %
572 self.checkout_path
573 + "%s" % ' '.join(rebase_cmd))
574
575 print rebase_output.strip()
576 if rebase_err:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000577 options.stdout.write('Rebase produced error output:\n%s\n' %
578 rebase_err.strip())
579 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000580 # Make the output a little prettier. It's nice to have some
581 # whitespace between projects when syncing.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000582 options.stdout.write('\n')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000583
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000584 @staticmethod
585 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000586 (ok, current_version) = scm.GIT.AssertVersion(min_version)
587 if not ok:
588 raise gclient_utils.Error('git version %s < minimum required %s' %
589 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000590
msb@chromium.org786fb682010-06-02 15:16:23 +0000591 def _IsRebasing(self):
592 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
593 # have a plumbing command to determine whether a rebase is in progress, so
594 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
595 g = os.path.join(self.checkout_path, '.git')
596 return (
597 os.path.isdir(os.path.join(g, "rebase-merge")) or
598 os.path.isdir(os.path.join(g, "rebase-apply")))
599
600 def _CheckClean(self, rev_str):
601 # Make sure the tree is clean; see git-rebase.sh for reference
602 try:
603 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
604 self.checkout_path, print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000605 except gclient_utils.CheckCallError:
606 raise gclient_utils.Error('\n____ %s%s\n'
607 '\tYou have unstaged changes.\n'
608 '\tPlease commit, stash, or reset.\n'
609 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000610 try:
611 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
612 '--ignore-submodules', 'HEAD', '--'], self.checkout_path,
613 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000614 except gclient_utils.CheckCallError:
615 raise gclient_utils.Error('\n____ %s%s\n'
616 '\tYour index contains uncommitted changes\n'
617 '\tPlease commit, stash, or reset.\n'
618 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000619
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000620 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000621 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
622 # reference by a commit). If not, error out -- most likely a rebase is
623 # in progress, try to detect so we can give a better error.
624 try:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000625 _, _ = scm.GIT.Capture(
msb@chromium.org786fb682010-06-02 15:16:23 +0000626 ['name-rev', '--no-undefined', 'HEAD'],
627 self.checkout_path,
628 print_error=False)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000629 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000630 # Commit is not contained by any rev. See if the user is rebasing:
631 if self._IsRebasing():
632 # Punt to the user
633 raise gclient_utils.Error('\n____ %s%s\n'
634 '\tAlready in a conflict, i.e. (no branch).\n'
635 '\tFix the conflict and run gclient again.\n'
636 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
637 '\tSee man git-rebase for details.\n'
638 % (self.relpath, rev_str))
639 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000640 name = ('saved-by-gclient-' +
641 self._Capture(['rev-parse', '--short', 'HEAD']))
642 self._Capture(['branch', name])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000643 options.stdout.write(
644 '\n_____ found an unreferenced commit and saved it as \'%s\'\n' %
645 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000646
msb@chromium.org5bde4852009-12-14 16:47:12 +0000647 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000648 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000649 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000650 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000651 return None
652 return branch
653
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000654 def _Capture(self, args):
655 return gclient_utils.CheckCall(['git'] + args,
656 cwd=self.checkout_path)[0].strip()
657
658 def _Run(self, args, **kwargs):
659 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000660 try:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000661 gclient_utils.Popen(['git'] + args, **kwargs).communicate()
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000662 except OSError:
663 raise gclient_utils.Error("git command '%s' failed to run." %
664 ' '.join(cmd) + "\nCheck that you have git installed.")
msb@chromium.orge28e4982009-09-25 20:51:45 +0000665
666
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000667class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000668 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000669
670 def cleanup(self, options, args, file_list):
671 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000672 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000673
674 def diff(self, options, args, file_list):
675 # NOTE: This function does not currently modify file_list.
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)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000679 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000680
681 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000682 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000683 assert len(args) == 1
684 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
685 try:
686 os.makedirs(export_path)
687 except OSError:
688 pass
689 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000690 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000691
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000692 def pack(self, options, args, file_list):
693 """Generates a patch file which can be applied to the root of the
694 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000695 if not os.path.isdir(self.checkout_path):
696 raise gclient_utils.Error('Directory %s is not present.' %
697 self.checkout_path)
698 gclient_utils.CheckCallAndFilter(
699 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
700 cwd=self.checkout_path,
701 print_stdout=False,
702 filter_fn=DiffFilterer(self.relpath, options.stdout).Filter,
maruel@chromium.org559c3f82010-08-23 19:26:08 +0000703 stdout=options.stdout)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000704
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000705 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000706 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000707
708 All updated files will be appended to file_list.
709
710 Raises:
711 Error: if can't get URL for relative path.
712 """
713 # Only update if git is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000714 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000715 if os.path.exists(git_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000716 options.stdout.write('________ found .git directory; skipping %s\n' %
717 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000718 return
719
720 if args:
721 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
722
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000723 # revision is the revision to match. It is None if no revision is specified,
724 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000725 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000726 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000727 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000728 if options.revision:
729 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000730 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000731 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000732 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000733 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000734 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000735 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000736 else:
737 forced_revision = False
738 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000739
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000740 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000741 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000742 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000743 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000744 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000745 return
746
747 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000748 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000749 if not from_info:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000750 raise gclient_utils.Error(('Can\'t update/checkout %r if an unversioned '
751 'directory is present. Delete the directory '
752 'and try again.') %
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000753 self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000754
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000755 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000756 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
757 if [True for d in dir_info
758 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000759 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000760 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000761
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000762 # Retrieve the current HEAD version because svn is slow at null updates.
763 if options.manually_grab_svn_rev and not revision:
764 from_info_live = scm.SVN.CaptureInfo(from_info['URL'], '.')
765 revision = str(from_info_live['Revision'])
766 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000767
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000768 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000769 # The repository url changed, need to switch.
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000770 to_info = scm.SVN.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000771 if not to_info.get('Repository Root') or not to_info.get('UUID'):
772 # The url is invalid or the server is not accessible, it's safer to bail
773 # out right now.
774 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000775 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
776 and (from_info['UUID'] == to_info['UUID']))
777 if can_switch:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000778 options.stdout.write('\n_____ relocating %s to a new checkout\n' %
779 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000780 # We have different roots, so check if we can switch --relocate.
781 # Subversion only permits this if the repository UUIDs match.
782 # Perform the switch --relocate, then rewrite the from_url
783 # to reflect where we "are now." (This is the same way that
784 # Subversion itself handles the metadata when switch --relocate
785 # is used.) This makes the checks below for whether we
786 # can update to a revision or have to switch to a different
787 # branch work as expected.
788 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000789 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000790 from_info['Repository Root'],
791 to_info['Repository Root'],
792 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000793 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000794 from_info['URL'] = from_info['URL'].replace(
795 from_info['Repository Root'],
796 to_info['Repository Root'])
797 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000798 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000799 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000800 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000801 if status[0] != '?':
802 raise gclient_utils.Error(
803 ('Can\'t switch the checkout to %s; UUID don\'t match and '
804 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000805 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000806 # Ok delete it.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000807 options.stdout.write('\n_____ switching %s to a new checkout\n' %
808 self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000809 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000810 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000811 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000812 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000813 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000814 return
815
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000816 # If the provided url has a revision number that matches the revision
817 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000818 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000819 if options.verbose or not forced_revision:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000820 options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000821 return
822
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000823 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000824 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000825 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000826
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000827 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000828 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000829 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000830 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000831 # Create an empty checkout and then update the one file we want. Future
832 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000833 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000834 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000835 if os.path.exists(os.path.join(self.checkout_path, filename)):
836 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000837 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000838 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000839 # After the initial checkout, we can use update as if it were any other
840 # dep.
841 self.update(options, args, file_list)
842 else:
843 # If the installed version of SVN doesn't support --depth, fallback to
844 # just exporting the file. This has the downside that revision
845 # information is not stored next to the file, so we will have to
846 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000847 if not os.path.exists(self.checkout_path):
848 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000849 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000850 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000851 command = self._AddAdditionalUpdateFlags(command, options,
852 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000853 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000854
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000855 def revert(self, options, args, file_list):
856 """Reverts local modifications. Subversion specific.
857
858 All reverted files will be appended to file_list, even if Subversion
859 doesn't know about them.
860 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000861 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000862 # svn revert won't work if the directory doesn't exist. It needs to
863 # checkout instead.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000864 options.stdout.write('\n_____ %s is missing, synching instead\n' %
865 self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000866 # Don't reuse the args.
867 return self.update(options, [], file_list)
868
maruel@chromium.org945405e2010-08-18 17:01:49 +0000869 # Do a flush of sys.stdout every 10 secs or so otherwise it may never be
870 # flushed fast enough for buildbot.
871 last_flushed_at = time.time()
872 sys.stdout.flush()
873
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000874 for file_status in scm.SVN.CaptureStatus(self.checkout_path):
875 file_path = os.path.join(self.checkout_path, file_status[1])
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000876 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000877 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000878 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000879 continue
880
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000881 if logging.getLogger().isEnabledFor(logging.INFO):
882 logging.info('%s%s' % (file[0], file[1]))
883 else:
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000884 options.stdout.write(file_path + '\n')
maruel@chromium.org945405e2010-08-18 17:01:49 +0000885 # Flush at least 10 seconds between line writes. We wait at least 10
886 # seconds to avoid overloading the reader that called us with output,
887 # which can slow busy readers down.
888 if (time.time() - last_flushed_at) > 10:
889 last_flushed_at = time.time()
890 sys.stdout.flush()
891
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000892 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000893 logging.error('No idea what is the status of %s.\n'
894 'You just found a bug in gclient, please ping '
895 'maruel@chromium.org ASAP!' % file_path)
896 # svn revert is really stupid. It fails on inconsistent line-endings,
897 # on switched directories, etc. So take no chance and delete everything!
898 try:
899 if not os.path.exists(file_path):
900 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000901 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000902 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000903 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000904 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000905 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000906 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000907 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000908 logging.error('no idea what is %s.\nYou just found a bug in gclient'
909 ', please ping maruel@chromium.org ASAP!' % file_path)
910 except EnvironmentError:
911 logging.error('Failed to remove %s.' % file_path)
912
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000913 try:
914 # svn revert is so broken we don't even use it. Using
915 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000916 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
917 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000918 except OSError, e:
919 # Maybe the directory disapeared meanwhile. We don't want it to throw an
920 # exception.
921 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000922
msb@chromium.org0f282062009-11-06 20:14:02 +0000923 def revinfo(self, options, args, file_list):
924 """Display revision"""
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000925 return scm.SVN.CaptureBaseRevision(self.checkout_path)
msb@chromium.org0f282062009-11-06 20:14:02 +0000926
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000927 def runhooks(self, options, args, file_list):
928 self.status(options, args, file_list)
929
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000930 def status(self, options, args, file_list):
931 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000932 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000933 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000934 # svn status won't work if the directory doesn't exist.
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000935 options.stdout.write(
936 ('\n________ couldn\'t run \'%s\' in \'%s\':\nThe directory '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000937 'does not exist.') % (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000938 # There's no file list to retrieve.
939 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000940 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000941
942 def FullUrlForRelativeUrl(self, url):
943 # Find the forth '/' and strip from there. A bit hackish.
944 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000945
maruel@chromium.org669600d2010-09-01 19:06:31 +0000946 def _Run(self, args, options, **kwargs):
947 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000948 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000949 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
950 always=options.verbose, stdout=options.stdout, **kwargs)
951
952 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
953 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000954 cwd = cwd or self.checkout_path
maruel@chromium.org669600d2010-09-01 19:06:31 +0000955 scm.SVN.RunAndGetFileList(options.verbose, args, cwd=cwd,
956 file_list=file_list, stdout=options.stdout)
957
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000958 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000959 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000960 """Add additional flags to command depending on what options are set.
961 command should be a list of strings that represents an svn command.
962
963 This method returns a new list to be used as a command."""
964 new_command = command[:]
965 if revision:
966 new_command.extend(['--revision', str(revision).strip()])
967 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000968 if ((options.force or options.manually_grab_svn_rev) and
969 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000970 new_command.append('--force')
971 return new_command