blob: 71fecd09f688dc3d699055ea503970ea3bb6eeed [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
szager@chromium.org71cbb502013-04-19 23:30:15 +000019THIS_FILE_PATH = os.path.abspath(__file__)
20
21
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000022class DiffFiltererWrapper(object):
23 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000024 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000025 working copy lines of the svn/git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000026 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000027 original_prefix = "--- "
28 working_prefix = "+++ "
29
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000030 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000031 # Note that we always use '/' as the path separator to be
32 # consistent with svn's cygwin-style output on Windows
33 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000034 self._current_file = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000035
maruel@chromium.org6e29d572010-06-04 17:32:20 +000036 def SetCurrentFile(self, current_file):
37 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000038
iannucci@chromium.org3830a672013-02-19 20:15:14 +000039 @property
40 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000041 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000042
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000043 def _Replace(self, line):
44 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000045
46 def Filter(self, line):
47 if (line.startswith(self.index_string)):
48 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000049 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000050 else:
51 if (line.startswith(self.original_prefix) or
52 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000053 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000054 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000055
56
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000057class SvnDiffFilterer(DiffFiltererWrapper):
58 index_string = "Index: "
59
60
61class GitDiffFilterer(DiffFiltererWrapper):
62 index_string = "diff --git "
63
64 def SetCurrentFile(self, current_file):
65 # Get filename by parsing "a/<filename> b/<filename>"
66 self._current_file = current_file[:(len(current_file)/2)][2:]
67
68 def _Replace(self, line):
69 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
70
71
maruel@chromium.org90541732011-04-01 17:54:18 +000072def ask_for_data(prompt):
73 try:
74 return raw_input(prompt)
75 except KeyboardInterrupt:
76 # Hide the exception.
77 sys.exit(1)
78
79
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000080### SCM abstraction layer
81
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000082# Factory Method for SCM wrapper creation
83
maruel@chromium.org9eda4112010-06-11 18:56:10 +000084def GetScmName(url):
85 if url:
86 url, _ = gclient_utils.SplitUrlRevision(url)
87 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000088 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000089 url.endswith('.git')):
90 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000091 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000092 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000093 return 'svn'
94 return None
95
96
97def CreateSCM(url, root_dir=None, relpath=None):
98 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000099 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +0000100 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000101 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000102
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000103 scm_name = GetScmName(url)
104 if not scm_name in SCM_MAP:
105 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000106 scm_class = SCM_MAP[scm_name]
107 if not scm_class.BinaryExists():
108 raise gclient_utils.Error('%s command not found' % scm_name)
109 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000110
111
112# SCMWrapper base class
113
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000114class SCMWrapper(object):
115 """Add necessary glue between all the supported SCM.
116
msb@chromium.orgd6504212010-01-13 17:34:31 +0000117 This is the abstraction layer to bind to different SCM.
118 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000119 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000120 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000121 self._root_dir = root_dir
122 if self._root_dir:
123 self._root_dir = self._root_dir.replace('/', os.sep)
124 self.relpath = relpath
125 if self.relpath:
126 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000127 if self.relpath and self._root_dir:
128 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000129
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000130 def RunCommand(self, command, options, args, file_list=None):
131 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000132 if file_list is None:
133 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000134
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000135 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000136 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000137
138 if not command in commands:
139 raise gclient_utils.Error('Unknown command %s' % command)
140
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000141 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000142 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000143 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000144
145 return getattr(self, command)(options, args, file_list)
146
147
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000148class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000149 """Wrapper for Git"""
150
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000151 def __init__(self, url=None, root_dir=None, relpath=None):
152 """Removes 'git+' fake prefix from git URL."""
153 if url.startswith('git+http://') or url.startswith('git+https://'):
154 url = url[4:]
155 SCMWrapper.__init__(self, url, root_dir, relpath)
156
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000157 @staticmethod
158 def BinaryExists():
159 """Returns true if the command exists."""
160 try:
161 # We assume git is newer than 1.7. See: crbug.com/114483
162 result, version = scm.GIT.AssertVersion('1.7')
163 if not result:
164 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
165 return result
166 except OSError:
167 return False
168
floitsch@google.comeaab7842011-04-28 09:07:58 +0000169 def GetRevisionDate(self, revision):
170 """Returns the given revision's date in ISO-8601 format (which contains the
171 time zone)."""
172 # TODO(floitsch): get the time-stamp of the given revision and not just the
173 # time-stamp of the currently checked out revision.
174 return self._Capture(['log', '-n', '1', '--format=%ai'])
175
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000176 @staticmethod
177 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000178 """'Cleanup' the repo.
179
180 There's no real git equivalent for the svn cleanup command, do a no-op.
181 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000182
183 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000184 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000185 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000186
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000187 def pack(self, options, args, file_list):
188 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000189 repository.
190
191 The patch file is generated from a diff of the merge base of HEAD and
192 its upstream branch.
193 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000194 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000195 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000196 ['git', 'diff', merge_base],
197 cwd=self.checkout_path,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000198 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000199
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000200 def UpdateSubmoduleConfig(self):
201 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
202 'submodule.$name.ignore', '||',
203 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000204 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000205 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000206 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000207 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000208 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000209 kwargs = {'cwd': self.checkout_path,
210 'print_stdout': False,
211 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000212 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000213 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
214 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000215 except subprocess2.CalledProcessError:
216 # Not a fatal error, or even very interesting in a non-git-submodule
217 # world. So just keep it quiet.
218 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000219 try:
220 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
221 except subprocess2.CalledProcessError:
222 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000223
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000224 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
225
msb@chromium.orge28e4982009-09-25 20:51:45 +0000226 def update(self, options, args, file_list):
227 """Runs git to update or transparently checkout the working copy.
228
229 All updated files will be appended to file_list.
230
231 Raises:
232 Error: if can't get URL for relative path.
233 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000234 if args:
235 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
236
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000237 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000238
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000239 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000240 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000241 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000242 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000243 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000244 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000245 # Override the revision number.
246 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000247 if revision == 'unmanaged':
248 revision = None
249 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000250 if not revision:
251 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000252
floitsch@google.comeaab7842011-04-28 09:07:58 +0000253 if gclient_utils.IsDateRevision(revision):
254 # Date-revisions only work on git-repositories if the reflog hasn't
255 # expired yet. Use rev-list to get the corresponding revision.
256 # git rev-list -n 1 --before='time-stamp' branchname
257 if options.transitive:
258 print('Warning: --transitive only works for SVN repositories.')
259 revision = default_rev
260
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000261 rev_str = ' at %s' % revision
262 files = []
263
264 printed_path = False
265 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000266 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000267 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000268 verbose = ['--verbose']
269 printed_path = True
270
271 if revision.startswith('refs/heads/'):
272 rev_type = "branch"
273 elif revision.startswith('origin/'):
274 # For compatability with old naming, translate 'origin' to 'refs/heads'
275 revision = revision.replace('origin/', 'refs/heads/')
276 rev_type = "branch"
277 else:
278 # hash is also a tag, only make a distinction at checkout
279 rev_type = "hash"
280
szager@google.com873e6672012-03-13 18:53:36 +0000281 if not os.path.exists(self.checkout_path) or (
282 os.path.isdir(self.checkout_path) and
283 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000284 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000285 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000286 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000287 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000288 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000289 if not verbose:
290 # Make the output a little prettier. It's nice to have some whitespace
291 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000292 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000293 return
294
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000295 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000296 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000297 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000298 print ('________ unmanaged solution; skipping %s' % self.relpath)
299 return
300
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000301 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
302 raise gclient_utils.Error('\n____ %s%s\n'
303 '\tPath is not a git repo. No .git dir.\n'
304 '\tTo resolve:\n'
305 '\t\trm -rf %s\n'
306 '\tAnd run gclient sync again\n'
307 % (self.relpath, rev_str, self.relpath))
308
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000309 # See if the url has changed (the unittests use git://foo for the url, let
310 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000311 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000312 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
313 # unit test pass. (and update the comment above)
314 if current_url != url and url != 'git://foo':
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000315 print('_____ switching %s to a new upstream' % self.relpath)
316 # Make sure it's clean
317 self._CheckClean(rev_str)
318 # Switch over to the new upstream
319 self._Run(['remote', 'set-url', 'origin', url], options)
320 quiet = []
321 if not options.verbose:
322 quiet = ['--quiet']
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000323 self._UpdateBranchHeads(options, fetch=False)
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000324 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
bauerb@chromium.org610060e2012-11-19 14:11:35 +0000325 self._Run(['reset', '--hard', revision] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000326 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000327 files = self._Capture(['ls-files']).splitlines()
328 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
329 return
330
msb@chromium.org5bde4852009-12-14 16:47:12 +0000331 cur_branch = self._GetCurrentBranch()
332
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000333 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000334 # 0) HEAD is detached. Probably from our initial clone.
335 # - make sure HEAD is contained by a named ref, then update.
336 # Cases 1-4. HEAD is a branch.
337 # 1) current branch is not tracking a remote branch (could be git-svn)
338 # - try to rebase onto the new hash or branch
339 # 2) current branch is tracking a remote branch with local committed
340 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000341 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000342 # 3) current branch is tracking a remote branch w/or w/out changes,
343 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000344 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000345 # 4) current branch is tracking a remote branch, switches to a different
346 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000347 # - exit
348
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000349 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
350 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000351 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
352 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000353 if cur_branch is None:
354 upstream_branch = None
355 current_type = "detached"
356 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000357 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000358 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
359 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
360 current_type = "hash"
361 logging.debug("Current branch is not tracking an upstream (remote)"
362 " branch.")
363 elif upstream_branch.startswith('refs/remotes'):
364 current_type = "branch"
365 else:
366 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000367
maruel@chromium.org92067382012-06-28 19:58:41 +0000368 if (not re.match(r'^[0-9a-fA-F]{40}$', revision) or
369 not scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=revision)):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000370 # Update the remotes first so we have all the refs.
371 backoff_time = 5
372 for _ in range(10):
373 try:
374 remote_output = scm.GIT.Capture(
375 ['remote'] + verbose + ['update'],
376 cwd=self.checkout_path)
377 break
378 except subprocess2.CalledProcessError, e:
379 # Hackish but at that point, git is known to work so just checking for
380 # 502 in stderr should be fine.
381 if '502' in e.stderr:
382 print(str(e))
383 print('Sleeping %.1f seconds and retrying...' % backoff_time)
384 time.sleep(backoff_time)
385 backoff_time *= 1.3
386 continue
387 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000388
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000389 if verbose:
390 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000391
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000392 self._UpdateBranchHeads(options, fetch=True)
393
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000394 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000395 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000396 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000397
msb@chromium.org786fb682010-06-02 15:16:23 +0000398 if current_type == 'detached':
399 # case 0
400 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000401 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000402 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000403 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000404 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000405 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000406 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000407 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000408 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000409 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000410 newbase=revision, printed_path=printed_path)
411 printed_path = True
412 else:
413 # Can't find a merge-base since we don't know our upstream. That makes
414 # this command VERY likely to produce a rebase failure. For now we
415 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000416 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000417 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000418 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000419 self._AttemptRebase(upstream_branch, files, options,
420 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000421 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000422 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000423 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000424 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000425 newbase=revision, printed_path=printed_path)
426 printed_path = True
427 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
428 # case 4
429 new_base = revision.replace('heads', 'remotes/origin')
430 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000431 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000432 switch_error = ("Switching upstream branch from %s to %s\n"
433 % (upstream_branch, new_base) +
434 "Please merge or rebase manually:\n" +
435 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
436 "OR git checkout -b <some new branch> %s" % new_base)
437 raise gclient_utils.Error(switch_error)
438 else:
439 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000440 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000441 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000442 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000443 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000444 merge_args = ['merge']
445 if not options.merge:
446 merge_args.append('--ff-only')
447 merge_args.append(upstream_branch)
448 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000449 except subprocess2.CalledProcessError, e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000450 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
451 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000452 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000453 printed_path = True
454 while True:
455 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000456 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000457 action = ask_for_data(
458 'Cannot fast-forward merge, attempt to rebase? '
459 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000460 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000461 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000462 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000463 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000464 printed_path=printed_path)
465 printed_path = True
466 break
467 elif re.match(r'quit|q', action, re.I):
468 raise gclient_utils.Error("Can't fast-forward, please merge or "
469 "rebase manually.\n"
470 "cd %s && git " % self.checkout_path
471 + "rebase %s" % upstream_branch)
472 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000473 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000474 return
475 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000476 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000477 elif re.match("error: Your local changes to '.*' would be "
478 "overwritten by merge. Aborting.\nPlease, commit your "
479 "changes or stash them before you can merge.\n",
480 e.stderr):
481 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000482 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 printed_path = True
484 raise gclient_utils.Error(e.stderr)
485 else:
486 # Some other problem happened with the merge
487 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000488 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000489 raise
490 else:
491 # Fast-forward merge was successful
492 if not re.match('Already up-to-date.', merge_output) or verbose:
493 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000494 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000495 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000496 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000497 if not verbose:
498 # Make the output a little prettier. It's nice to have some
499 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000500 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000501
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000502 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000503 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000504
505 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000506 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000507 raise gclient_utils.Error('\n____ %s%s\n'
508 '\nConflict while rebasing this branch.\n'
509 'Fix the conflict and run gclient again.\n'
510 'See man git-rebase for details.\n'
511 % (self.relpath, rev_str))
512
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000513 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000514 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000515
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000516 # If --reset and --delete_unversioned_trees are specified, remove any
517 # untracked directories.
518 if options.reset and options.delete_unversioned_trees:
519 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
520 # merge-base by default), so doesn't include untracked files. So we use
521 # 'git ls-files --directory --others --exclude-standard' here directly.
522 paths = scm.GIT.Capture(
523 ['ls-files', '--directory', '--others', '--exclude-standard'],
524 self.checkout_path)
525 for path in (p for p in paths.splitlines() if p.endswith('/')):
526 full_path = os.path.join(self.checkout_path, path)
527 if not os.path.islink(full_path):
528 print('\n_____ removing unversioned directory %s' % path)
529 gclient_utils.RemoveDirectory(full_path)
530
531
msb@chromium.orge28e4982009-09-25 20:51:45 +0000532 def revert(self, options, args, file_list):
533 """Reverts local modifications.
534
535 All reverted files will be appended to file_list.
536 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000537 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000538 # revert won't work if the directory doesn't exist. It needs to
539 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000540 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000541 # Don't reuse the args.
542 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000543
544 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000545 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000546 if not deps_revision:
547 deps_revision = default_rev
548 if deps_revision.startswith('refs/heads/'):
549 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
550
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000551 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000552 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000553 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000554 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
555
msb@chromium.org0f282062009-11-06 20:14:02 +0000556 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000557 """Returns revision"""
558 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000559
msb@chromium.orge28e4982009-09-25 20:51:45 +0000560 def runhooks(self, options, args, file_list):
561 self.status(options, args, file_list)
562
563 def status(self, options, args, file_list):
564 """Display status information."""
565 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000566 print(('\n________ couldn\'t run status in %s:\n'
567 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000568 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000569 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000570 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000571 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000572 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
573
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000574 def GetUsableRev(self, rev, options):
575 """Finds a useful revision for this repository.
576
577 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
578 will be called on the source."""
579 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000580 if not os.path.isdir(self.checkout_path):
581 raise gclient_utils.Error(
582 ( 'We could not find a valid hash for safesync_url response "%s".\n'
583 'Safesync URLs with a git checkout currently require the repo to\n'
584 'be cloned without a safesync_url before adding the safesync_url.\n'
585 'For more info, see: '
586 'http://code.google.com/p/chromium/wiki/UsingNewGit'
587 '#Initial_checkout' ) % rev)
588 elif rev.isdigit() and len(rev) < 7:
589 # Handles an SVN rev. As an optimization, only verify an SVN revision as
590 # [0-9]{1,6} for now to avoid making a network request.
591 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000592 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
593 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000594 try:
595 logging.debug('Looking for git-svn configuration optimizations.')
596 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
597 cwd=self.checkout_path):
598 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
599 except subprocess2.CalledProcessError:
600 logging.debug('git config --get svn-remote.svn.fetch failed, '
601 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000602 if options.verbose:
603 print('Running git svn fetch. This might take a while.\n')
604 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000605 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000606 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
607 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000608 except gclient_utils.Error, e:
609 sha1 = e.message
610 print('\nWarning: Could not find a git revision with accurate\n'
611 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
612 'the closest sane git revision, which is:\n'
613 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000614 if not sha1:
615 raise gclient_utils.Error(
616 ( 'It appears that either your git-svn remote is incorrectly\n'
617 'configured or the revision in your safesync_url is\n'
618 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
619 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000620 else:
621 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
622 sha1 = rev
623 else:
624 # May exist in origin, but we don't have it yet, so fetch and look
625 # again.
626 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
627 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
628 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000629
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000630 if not sha1:
631 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000632 ( 'We could not find a valid hash for safesync_url response "%s".\n'
633 'Safesync URLs with a git checkout currently require a git-svn\n'
634 'remote or a safesync_url that provides git sha1s. Please add a\n'
635 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000636 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000637 '#Initial_checkout' ) % rev)
638
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000639 return sha1
640
msb@chromium.orge6f78352010-01-13 17:05:33 +0000641 def FullUrlForRelativeUrl(self, url):
642 # Strip from last '/'
643 # Equivalent to unix basename
644 base_url = self.url
645 return base_url[:base_url.rfind('/')] + url
646
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000647 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000648 """Clone a git repository from the given URL.
649
msb@chromium.org786fb682010-06-02 15:16:23 +0000650 Once we've cloned the repo, we checkout a working branch if the specified
651 revision is a branch head. If it is a tag or a specific commit, then we
652 leave HEAD detached as it makes future updates simpler -- in this case the
653 user should first create a new branch or switch to an existing branch before
654 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000655 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000656 # git clone doesn't seem to insert a newline properly before printing
657 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000658 print('')
szager@chromium.org71cbb502013-04-19 23:30:15 +0000659 template_path = os.path.join(
660 os.path.dirname(THIS_FILE_PATH), 'git-templates')
661 clone_cmd = ['clone', '--progress', '--template=%s' % template_path]
msb@chromium.org786fb682010-06-02 15:16:23 +0000662 if revision.startswith('refs/heads/'):
663 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
664 detach_head = False
665 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000666 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000667 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000668 clone_cmd.append('--verbose')
669 clone_cmd.extend([url, self.checkout_path])
670
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000671 # If the parent directory does not exist, Git clone on Windows will not
672 # create it, so we need to do it manually.
673 parent_dir = os.path.dirname(self.checkout_path)
674 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000675 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000676
szager@google.com85d3e3a2011-10-07 17:12:00 +0000677 percent_re = re.compile('.* ([0-9]{1,2})% .*')
678 def _GitFilter(line):
679 # git uses an escape sequence to clear the line; elide it.
680 esc = line.find(unichr(033))
681 if esc > -1:
682 line = line[:esc]
683 match = percent_re.match(line)
684 if not match or not int(match.group(1)) % 10:
685 print '%s' % line
686
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000687 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000688 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000689 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
690 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000691 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000692 except subprocess2.CalledProcessError, e:
693 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000694 # We should check for "transfer closed with NNN bytes remaining to
695 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000696 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000697 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000698 print(str(e))
699 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000700 continue
701 raise e
702
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000703 # Update the "branch-heads" remote-tracking branches, since we might need it
704 # to checkout a specific revision below.
705 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org059cc452013-03-11 15:14:35 +0000706
msb@chromium.org786fb682010-06-02 15:16:23 +0000707 if detach_head:
708 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000709 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000710 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000711 ('Checked out %s to a detached HEAD. Before making any commits\n'
712 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
713 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
714 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000715
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000716 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000717 branch=None, printed_path=False):
718 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000719 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000720 revision = upstream
721 if newbase:
722 revision = newbase
723 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000724 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000725 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000726 printed_path = True
727 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000728 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000729
730 # Build the rebase command here using the args
731 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
732 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000733 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000734 rebase_cmd.append('--verbose')
735 if newbase:
736 rebase_cmd.extend(['--onto', newbase])
737 rebase_cmd.append(upstream)
738 if branch:
739 rebase_cmd.append(branch)
740
741 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000742 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000743 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000744 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
745 re.match(r'cannot rebase: your index contains uncommitted changes',
746 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000747 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000748 rebase_action = ask_for_data(
749 'Cannot rebase because of unstaged changes.\n'
750 '\'git reset --hard HEAD\' ?\n'
751 'WARNING: destroys any uncommitted work in your current branch!'
752 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000753 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000754 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000755 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000756 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000757 break
758 elif re.match(r'quit|q', rebase_action, re.I):
759 raise gclient_utils.Error("Please merge or rebase manually\n"
760 "cd %s && git " % self.checkout_path
761 + "%s" % ' '.join(rebase_cmd))
762 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000763 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000764 continue
765 else:
766 gclient_utils.Error("Input not recognized")
767 continue
768 elif re.search(r'^CONFLICT', e.stdout, re.M):
769 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
770 "Fix the conflict and run gclient again.\n"
771 "See 'man git-rebase' for details.\n")
772 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000773 print(e.stdout.strip())
774 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000775 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
776 "manually.\ncd %s && git " %
777 self.checkout_path
778 + "%s" % ' '.join(rebase_cmd))
779
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000780 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000781 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000782 # Make the output a little prettier. It's nice to have some
783 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000784 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000785
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000786 @staticmethod
787 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000788 (ok, current_version) = scm.GIT.AssertVersion(min_version)
789 if not ok:
790 raise gclient_utils.Error('git version %s < minimum required %s' %
791 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000792
msb@chromium.org786fb682010-06-02 15:16:23 +0000793 def _IsRebasing(self):
794 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
795 # have a plumbing command to determine whether a rebase is in progress, so
796 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
797 g = os.path.join(self.checkout_path, '.git')
798 return (
799 os.path.isdir(os.path.join(g, "rebase-merge")) or
800 os.path.isdir(os.path.join(g, "rebase-apply")))
801
802 def _CheckClean(self, rev_str):
803 # Make sure the tree is clean; see git-rebase.sh for reference
804 try:
805 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000806 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000807 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000808 raise gclient_utils.Error('\n____ %s%s\n'
809 '\tYou have unstaged changes.\n'
810 '\tPlease commit, stash, or reset.\n'
811 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000812 try:
813 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000814 '--ignore-submodules', 'HEAD', '--'],
815 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000816 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000817 raise gclient_utils.Error('\n____ %s%s\n'
818 '\tYour index contains uncommitted changes\n'
819 '\tPlease commit, stash, or reset.\n'
820 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000821
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000822 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000823 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
824 # reference by a commit). If not, error out -- most likely a rebase is
825 # in progress, try to detect so we can give a better error.
826 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000827 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
828 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000829 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000830 # Commit is not contained by any rev. See if the user is rebasing:
831 if self._IsRebasing():
832 # Punt to the user
833 raise gclient_utils.Error('\n____ %s%s\n'
834 '\tAlready in a conflict, i.e. (no branch).\n'
835 '\tFix the conflict and run gclient again.\n'
836 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
837 '\tSee man git-rebase for details.\n'
838 % (self.relpath, rev_str))
839 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000840 name = ('saved-by-gclient-' +
841 self._Capture(['rev-parse', '--short', 'HEAD']))
842 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000843 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000844 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000845
msb@chromium.org5bde4852009-12-14 16:47:12 +0000846 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000847 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000848 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000849 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000850 return None
851 return branch
852
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000853 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000854 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000855 ['git'] + args,
856 stderr=subprocess2.PIPE,
857 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000858
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000859 def _UpdateBranchHeads(self, options, fetch=False):
860 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
861 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
862 backoff_time = 5
863 for _ in range(3):
864 try:
865 config_cmd = ['config', 'remote.origin.fetch',
866 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
867 '^\\+refs/branch-heads/\\*:.*$']
868 self._Run(config_cmd, options)
869 if fetch:
870 fetch_cmd = ['fetch', 'origin']
871 if options.verbose:
872 fetch_cmd.append('--verbose')
873 self._Run(fetch_cmd, options)
874 break
875 except subprocess2.CalledProcessError, e:
876 print(str(e))
877 print('Retrying in %.1f seconds...' % backoff_time)
878 time.sleep(backoff_time)
879 backoff_time *= 1.3
880
maruel@chromium.org37e89872010-09-07 16:11:33 +0000881 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000882 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000883 kwargs.setdefault('print_stdout', True)
884 stdout = kwargs.get('stdout', sys.stdout)
885 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
886 ' '.join(args), kwargs['cwd']))
887 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000888
889
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000890class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000891 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000892
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000893 @staticmethod
894 def BinaryExists():
895 """Returns true if the command exists."""
896 try:
897 result, version = scm.SVN.AssertVersion('1.4')
898 if not result:
899 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
900 return result
901 except OSError:
902 return False
903
floitsch@google.comeaab7842011-04-28 09:07:58 +0000904 def GetRevisionDate(self, revision):
905 """Returns the given revision's date in ISO-8601 format (which contains the
906 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000907 date = scm.SVN.Capture(
908 ['propget', '--revprop', 'svn:date', '-r', revision],
909 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000910 return date.strip()
911
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000912 def cleanup(self, options, args, file_list):
913 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000914 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000915
916 def diff(self, options, args, file_list):
917 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000918 if not os.path.isdir(self.checkout_path):
919 raise gclient_utils.Error('Directory %s is not present.' %
920 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000921 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000922
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000923 def pack(self, options, args, file_list):
924 """Generates a patch file which can be applied to the root of the
925 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000926 if not os.path.isdir(self.checkout_path):
927 raise gclient_utils.Error('Directory %s is not present.' %
928 self.checkout_path)
929 gclient_utils.CheckCallAndFilter(
930 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
931 cwd=self.checkout_path,
932 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000933 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000934
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000935 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000936 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000937
938 All updated files will be appended to file_list.
939
940 Raises:
941 Error: if can't get URL for relative path.
942 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000943 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000944 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000945 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000946 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000947 return
948
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000949 hg_path = os.path.join(self.checkout_path, '.hg')
950 if os.path.exists(hg_path):
951 print('________ found .hg directory; skipping %s' % self.relpath)
952 return
953
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000954 if args:
955 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
956
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000957 # revision is the revision to match. It is None if no revision is specified,
958 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000959 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000960 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000961 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000962 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000963 if options.revision:
964 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000965 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000966 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000967 if revision != 'unmanaged':
968 forced_revision = True
969 # Reconstruct the url.
970 url = '%s@%s' % (url, revision)
971 rev_str = ' at %s' % revision
972 else:
973 managed = False
974 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000975 else:
976 forced_revision = False
977 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000978
davidjames@chromium.org13349e22012-11-15 17:11:28 +0000979 # Get the existing scm url and the revision number of the current checkout.
980 exists = os.path.exists(self.checkout_path)
981 if exists and managed:
982 try:
983 from_info = scm.SVN.CaptureLocalInfo(
984 [], os.path.join(self.checkout_path, '.'))
985 except (gclient_utils.Error, subprocess2.CalledProcessError):
986 if options.reset and options.delete_unversioned_trees:
987 print 'Removing troublesome path %s' % self.checkout_path
988 gclient_utils.rmtree(self.checkout_path)
989 exists = False
990 else:
991 msg = ('Can\'t update/checkout %s if an unversioned directory is '
992 'present. Delete the directory and try again.')
993 raise gclient_utils.Error(msg % self.checkout_path)
994
995 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000996 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000997 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000998 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000999 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001000 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001001 return
1002
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001003 if not managed:
1004 print ('________ unmanaged solution; skipping %s' % self.relpath)
1005 return
1006
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001007 if 'URL' not in from_info:
1008 raise gclient_utils.Error(
1009 ('gclient is confused. Couldn\'t get the url for %s.\n'
1010 'Try using @unmanaged.\n%s') % (
1011 self.checkout_path, from_info))
1012
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001013 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001014 dir_info = scm.SVN.CaptureStatus(
1015 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001016 if any(d[0][2] == 'L' for d in dir_info):
1017 try:
1018 self._Run(['cleanup', self.checkout_path], options)
1019 except subprocess2.CalledProcessError, e:
1020 # Get the status again, svn cleanup may have cleaned up at least
1021 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001022 dir_info = scm.SVN.CaptureStatus(
1023 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001024
1025 # Try to fix the failures by removing troublesome files.
1026 for d in dir_info:
1027 if d[0][2] == 'L':
1028 if d[0][0] == '!' and options.force:
1029 print 'Removing troublesome path %s' % d[1]
1030 gclient_utils.rmtree(d[1])
1031 else:
1032 print 'Not removing troublesome path %s automatically.' % d[1]
1033 if d[0][0] == '!':
1034 print 'You can pass --force to enable automatic removal.'
1035 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001036
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001037 # Retrieve the current HEAD version because svn is slow at null updates.
1038 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001039 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001040 revision = str(from_info_live['Revision'])
1041 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001042
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001043 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001044 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001045 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001046 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001047 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001048 # The url is invalid or the server is not accessible, it's safer to bail
1049 # out right now.
1050 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001051 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1052 and (from_info['UUID'] == to_info['UUID']))
1053 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001054 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001055 # We have different roots, so check if we can switch --relocate.
1056 # Subversion only permits this if the repository UUIDs match.
1057 # Perform the switch --relocate, then rewrite the from_url
1058 # to reflect where we "are now." (This is the same way that
1059 # Subversion itself handles the metadata when switch --relocate
1060 # is used.) This makes the checks below for whether we
1061 # can update to a revision or have to switch to a different
1062 # branch work as expected.
1063 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001064 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001065 from_info['Repository Root'],
1066 to_info['Repository Root'],
1067 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001068 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001069 from_info['URL'] = from_info['URL'].replace(
1070 from_info['Repository Root'],
1071 to_info['Repository Root'])
1072 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001073 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001074 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001075 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001076 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001077 raise gclient_utils.Error(
1078 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1079 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001080 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001081 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001082 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001083 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001084 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001085 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001086 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001087 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001088 return
1089
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001090 # If the provided url has a revision number that matches the revision
1091 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001092 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001093 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001094 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001095 else:
1096 command = ['update', self.checkout_path]
1097 command = self._AddAdditionalUpdateFlags(command, options, revision)
1098 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001099
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001100 # If --reset and --delete_unversioned_trees are specified, remove any
1101 # untracked files and directories.
1102 if options.reset and options.delete_unversioned_trees:
1103 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1104 full_path = os.path.join(self.checkout_path, status[1])
1105 if (status[0][0] == '?'
1106 and os.path.isdir(full_path)
1107 and not os.path.islink(full_path)):
1108 print('\n_____ removing unversioned directory %s' % status[1])
1109 gclient_utils.RemoveDirectory(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001110
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001111 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001112 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001113 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001114 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001115 # Create an empty checkout and then update the one file we want. Future
1116 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001117 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001118 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001119 if os.path.exists(os.path.join(self.checkout_path, filename)):
1120 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001121 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001122 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001123 # After the initial checkout, we can use update as if it were any other
1124 # dep.
1125 self.update(options, args, file_list)
1126 else:
1127 # If the installed version of SVN doesn't support --depth, fallback to
1128 # just exporting the file. This has the downside that revision
1129 # information is not stored next to the file, so we will have to
1130 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001131 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001132 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001133 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001134 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001135 command = self._AddAdditionalUpdateFlags(command, options,
1136 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001137 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001138
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001139 def revert(self, options, args, file_list):
1140 """Reverts local modifications. Subversion specific.
1141
1142 All reverted files will be appended to file_list, even if Subversion
1143 doesn't know about them.
1144 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001145 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001146 if os.path.exists(self.checkout_path):
1147 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001148 # svn revert won't work if the directory doesn't exist. It needs to
1149 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001150 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001151 # Don't reuse the args.
1152 return self.update(options, [], file_list)
1153
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001154 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1155 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1156 print('________ found .git directory; skipping %s' % self.relpath)
1157 return
1158 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1159 print('________ found .hg directory; skipping %s' % self.relpath)
1160 return
1161 if not options.force:
1162 raise gclient_utils.Error('Invalid checkout path, aborting')
1163 print(
1164 '\n_____ %s is not a valid svn checkout, synching instead' %
1165 self.relpath)
1166 gclient_utils.rmtree(self.checkout_path)
1167 # Don't reuse the args.
1168 return self.update(options, [], file_list)
1169
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001170 def printcb(file_status):
1171 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001172 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001173 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001174 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001175 print(os.path.join(self.checkout_path, file_status[1]))
1176 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001177
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001178 # Revert() may delete the directory altogether.
1179 if not os.path.isdir(self.checkout_path):
1180 # Don't reuse the args.
1181 return self.update(options, [], file_list)
1182
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001183 try:
1184 # svn revert is so broken we don't even use it. Using
1185 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001186 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001187 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1188 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001189 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001190 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001191 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001192
msb@chromium.org0f282062009-11-06 20:14:02 +00001193 def revinfo(self, options, args, file_list):
1194 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001195 try:
1196 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001197 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001198 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001199
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001200 def runhooks(self, options, args, file_list):
1201 self.status(options, args, file_list)
1202
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001203 def status(self, options, args, file_list):
1204 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001205 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001206 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001207 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001208 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1209 'The directory does not exist.') %
1210 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001211 # There's no file list to retrieve.
1212 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001213 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001214
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001215 def GetUsableRev(self, rev, options):
1216 """Verifies the validity of the revision for this repository."""
1217 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1218 raise gclient_utils.Error(
1219 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1220 'correct.') % rev)
1221 return rev
1222
msb@chromium.orge6f78352010-01-13 17:05:33 +00001223 def FullUrlForRelativeUrl(self, url):
1224 # Find the forth '/' and strip from there. A bit hackish.
1225 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001226
maruel@chromium.org669600d2010-09-01 19:06:31 +00001227 def _Run(self, args, options, **kwargs):
1228 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001229 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001230 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001231 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001232
1233 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1234 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001235 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001236 scm.SVN.RunAndGetFileList(
1237 options.verbose,
1238 args + ['--ignore-externals'],
1239 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001240 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001241
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001242 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001243 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001244 """Add additional flags to command depending on what options are set.
1245 command should be a list of strings that represents an svn command.
1246
1247 This method returns a new list to be used as a command."""
1248 new_command = command[:]
1249 if revision:
1250 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001251 # We don't want interaction when jobs are used.
1252 if options.jobs > 1:
1253 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001254 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001255 # --accept was added to 'svn update' in svn 1.6.
1256 if not scm.SVN.AssertVersion('1.5')[0]:
1257 return new_command
1258
1259 # It's annoying to have it block in the middle of a sync, just sensible
1260 # defaults.
1261 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001262 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001263 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1264 new_command.extend(('--accept', 'theirs-conflict'))
1265 elif options.manually_grab_svn_rev:
1266 new_command.append('--force')
1267 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1268 new_command.extend(('--accept', 'postpone'))
1269 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1270 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001271 return new_command