blob: 8c7bcba01f0ea6ced4842e9f4b939961a8b722b7 [file] [log] [blame]
steveblock@chromium.org93567042012-02-15 01:02:26 +00001# Copyright (c) 2012 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.org90541732011-04-01 17:54:18 +000011import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000012import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013
14import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000015import scm
16import subprocess2
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000017
18
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000019class DiffFiltererWrapper(object):
20 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000021 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."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000023 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000024 original_prefix = "--- "
25 working_prefix = "+++ "
26
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000027 def __init__(self, relpath):
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("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000031 self._current_file = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000032
maruel@chromium.org6e29d572010-06-04 17:32:20 +000033 def SetCurrentFile(self, current_file):
34 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000035
iannucci@chromium.org3830a672013-02-19 20:15:14 +000036 @property
37 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000038 return posixpath.join(self._relpath, self._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)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000051 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000052
53
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000054class SvnDiffFilterer(DiffFiltererWrapper):
55 index_string = "Index: "
56
57
58class GitDiffFilterer(DiffFiltererWrapper):
59 index_string = "diff --git "
60
61 def SetCurrentFile(self, current_file):
62 # Get filename by parsing "a/<filename> b/<filename>"
63 self._current_file = current_file[:(len(current_file)/2)][2:]
64
65 def _Replace(self, line):
66 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
67
68
maruel@chromium.org90541732011-04-01 17:54:18 +000069def ask_for_data(prompt):
70 try:
71 return raw_input(prompt)
72 except KeyboardInterrupt:
73 # Hide the exception.
74 sys.exit(1)
75
76
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000077### SCM abstraction layer
78
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000079# Factory Method for SCM wrapper creation
80
maruel@chromium.org9eda4112010-06-11 18:56:10 +000081def GetScmName(url):
82 if url:
83 url, _ = gclient_utils.SplitUrlRevision(url)
84 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000085 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000086 url.endswith('.git')):
87 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000088 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000089 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000090 return 'svn'
91 return None
92
93
94def CreateSCM(url, root_dir=None, relpath=None):
95 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000096 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000097 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000098 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000099
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000100 scm_name = GetScmName(url)
101 if not scm_name in SCM_MAP:
102 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000103 scm_class = SCM_MAP[scm_name]
104 if not scm_class.BinaryExists():
105 raise gclient_utils.Error('%s command not found' % scm_name)
106 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000107
108
109# SCMWrapper base class
110
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000111class SCMWrapper(object):
112 """Add necessary glue between all the supported SCM.
113
msb@chromium.orgd6504212010-01-13 17:34:31 +0000114 This is the abstraction layer to bind to different SCM.
115 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000116 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000117 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000118 self._root_dir = root_dir
119 if self._root_dir:
120 self._root_dir = self._root_dir.replace('/', os.sep)
121 self.relpath = relpath
122 if self.relpath:
123 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000124 if self.relpath and self._root_dir:
125 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000126
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000127 def RunCommand(self, command, options, args, file_list=None):
128 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000129 if file_list is None:
130 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000131
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000132 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000133 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000134
135 if not command in commands:
136 raise gclient_utils.Error('Unknown command %s' % command)
137
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000138 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000139 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000140 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000141
142 return getattr(self, command)(options, args, file_list)
143
144
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000145class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000146 """Wrapper for Git"""
147
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000148 def __init__(self, url=None, root_dir=None, relpath=None):
149 """Removes 'git+' fake prefix from git URL."""
150 if url.startswith('git+http://') or url.startswith('git+https://'):
151 url = url[4:]
152 SCMWrapper.__init__(self, url, root_dir, relpath)
153
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000154 @staticmethod
155 def BinaryExists():
156 """Returns true if the command exists."""
157 try:
158 # We assume git is newer than 1.7. See: crbug.com/114483
159 result, version = scm.GIT.AssertVersion('1.7')
160 if not result:
161 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
162 return result
163 except OSError:
164 return False
165
floitsch@google.comeaab7842011-04-28 09:07:58 +0000166 def GetRevisionDate(self, revision):
167 """Returns the given revision's date in ISO-8601 format (which contains the
168 time zone)."""
169 # TODO(floitsch): get the time-stamp of the given revision and not just the
170 # time-stamp of the currently checked out revision.
171 return self._Capture(['log', '-n', '1', '--format=%ai'])
172
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000173 @staticmethod
174 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000175 """'Cleanup' the repo.
176
177 There's no real git equivalent for the svn cleanup command, do a no-op.
178 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000179
180 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000181 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000182 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000183
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000184 def pack(self, options, args, file_list):
185 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000186 repository.
187
188 The patch file is generated from a diff of the merge base of HEAD and
189 its upstream branch.
190 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000191 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000192 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000193 ['git', 'diff', merge_base],
194 cwd=self.checkout_path,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000195 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000196
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000197 def UpdateSubmoduleConfig(self):
198 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
199 'submodule.$name.ignore', '||',
200 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000201 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000202 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000203 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000204 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000205 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000206 kwargs = {'cwd': self.checkout_path,
207 'print_stdout': False,
208 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000209 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000210 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
211 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000212 except subprocess2.CalledProcessError:
213 # Not a fatal error, or even very interesting in a non-git-submodule
214 # world. So just keep it quiet.
215 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000216 try:
217 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
218 except subprocess2.CalledProcessError:
219 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000220
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000221 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
222
msb@chromium.orge28e4982009-09-25 20:51:45 +0000223 def update(self, options, args, file_list):
224 """Runs git to update or transparently checkout the working copy.
225
226 All updated files will be appended to file_list.
227
228 Raises:
229 Error: if can't get URL for relative path.
230 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000231 if args:
232 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
233
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000234 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000235
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000236 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000237 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000238 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000239 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000240 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000241 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000242 # Override the revision number.
243 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000244 if revision == 'unmanaged':
245 revision = None
246 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000247 if not revision:
248 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000249
floitsch@google.comeaab7842011-04-28 09:07:58 +0000250 if gclient_utils.IsDateRevision(revision):
251 # Date-revisions only work on git-repositories if the reflog hasn't
252 # expired yet. Use rev-list to get the corresponding revision.
253 # git rev-list -n 1 --before='time-stamp' branchname
254 if options.transitive:
255 print('Warning: --transitive only works for SVN repositories.')
256 revision = default_rev
257
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000258 rev_str = ' at %s' % revision
259 files = []
260
261 printed_path = False
262 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000263 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000264 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000265 verbose = ['--verbose']
266 printed_path = True
267
268 if revision.startswith('refs/heads/'):
269 rev_type = "branch"
270 elif revision.startswith('origin/'):
271 # For compatability with old naming, translate 'origin' to 'refs/heads'
272 revision = revision.replace('origin/', 'refs/heads/')
273 rev_type = "branch"
274 else:
275 # hash is also a tag, only make a distinction at checkout
276 rev_type = "hash"
277
szager@google.com873e6672012-03-13 18:53:36 +0000278 if not os.path.exists(self.checkout_path) or (
279 os.path.isdir(self.checkout_path) and
280 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000281 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000282 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000283 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000284 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000285 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000286 if not verbose:
287 # Make the output a little prettier. It's nice to have some whitespace
288 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000289 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000290 return
291
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000292 if not managed:
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000293 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000294 print ('________ unmanaged solution; skipping %s' % self.relpath)
295 return
296
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000297 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
298 raise gclient_utils.Error('\n____ %s%s\n'
299 '\tPath is not a git repo. No .git dir.\n'
300 '\tTo resolve:\n'
301 '\t\trm -rf %s\n'
302 '\tAnd run gclient sync again\n'
303 % (self.relpath, rev_str, self.relpath))
304
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000305 # See if the url has changed (the unittests use git://foo for the url, let
306 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000307 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000308 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
309 # unit test pass. (and update the comment above)
310 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000311 print('_____ switching %s to a new upstream' % self.relpath)
312 # Make sure it's clean
313 self._CheckClean(rev_str)
314 # Switch over to the new upstream
315 self._Run(['remote', 'set-url', 'origin', url], options)
316 quiet = []
317 if not options.verbose:
318 quiet = ['--quiet']
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000319 self._UpdateBranchHeads(options, fetch=False)
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000320 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
bauerb@chromium.org610060e2012-11-19 14:11:35 +0000321 self._Run(['reset', '--hard', revision] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000322 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000323 files = self._Capture(['ls-files']).splitlines()
324 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
325 return
326
msb@chromium.org5bde4852009-12-14 16:47:12 +0000327 cur_branch = self._GetCurrentBranch()
328
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000329 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000330 # 0) HEAD is detached. Probably from our initial clone.
331 # - make sure HEAD is contained by a named ref, then update.
332 # Cases 1-4. HEAD is a branch.
333 # 1) current branch is not tracking a remote branch (could be git-svn)
334 # - try to rebase onto the new hash or branch
335 # 2) current branch is tracking a remote branch with local committed
336 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000337 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000338 # 3) current branch is tracking a remote branch w/or w/out changes,
339 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000340 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000341 # 4) current branch is tracking a remote branch, switches to a different
342 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000343 # - exit
344
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000345 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
346 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000347 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
348 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000349 if cur_branch is None:
350 upstream_branch = None
351 current_type = "detached"
352 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000353 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000354 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
355 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
356 current_type = "hash"
357 logging.debug("Current branch is not tracking an upstream (remote)"
358 " branch.")
359 elif upstream_branch.startswith('refs/remotes'):
360 current_type = "branch"
361 else:
362 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000363
maruel@chromium.org92067382012-06-28 19:58:41 +0000364 if (not re.match(r'^[0-9a-fA-F]{40}$', revision) or
365 not scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=revision)):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000366 # Update the remotes first so we have all the refs.
367 backoff_time = 5
368 for _ in range(10):
369 try:
370 remote_output = scm.GIT.Capture(
371 ['remote'] + verbose + ['update'],
372 cwd=self.checkout_path)
373 break
374 except subprocess2.CalledProcessError, e:
375 # Hackish but at that point, git is known to work so just checking for
376 # 502 in stderr should be fine.
377 if '502' in e.stderr:
378 print(str(e))
379 print('Sleeping %.1f seconds and retrying...' % backoff_time)
380 time.sleep(backoff_time)
381 backoff_time *= 1.3
382 continue
383 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000384
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000385 if verbose:
386 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000387
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000388 self._UpdateBranchHeads(options, fetch=True)
389
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000390 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000391 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000392 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000393
msb@chromium.org786fb682010-06-02 15:16:23 +0000394 if current_type == 'detached':
395 # case 0
396 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000397 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000398 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000399 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000400 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000401 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000402 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000403 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000404 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000405 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000406 newbase=revision, printed_path=printed_path)
407 printed_path = True
408 else:
409 # Can't find a merge-base since we don't know our upstream. That makes
410 # this command VERY likely to produce a rebase failure. For now we
411 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000412 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000413 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000414 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000415 self._AttemptRebase(upstream_branch, files, options,
416 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000417 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000418 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000419 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000420 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000421 newbase=revision, printed_path=printed_path)
422 printed_path = True
423 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
424 # case 4
425 new_base = revision.replace('heads', 'remotes/origin')
426 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000427 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000428 switch_error = ("Switching upstream branch from %s to %s\n"
429 % (upstream_branch, new_base) +
430 "Please merge or rebase manually:\n" +
431 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
432 "OR git checkout -b <some new branch> %s" % new_base)
433 raise gclient_utils.Error(switch_error)
434 else:
435 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000436 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000437 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000438 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000439 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000440 merge_args = ['merge']
441 if not options.merge:
442 merge_args.append('--ff-only')
443 merge_args.append(upstream_branch)
444 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000445 except subprocess2.CalledProcessError, e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000446 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
447 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000448 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000449 printed_path = True
450 while True:
451 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000452 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000453 action = ask_for_data(
454 'Cannot fast-forward merge, attempt to rebase? '
455 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000456 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000457 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000458 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000459 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000460 printed_path=printed_path)
461 printed_path = True
462 break
463 elif re.match(r'quit|q', action, re.I):
464 raise gclient_utils.Error("Can't fast-forward, please merge or "
465 "rebase manually.\n"
466 "cd %s && git " % self.checkout_path
467 + "rebase %s" % upstream_branch)
468 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000469 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470 return
471 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000472 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000473 elif re.match("error: Your local changes to '.*' would be "
474 "overwritten by merge. Aborting.\nPlease, commit your "
475 "changes or stash them before you can merge.\n",
476 e.stderr):
477 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000478 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000479 printed_path = True
480 raise gclient_utils.Error(e.stderr)
481 else:
482 # Some other problem happened with the merge
483 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000484 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000485 raise
486 else:
487 # Fast-forward merge was successful
488 if not re.match('Already up-to-date.', merge_output) or verbose:
489 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000490 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000491 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000492 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000493 if not verbose:
494 # Make the output a little prettier. It's nice to have some
495 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000496 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000497
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000498 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000499 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000500
501 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000502 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000503 raise gclient_utils.Error('\n____ %s%s\n'
504 '\nConflict while rebasing this branch.\n'
505 'Fix the conflict and run gclient again.\n'
506 'See man git-rebase for details.\n'
507 % (self.relpath, rev_str))
508
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000509 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000510 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000511
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000512 # If --reset and --delete_unversioned_trees are specified, remove any
513 # untracked directories.
514 if options.reset and options.delete_unversioned_trees:
515 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
516 # merge-base by default), so doesn't include untracked files. So we use
517 # 'git ls-files --directory --others --exclude-standard' here directly.
518 paths = scm.GIT.Capture(
519 ['ls-files', '--directory', '--others', '--exclude-standard'],
520 self.checkout_path)
521 for path in (p for p in paths.splitlines() if p.endswith('/')):
522 full_path = os.path.join(self.checkout_path, path)
523 if not os.path.islink(full_path):
524 print('\n_____ removing unversioned directory %s' % path)
525 gclient_utils.RemoveDirectory(full_path)
526
527
msb@chromium.orge28e4982009-09-25 20:51:45 +0000528 def revert(self, options, args, file_list):
529 """Reverts local modifications.
530
531 All reverted files will be appended to file_list.
532 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000533 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000534 # revert won't work if the directory doesn't exist. It needs to
535 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000536 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000537 # Don't reuse the args.
538 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000539
540 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000541 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000542 if not deps_revision:
543 deps_revision = default_rev
544 if deps_revision.startswith('refs/heads/'):
545 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
546
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000547 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000548 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000549 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000550 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
551
msb@chromium.org0f282062009-11-06 20:14:02 +0000552 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000553 """Returns revision"""
554 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000555
msb@chromium.orge28e4982009-09-25 20:51:45 +0000556 def runhooks(self, options, args, file_list):
557 self.status(options, args, file_list)
558
559 def status(self, options, args, file_list):
560 """Display status information."""
561 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000562 print(('\n________ couldn\'t run status in %s:\n'
563 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000564 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000565 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000566 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000567 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000568 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
569
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000570 def GetUsableRev(self, rev, options):
571 """Finds a useful revision for this repository.
572
573 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
574 will be called on the source."""
575 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000576 if not os.path.isdir(self.checkout_path):
577 raise gclient_utils.Error(
578 ( 'We could not find a valid hash for safesync_url response "%s".\n'
579 'Safesync URLs with a git checkout currently require the repo to\n'
580 'be cloned without a safesync_url before adding the safesync_url.\n'
581 'For more info, see: '
582 'http://code.google.com/p/chromium/wiki/UsingNewGit'
583 '#Initial_checkout' ) % rev)
584 elif rev.isdigit() and len(rev) < 7:
585 # Handles an SVN rev. As an optimization, only verify an SVN revision as
586 # [0-9]{1,6} for now to avoid making a network request.
587 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000588 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
589 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000590 try:
591 logging.debug('Looking for git-svn configuration optimizations.')
592 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
593 cwd=self.checkout_path):
594 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
595 except subprocess2.CalledProcessError:
596 logging.debug('git config --get svn-remote.svn.fetch failed, '
597 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000598 if options.verbose:
599 print('Running git svn fetch. This might take a while.\n')
600 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000601 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000602 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
603 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000604 except gclient_utils.Error, e:
605 sha1 = e.message
606 print('\nWarning: Could not find a git revision with accurate\n'
607 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
608 'the closest sane git revision, which is:\n'
609 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000610 if not sha1:
611 raise gclient_utils.Error(
612 ( 'It appears that either your git-svn remote is incorrectly\n'
613 'configured or the revision in your safesync_url is\n'
614 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
615 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000616 else:
617 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
618 sha1 = rev
619 else:
620 # May exist in origin, but we don't have it yet, so fetch and look
621 # again.
622 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
623 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
624 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000625
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000626 if not sha1:
627 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000628 ( 'We could not find a valid hash for safesync_url response "%s".\n'
629 'Safesync URLs with a git checkout currently require a git-svn\n'
630 'remote or a safesync_url that provides git sha1s. Please add a\n'
631 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000632 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000633 '#Initial_checkout' ) % rev)
634
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000635 return sha1
636
msb@chromium.orge6f78352010-01-13 17:05:33 +0000637 def FullUrlForRelativeUrl(self, url):
638 # Strip from last '/'
639 # Equivalent to unix basename
640 base_url = self.url
641 return base_url[:base_url.rfind('/')] + url
642
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000643 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000644 """Clone a git repository from the given URL.
645
msb@chromium.org786fb682010-06-02 15:16:23 +0000646 Once we've cloned the repo, we checkout a working branch if the specified
647 revision is a branch head. If it is a tag or a specific commit, then we
648 leave HEAD detached as it makes future updates simpler -- in this case the
649 user should first create a new branch or switch to an existing branch before
650 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000651 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000652 # git clone doesn't seem to insert a newline properly before printing
653 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000654 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000655
szager@google.com85d3e3a2011-10-07 17:12:00 +0000656 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000657 if revision.startswith('refs/heads/'):
658 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
659 detach_head = False
660 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000661 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000662 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000663 clone_cmd.append('--verbose')
664 clone_cmd.extend([url, self.checkout_path])
665
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000666 # If the parent directory does not exist, Git clone on Windows will not
667 # create it, so we need to do it manually.
668 parent_dir = os.path.dirname(self.checkout_path)
669 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000670 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000671
szager@google.com85d3e3a2011-10-07 17:12:00 +0000672 percent_re = re.compile('.* ([0-9]{1,2})% .*')
673 def _GitFilter(line):
674 # git uses an escape sequence to clear the line; elide it.
675 esc = line.find(unichr(033))
676 if esc > -1:
677 line = line[:esc]
678 match = percent_re.match(line)
679 if not match or not int(match.group(1)) % 10:
680 print '%s' % line
681
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000682 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000683 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000684 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
685 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000686 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000687 except subprocess2.CalledProcessError, e:
688 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000689 # We should check for "transfer closed with NNN bytes remaining to
690 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000691 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000692 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000693 print(str(e))
694 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000695 continue
696 raise e
697
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000698 # Update the "branch-heads" remote-tracking branches, since we might need it
699 # to checkout a specific revision below.
700 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org059cc452013-03-11 15:14:35 +0000701
msb@chromium.org786fb682010-06-02 15:16:23 +0000702 if detach_head:
703 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000704 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000705 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000706 ('Checked out %s to a detached HEAD. Before making any commits\n'
707 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
708 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
709 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000710
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000711 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000712 branch=None, printed_path=False):
713 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000714 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000715 revision = upstream
716 if newbase:
717 revision = newbase
718 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000719 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000720 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000721 printed_path = True
722 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000723 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000724
725 # Build the rebase command here using the args
726 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
727 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000728 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000729 rebase_cmd.append('--verbose')
730 if newbase:
731 rebase_cmd.extend(['--onto', newbase])
732 rebase_cmd.append(upstream)
733 if branch:
734 rebase_cmd.append(branch)
735
736 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000737 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000738 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000739 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
740 re.match(r'cannot rebase: your index contains uncommitted changes',
741 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000742 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000743 rebase_action = ask_for_data(
744 'Cannot rebase because of unstaged changes.\n'
745 '\'git reset --hard HEAD\' ?\n'
746 'WARNING: destroys any uncommitted work in your current branch!'
747 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000748 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000749 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000750 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000751 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000752 break
753 elif re.match(r'quit|q', rebase_action, re.I):
754 raise gclient_utils.Error("Please merge or rebase manually\n"
755 "cd %s && git " % self.checkout_path
756 + "%s" % ' '.join(rebase_cmd))
757 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000758 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000759 continue
760 else:
761 gclient_utils.Error("Input not recognized")
762 continue
763 elif re.search(r'^CONFLICT', e.stdout, re.M):
764 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
765 "Fix the conflict and run gclient again.\n"
766 "See 'man git-rebase' for details.\n")
767 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000768 print(e.stdout.strip())
769 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000770 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
771 "manually.\ncd %s && git " %
772 self.checkout_path
773 + "%s" % ' '.join(rebase_cmd))
774
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000775 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000776 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000777 # Make the output a little prettier. It's nice to have some
778 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000779 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000780
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000781 @staticmethod
782 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000783 (ok, current_version) = scm.GIT.AssertVersion(min_version)
784 if not ok:
785 raise gclient_utils.Error('git version %s < minimum required %s' %
786 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000787
msb@chromium.org786fb682010-06-02 15:16:23 +0000788 def _IsRebasing(self):
789 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
790 # have a plumbing command to determine whether a rebase is in progress, so
791 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
792 g = os.path.join(self.checkout_path, '.git')
793 return (
794 os.path.isdir(os.path.join(g, "rebase-merge")) or
795 os.path.isdir(os.path.join(g, "rebase-apply")))
796
797 def _CheckClean(self, rev_str):
798 # Make sure the tree is clean; see git-rebase.sh for reference
799 try:
800 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000801 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000802 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000803 raise gclient_utils.Error('\n____ %s%s\n'
804 '\tYou have unstaged changes.\n'
805 '\tPlease commit, stash, or reset.\n'
806 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000807 try:
808 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000809 '--ignore-submodules', 'HEAD', '--'],
810 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000811 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000812 raise gclient_utils.Error('\n____ %s%s\n'
813 '\tYour index contains uncommitted changes\n'
814 '\tPlease commit, stash, or reset.\n'
815 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000816
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000817 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000818 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
819 # reference by a commit). If not, error out -- most likely a rebase is
820 # in progress, try to detect so we can give a better error.
821 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000822 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
823 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000824 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000825 # Commit is not contained by any rev. See if the user is rebasing:
826 if self._IsRebasing():
827 # Punt to the user
828 raise gclient_utils.Error('\n____ %s%s\n'
829 '\tAlready in a conflict, i.e. (no branch).\n'
830 '\tFix the conflict and run gclient again.\n'
831 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
832 '\tSee man git-rebase for details.\n'
833 % (self.relpath, rev_str))
834 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000835 name = ('saved-by-gclient-' +
836 self._Capture(['rev-parse', '--short', 'HEAD']))
837 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000838 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000839 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000840
msb@chromium.org5bde4852009-12-14 16:47:12 +0000841 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000842 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000843 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000844 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000845 return None
846 return branch
847
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000848 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000849 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000850 ['git'] + args,
851 stderr=subprocess2.PIPE,
852 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000853
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000854 def _UpdateBranchHeads(self, options, fetch=False):
855 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
856 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
857 backoff_time = 5
858 for _ in range(3):
859 try:
860 config_cmd = ['config', 'remote.origin.fetch',
861 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
862 '^\\+refs/branch-heads/\\*:.*$']
863 self._Run(config_cmd, options)
864 if fetch:
865 fetch_cmd = ['fetch', 'origin']
866 if options.verbose:
867 fetch_cmd.append('--verbose')
868 self._Run(fetch_cmd, options)
869 break
870 except subprocess2.CalledProcessError, e:
871 print(str(e))
872 print('Retrying in %.1f seconds...' % backoff_time)
873 time.sleep(backoff_time)
874 backoff_time *= 1.3
875
maruel@chromium.org37e89872010-09-07 16:11:33 +0000876 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000877 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000878 kwargs.setdefault('print_stdout', True)
879 stdout = kwargs.get('stdout', sys.stdout)
880 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
881 ' '.join(args), kwargs['cwd']))
882 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000883
884
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000885class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000886 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000887
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000888 @staticmethod
889 def BinaryExists():
890 """Returns true if the command exists."""
891 try:
892 result, version = scm.SVN.AssertVersion('1.4')
893 if not result:
894 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
895 return result
896 except OSError:
897 return False
898
floitsch@google.comeaab7842011-04-28 09:07:58 +0000899 def GetRevisionDate(self, revision):
900 """Returns the given revision's date in ISO-8601 format (which contains the
901 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000902 date = scm.SVN.Capture(
903 ['propget', '--revprop', 'svn:date', '-r', revision],
904 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000905 return date.strip()
906
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000907 def cleanup(self, options, args, file_list):
908 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000909 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000910
911 def diff(self, options, args, file_list):
912 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000913 if not os.path.isdir(self.checkout_path):
914 raise gclient_utils.Error('Directory %s is not present.' %
915 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000916 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000917
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000918 def pack(self, options, args, file_list):
919 """Generates a patch file which can be applied to the root of the
920 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000921 if not os.path.isdir(self.checkout_path):
922 raise gclient_utils.Error('Directory %s is not present.' %
923 self.checkout_path)
924 gclient_utils.CheckCallAndFilter(
925 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
926 cwd=self.checkout_path,
927 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000928 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000929
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000930 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000931 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000932
933 All updated files will be appended to file_list.
934
935 Raises:
936 Error: if can't get URL for relative path.
937 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000938 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000939 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000940 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000941 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000942 return
943
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000944 hg_path = os.path.join(self.checkout_path, '.hg')
945 if os.path.exists(hg_path):
946 print('________ found .hg directory; skipping %s' % self.relpath)
947 return
948
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000949 if args:
950 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
951
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000952 # revision is the revision to match. It is None if no revision is specified,
953 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000954 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000955 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000956 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000957 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000958 if options.revision:
959 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000960 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000961 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000962 if revision != 'unmanaged':
963 forced_revision = True
964 # Reconstruct the url.
965 url = '%s@%s' % (url, revision)
966 rev_str = ' at %s' % revision
967 else:
968 managed = False
969 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000970 else:
971 forced_revision = False
972 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000973
davidjames@chromium.org13349e22012-11-15 17:11:28 +0000974 # Get the existing scm url and the revision number of the current checkout.
975 exists = os.path.exists(self.checkout_path)
976 if exists and managed:
977 try:
978 from_info = scm.SVN.CaptureLocalInfo(
979 [], os.path.join(self.checkout_path, '.'))
980 except (gclient_utils.Error, subprocess2.CalledProcessError):
981 if options.reset and options.delete_unversioned_trees:
982 print 'Removing troublesome path %s' % self.checkout_path
983 gclient_utils.rmtree(self.checkout_path)
984 exists = False
985 else:
986 msg = ('Can\'t update/checkout %s if an unversioned directory is '
987 'present. Delete the directory and try again.')
988 raise gclient_utils.Error(msg % self.checkout_path)
989
990 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000991 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000992 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000993 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000994 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000995 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000996 return
997
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000998 if not managed:
999 print ('________ unmanaged solution; skipping %s' % self.relpath)
1000 return
1001
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001002 if 'URL' not in from_info:
1003 raise gclient_utils.Error(
1004 ('gclient is confused. Couldn\'t get the url for %s.\n'
1005 'Try using @unmanaged.\n%s') % (
1006 self.checkout_path, from_info))
1007
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001008 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001009 dir_info = scm.SVN.CaptureStatus(
1010 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001011 if any(d[0][2] == 'L' for d in dir_info):
1012 try:
1013 self._Run(['cleanup', self.checkout_path], options)
1014 except subprocess2.CalledProcessError, e:
1015 # Get the status again, svn cleanup may have cleaned up at least
1016 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001017 dir_info = scm.SVN.CaptureStatus(
1018 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001019
1020 # Try to fix the failures by removing troublesome files.
1021 for d in dir_info:
1022 if d[0][2] == 'L':
1023 if d[0][0] == '!' and options.force:
1024 print 'Removing troublesome path %s' % d[1]
1025 gclient_utils.rmtree(d[1])
1026 else:
1027 print 'Not removing troublesome path %s automatically.' % d[1]
1028 if d[0][0] == '!':
1029 print 'You can pass --force to enable automatic removal.'
1030 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001031
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001032 # Retrieve the current HEAD version because svn is slow at null updates.
1033 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001034 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001035 revision = str(from_info_live['Revision'])
1036 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001037
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001038 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001039 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001040 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001041 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001042 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001043 # The url is invalid or the server is not accessible, it's safer to bail
1044 # out right now.
1045 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001046 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1047 and (from_info['UUID'] == to_info['UUID']))
1048 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001049 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001050 # We have different roots, so check if we can switch --relocate.
1051 # Subversion only permits this if the repository UUIDs match.
1052 # Perform the switch --relocate, then rewrite the from_url
1053 # to reflect where we "are now." (This is the same way that
1054 # Subversion itself handles the metadata when switch --relocate
1055 # is used.) This makes the checks below for whether we
1056 # can update to a revision or have to switch to a different
1057 # branch work as expected.
1058 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001059 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001060 from_info['Repository Root'],
1061 to_info['Repository Root'],
1062 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001063 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001064 from_info['URL'] = from_info['URL'].replace(
1065 from_info['Repository Root'],
1066 to_info['Repository Root'])
1067 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001068 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001069 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001070 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001071 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001072 raise gclient_utils.Error(
1073 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1074 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001075 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001076 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001077 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001078 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001079 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001080 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001081 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001082 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001083 return
1084
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001085 # If the provided url has a revision number that matches the revision
1086 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001087 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001088 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001089 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001090 else:
1091 command = ['update', self.checkout_path]
1092 command = self._AddAdditionalUpdateFlags(command, options, revision)
1093 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001094
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001095 # If --reset and --delete_unversioned_trees are specified, remove any
1096 # untracked files and directories.
1097 if options.reset and options.delete_unversioned_trees:
1098 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1099 full_path = os.path.join(self.checkout_path, status[1])
1100 if (status[0][0] == '?'
1101 and os.path.isdir(full_path)
1102 and not os.path.islink(full_path)):
1103 print('\n_____ removing unversioned directory %s' % status[1])
1104 gclient_utils.RemoveDirectory(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001105
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001106 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001107 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001108 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001109 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001110 # Create an empty checkout and then update the one file we want. Future
1111 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001112 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001113 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001114 if os.path.exists(os.path.join(self.checkout_path, filename)):
1115 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001116 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001117 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001118 # After the initial checkout, we can use update as if it were any other
1119 # dep.
1120 self.update(options, args, file_list)
1121 else:
1122 # If the installed version of SVN doesn't support --depth, fallback to
1123 # just exporting the file. This has the downside that revision
1124 # information is not stored next to the file, so we will have to
1125 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001126 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001127 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001128 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001129 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001130 command = self._AddAdditionalUpdateFlags(command, options,
1131 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001132 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001133
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001134 def revert(self, options, args, file_list):
1135 """Reverts local modifications. Subversion specific.
1136
1137 All reverted files will be appended to file_list, even if Subversion
1138 doesn't know about them.
1139 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001140 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001141 if os.path.exists(self.checkout_path):
1142 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001143 # svn revert won't work if the directory doesn't exist. It needs to
1144 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001145 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001146 # Don't reuse the args.
1147 return self.update(options, [], file_list)
1148
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001149 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1150 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1151 print('________ found .git directory; skipping %s' % self.relpath)
1152 return
1153 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1154 print('________ found .hg directory; skipping %s' % self.relpath)
1155 return
1156 if not options.force:
1157 raise gclient_utils.Error('Invalid checkout path, aborting')
1158 print(
1159 '\n_____ %s is not a valid svn checkout, synching instead' %
1160 self.relpath)
1161 gclient_utils.rmtree(self.checkout_path)
1162 # Don't reuse the args.
1163 return self.update(options, [], file_list)
1164
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001165 def printcb(file_status):
1166 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001167 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001168 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001169 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001170 print(os.path.join(self.checkout_path, file_status[1]))
1171 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001172
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001173 # Revert() may delete the directory altogether.
1174 if not os.path.isdir(self.checkout_path):
1175 # Don't reuse the args.
1176 return self.update(options, [], file_list)
1177
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001178 try:
1179 # svn revert is so broken we don't even use it. Using
1180 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001181 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001182 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1183 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001184 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001185 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001186 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001187
msb@chromium.org0f282062009-11-06 20:14:02 +00001188 def revinfo(self, options, args, file_list):
1189 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001190 try:
1191 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001192 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001193 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001194
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001195 def runhooks(self, options, args, file_list):
1196 self.status(options, args, file_list)
1197
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001198 def status(self, options, args, file_list):
1199 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001200 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001201 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001202 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001203 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1204 'The directory does not exist.') %
1205 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001206 # There's no file list to retrieve.
1207 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001208 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001209
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001210 def GetUsableRev(self, rev, options):
1211 """Verifies the validity of the revision for this repository."""
1212 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1213 raise gclient_utils.Error(
1214 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1215 'correct.') % rev)
1216 return rev
1217
msb@chromium.orge6f78352010-01-13 17:05:33 +00001218 def FullUrlForRelativeUrl(self, url):
1219 # Find the forth '/' and strip from there. A bit hackish.
1220 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001221
maruel@chromium.org669600d2010-09-01 19:06:31 +00001222 def _Run(self, args, options, **kwargs):
1223 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001224 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001225 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001226 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001227
1228 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1229 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001230 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001231 scm.SVN.RunAndGetFileList(
1232 options.verbose,
1233 args + ['--ignore-externals'],
1234 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001235 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001236
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001237 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001238 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001239 """Add additional flags to command depending on what options are set.
1240 command should be a list of strings that represents an svn command.
1241
1242 This method returns a new list to be used as a command."""
1243 new_command = command[:]
1244 if revision:
1245 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001246 # We don't want interaction when jobs are used.
1247 if options.jobs > 1:
1248 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001249 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001250 # --accept was added to 'svn update' in svn 1.6.
1251 if not scm.SVN.AssertVersion('1.5')[0]:
1252 return new_command
1253
1254 # It's annoying to have it block in the middle of a sync, just sensible
1255 # defaults.
1256 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001257 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001258 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1259 new_command.extend(('--accept', 'theirs-conflict'))
1260 elif options.manually_grab_svn_rev:
1261 new_command.append('--force')
1262 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1263 new_command.extend(('--accept', 'postpone'))
1264 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1265 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001266 return new_command