blob: 3e8f59c9ba837fb02eea5a3974bb96183c11e250 [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
bratell@opera.com18fa4542013-05-21 13:30:46 +000072def ask_for_data(prompt, options):
73 if options.jobs > 1:
74 raise gclient_utils.Error("Background task requires input. Rerun "
75 "gclient with --jobs=1 so that\n"
76 "interaction is possible.")
maruel@chromium.org90541732011-04-01 17:54:18 +000077 try:
78 return raw_input(prompt)
79 except KeyboardInterrupt:
80 # Hide the exception.
81 sys.exit(1)
82
83
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000084### SCM abstraction layer
85
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000086# Factory Method for SCM wrapper creation
87
maruel@chromium.org9eda4112010-06-11 18:56:10 +000088def GetScmName(url):
89 if url:
90 url, _ = gclient_utils.SplitUrlRevision(url)
91 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000092 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000093 url.endswith('.git')):
94 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000095 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000096 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000097 return 'svn'
98 return None
99
100
101def CreateSCM(url, root_dir=None, relpath=None):
102 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000103 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +0000104 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000105 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000106
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000107 scm_name = GetScmName(url)
108 if not scm_name in SCM_MAP:
109 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000110 scm_class = SCM_MAP[scm_name]
111 if not scm_class.BinaryExists():
112 raise gclient_utils.Error('%s command not found' % scm_name)
113 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000114
115
116# SCMWrapper base class
117
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000118class SCMWrapper(object):
119 """Add necessary glue between all the supported SCM.
120
msb@chromium.orgd6504212010-01-13 17:34:31 +0000121 This is the abstraction layer to bind to different SCM.
122 """
szager@chromium.org12b07e72013-05-03 22:06:34 +0000123 nag_timer = 30
szager@chromium.org41da24b2013-05-23 19:37:04 +0000124 nag_max = 6
szager@chromium.org12b07e72013-05-03 22:06:34 +0000125
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000126 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000127 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000128 self._root_dir = root_dir
129 if self._root_dir:
130 self._root_dir = self._root_dir.replace('/', os.sep)
131 self.relpath = relpath
132 if self.relpath:
133 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000134 if self.relpath and self._root_dir:
135 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000136
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000137 def RunCommand(self, command, options, args, file_list=None):
138 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000139 if file_list is None:
140 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000141
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000142 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000143 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000144
145 if not command in commands:
146 raise gclient_utils.Error('Unknown command %s' % command)
147
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000148 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000149 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000150 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000151
152 return getattr(self, command)(options, args, file_list)
153
154
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000155class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000156 """Wrapper for Git"""
157
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000158 def __init__(self, url=None, root_dir=None, relpath=None):
159 """Removes 'git+' fake prefix from git URL."""
160 if url.startswith('git+http://') or url.startswith('git+https://'):
161 url = url[4:]
162 SCMWrapper.__init__(self, url, root_dir, relpath)
163
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000164 @staticmethod
165 def BinaryExists():
166 """Returns true if the command exists."""
167 try:
168 # We assume git is newer than 1.7. See: crbug.com/114483
169 result, version = scm.GIT.AssertVersion('1.7')
170 if not result:
171 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
172 return result
173 except OSError:
174 return False
175
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000176 def GetCheckoutRoot(self):
177 return scm.GIT.GetCheckoutRoot(self.checkout_path)
178
floitsch@google.comeaab7842011-04-28 09:07:58 +0000179 def GetRevisionDate(self, revision):
180 """Returns the given revision's date in ISO-8601 format (which contains the
181 time zone)."""
182 # TODO(floitsch): get the time-stamp of the given revision and not just the
183 # time-stamp of the currently checked out revision.
184 return self._Capture(['log', '-n', '1', '--format=%ai'])
185
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000186 @staticmethod
187 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000188 """'Cleanup' the repo.
189
190 There's no real git equivalent for the svn cleanup command, do a no-op.
191 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000192
193 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000194 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000195 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000196
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000197 def pack(self, options, args, file_list):
198 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000199 repository.
200
201 The patch file is generated from a diff of the merge base of HEAD and
202 its upstream branch.
203 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000204 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000205 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000206 ['git', 'diff', merge_base],
207 cwd=self.checkout_path,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000208 nag_timer=self.nag_timer,
209 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000210 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000211
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000212 def UpdateSubmoduleConfig(self):
213 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
214 'submodule.$name.ignore', '||',
215 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000216 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000217 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000218 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000219 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000220 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000221 kwargs = {'cwd': self.checkout_path,
222 'print_stdout': False,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000223 'nag_timer': self.nag_timer,
224 'nag_max': self.nag_max,
szager@chromium.org987b0612012-07-09 23:41:08 +0000225 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000226 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000227 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
228 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000229 except subprocess2.CalledProcessError:
230 # Not a fatal error, or even very interesting in a non-git-submodule
231 # world. So just keep it quiet.
232 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000233 try:
234 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
235 except subprocess2.CalledProcessError:
236 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000237
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000238 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
239
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000240 def _FetchAndReset(self, revision, file_list, options):
241 """Equivalent to git fetch; git reset."""
242 quiet = []
243 if not options.verbose:
244 quiet = ['--quiet']
245 self._UpdateBranchHeads(options, fetch=False)
246 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
247 self._Run(['reset', '--hard', revision] + quiet, options)
248 self.UpdateSubmoduleConfig()
249 files = self._Capture(['ls-files']).splitlines()
250 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
251
msb@chromium.orge28e4982009-09-25 20:51:45 +0000252 def update(self, options, args, file_list):
253 """Runs git to update or transparently checkout the working copy.
254
255 All updated files will be appended to file_list.
256
257 Raises:
258 Error: if can't get URL for relative path.
259 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000260 if args:
261 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
262
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000263 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000264
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000265 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000266 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000267 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000268 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000269 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000270 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000271 # Override the revision number.
272 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000273 if revision == 'unmanaged':
274 revision = None
275 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000276 if not revision:
277 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000278
floitsch@google.comeaab7842011-04-28 09:07:58 +0000279 if gclient_utils.IsDateRevision(revision):
280 # Date-revisions only work on git-repositories if the reflog hasn't
281 # expired yet. Use rev-list to get the corresponding revision.
282 # git rev-list -n 1 --before='time-stamp' branchname
283 if options.transitive:
284 print('Warning: --transitive only works for SVN repositories.')
285 revision = default_rev
286
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000287 rev_str = ' at %s' % revision
288 files = []
289
290 printed_path = False
291 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000292 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000293 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000294 verbose = ['--verbose']
295 printed_path = True
296
297 if revision.startswith('refs/heads/'):
298 rev_type = "branch"
299 elif revision.startswith('origin/'):
300 # For compatability with old naming, translate 'origin' to 'refs/heads'
301 revision = revision.replace('origin/', 'refs/heads/')
302 rev_type = "branch"
303 else:
304 # hash is also a tag, only make a distinction at checkout
305 rev_type = "hash"
306
szager@google.com873e6672012-03-13 18:53:36 +0000307 if not os.path.exists(self.checkout_path) or (
308 os.path.isdir(self.checkout_path) and
309 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000310 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000311 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000312 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000313 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000314 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000315 if not verbose:
316 # Make the output a little prettier. It's nice to have some whitespace
317 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000318 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000319 return
320
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000321 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000322 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000323 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000324 print ('________ unmanaged solution; skipping %s' % self.relpath)
325 return
326
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000327 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
328 raise gclient_utils.Error('\n____ %s%s\n'
329 '\tPath is not a git repo. No .git dir.\n'
330 '\tTo resolve:\n'
331 '\t\trm -rf %s\n'
332 '\tAnd run gclient sync again\n'
333 % (self.relpath, rev_str, self.relpath))
334
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000335 # See if the url has changed (the unittests use git://foo for the url, let
336 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000337 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000338 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
339 # unit test pass. (and update the comment above)
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000340 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
341 # This allows devs to use experimental repos which have a different url
342 # but whose branch(s) are the same as official repos.
343 if (current_url != url and
344 url != 'git://foo' and
345 subprocess2.capture(
346 ['git', 'config', 'remote.origin.gclient-auto-fix-url'],
347 cwd=self.checkout_path).strip() != 'False'):
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000348 print('_____ switching %s to a new upstream' % self.relpath)
349 # Make sure it's clean
350 self._CheckClean(rev_str)
351 # Switch over to the new upstream
352 self._Run(['remote', 'set-url', 'origin', url], options)
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000353 self._FetchAndReset(revision, file_list, options)
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000354 return
355
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000356 if not self._IsValidGitRepo():
357 # .git directory is hosed for some reason, set it back up.
358 print('_____ %s/.git is corrupted, rebuilding' % self.relpath)
359 self._Run(['init'], options)
360 self._Run(['remote', 'set-url', 'origin', url], options)
361
362 if not self._HasHead():
363 # Previous checkout was aborted before branches could be created in repo,
364 # so we need to reconstruct them here.
365 self._Run(['pull', 'origin', 'master'], options)
366 self._FetchAndReset(revision, file_list, options)
367
msb@chromium.org5bde4852009-12-14 16:47:12 +0000368 cur_branch = self._GetCurrentBranch()
369
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000370 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000371 # 0) HEAD is detached. Probably from our initial clone.
372 # - make sure HEAD is contained by a named ref, then update.
373 # Cases 1-4. HEAD is a branch.
374 # 1) current branch is not tracking a remote branch (could be git-svn)
375 # - try to rebase onto the new hash or branch
376 # 2) current branch is tracking a remote branch with local committed
377 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000378 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000379 # 3) current branch is tracking a remote branch w/or w/out changes,
380 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000381 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000382 # 4) current branch is tracking a remote branch, switches to a different
383 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000384 # - exit
385
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000386 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
387 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000388 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
389 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000390 if cur_branch is None:
391 upstream_branch = None
392 current_type = "detached"
393 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000394 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000395 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
396 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
397 current_type = "hash"
398 logging.debug("Current branch is not tracking an upstream (remote)"
399 " branch.")
400 elif upstream_branch.startswith('refs/remotes'):
401 current_type = "branch"
402 else:
403 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000404
maruel@chromium.org92067382012-06-28 19:58:41 +0000405 if (not re.match(r'^[0-9a-fA-F]{40}$', revision) or
406 not scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=revision)):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000407 # Update the remotes first so we have all the refs.
408 backoff_time = 5
409 for _ in range(10):
410 try:
411 remote_output = scm.GIT.Capture(
412 ['remote'] + verbose + ['update'],
413 cwd=self.checkout_path)
414 break
415 except subprocess2.CalledProcessError, e:
416 # Hackish but at that point, git is known to work so just checking for
417 # 502 in stderr should be fine.
418 if '502' in e.stderr:
419 print(str(e))
420 print('Sleeping %.1f seconds and retrying...' % backoff_time)
421 time.sleep(backoff_time)
422 backoff_time *= 1.3
423 continue
424 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000425
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000426 if verbose:
427 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000428
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000429 self._UpdateBranchHeads(options, fetch=True)
430
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000431 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000432 if options.force or options.reset:
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000433 target = 'HEAD'
434 if options.upstream and upstream_branch:
435 target = upstream_branch
436 self._Run(['reset', '--hard', target], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000437
msb@chromium.org786fb682010-06-02 15:16:23 +0000438 if current_type == 'detached':
439 # case 0
440 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000441 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000442 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000443 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000444 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000445 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000446 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000447 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000448 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000449 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000450 newbase=revision, printed_path=printed_path)
451 printed_path = True
452 else:
453 # Can't find a merge-base since we don't know our upstream. That makes
454 # this command VERY likely to produce a rebase failure. For now we
455 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000456 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000457 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000458 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000459 self._AttemptRebase(upstream_branch, files, options,
460 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000461 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000462 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000463 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000464 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000465 newbase=revision, printed_path=printed_path)
466 printed_path = True
467 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
468 # case 4
469 new_base = revision.replace('heads', 'remotes/origin')
470 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000471 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000472 switch_error = ("Switching upstream branch from %s to %s\n"
473 % (upstream_branch, new_base) +
474 "Please merge or rebase manually:\n" +
475 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
476 "OR git checkout -b <some new branch> %s" % new_base)
477 raise gclient_utils.Error(switch_error)
478 else:
479 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000480 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000481 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000482 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000484 merge_args = ['merge']
485 if not options.merge:
486 merge_args.append('--ff-only')
487 merge_args.append(upstream_branch)
488 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000489 except subprocess2.CalledProcessError as e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000490 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
491 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000492 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000493 printed_path = True
494 while True:
495 try:
maruel@chromium.org90541732011-04-01 17:54:18 +0000496 action = ask_for_data(
497 'Cannot fast-forward merge, attempt to rebase? '
bratell@opera.com18fa4542013-05-21 13:30:46 +0000498 '(y)es / (q)uit / (s)kip : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000499 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000500 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000501 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000502 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000503 printed_path=printed_path)
504 printed_path = True
505 break
506 elif re.match(r'quit|q', action, re.I):
507 raise gclient_utils.Error("Can't fast-forward, please merge or "
508 "rebase manually.\n"
509 "cd %s && git " % self.checkout_path
510 + "rebase %s" % upstream_branch)
511 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000512 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000513 return
514 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000515 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000516 elif re.match("error: Your local changes to '.*' would be "
517 "overwritten by merge. Aborting.\nPlease, commit your "
518 "changes or stash them before you can merge.\n",
519 e.stderr):
520 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000521 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000522 printed_path = True
523 raise gclient_utils.Error(e.stderr)
524 else:
525 # Some other problem happened with the merge
526 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000527 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000528 raise
529 else:
530 # Fast-forward merge was successful
531 if not re.match('Already up-to-date.', merge_output) or verbose:
532 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000533 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000534 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000535 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000536 if not verbose:
537 # Make the output a little prettier. It's nice to have some
538 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000539 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000540
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000541 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000542 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000543
544 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000545 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000546 raise gclient_utils.Error('\n____ %s%s\n'
547 '\nConflict while rebasing this branch.\n'
548 'Fix the conflict and run gclient again.\n'
549 'See man git-rebase for details.\n'
550 % (self.relpath, rev_str))
551
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000552 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000553 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000554
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000555 # If --reset and --delete_unversioned_trees are specified, remove any
556 # untracked directories.
557 if options.reset and options.delete_unversioned_trees:
558 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
559 # merge-base by default), so doesn't include untracked files. So we use
560 # 'git ls-files --directory --others --exclude-standard' here directly.
561 paths = scm.GIT.Capture(
562 ['ls-files', '--directory', '--others', '--exclude-standard'],
563 self.checkout_path)
564 for path in (p for p in paths.splitlines() if p.endswith('/')):
565 full_path = os.path.join(self.checkout_path, path)
566 if not os.path.islink(full_path):
567 print('\n_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000568 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000569
570
msb@chromium.orge28e4982009-09-25 20:51:45 +0000571 def revert(self, options, args, file_list):
572 """Reverts local modifications.
573
574 All reverted files will be appended to file_list.
575 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000576 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000577 # revert won't work if the directory doesn't exist. It needs to
578 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000579 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000580 # Don't reuse the args.
581 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000582
583 default_rev = "refs/heads/master"
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000584 if options.upstream:
585 if self._GetCurrentBranch():
586 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
587 default_rev = upstream_branch or default_rev
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000588 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000589 if not deps_revision:
590 deps_revision = default_rev
591 if deps_revision.startswith('refs/heads/'):
592 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
593
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000594 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000595 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000596 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000597 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
598
msb@chromium.org0f282062009-11-06 20:14:02 +0000599 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000600 """Returns revision"""
601 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000602
msb@chromium.orge28e4982009-09-25 20:51:45 +0000603 def runhooks(self, options, args, file_list):
604 self.status(options, args, file_list)
605
606 def status(self, options, args, file_list):
607 """Display status information."""
608 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000609 print(('\n________ couldn\'t run status in %s:\n'
610 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000611 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000612 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000613 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000614 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000615 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
616
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000617 def GetUsableRev(self, rev, options):
618 """Finds a useful revision for this repository.
619
620 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
621 will be called on the source."""
622 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000623 if not os.path.isdir(self.checkout_path):
624 raise gclient_utils.Error(
625 ( 'We could not find a valid hash for safesync_url response "%s".\n'
626 'Safesync URLs with a git checkout currently require the repo to\n'
627 'be cloned without a safesync_url before adding the safesync_url.\n'
628 'For more info, see: '
629 'http://code.google.com/p/chromium/wiki/UsingNewGit'
630 '#Initial_checkout' ) % rev)
631 elif rev.isdigit() and len(rev) < 7:
632 # Handles an SVN rev. As an optimization, only verify an SVN revision as
633 # [0-9]{1,6} for now to avoid making a network request.
634 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000635 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
636 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000637 try:
638 logging.debug('Looking for git-svn configuration optimizations.')
639 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
640 cwd=self.checkout_path):
641 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
642 except subprocess2.CalledProcessError:
643 logging.debug('git config --get svn-remote.svn.fetch failed, '
644 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000645 if options.verbose:
646 print('Running git svn fetch. This might take a while.\n')
647 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000648 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000649 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
650 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000651 except gclient_utils.Error, e:
652 sha1 = e.message
653 print('\nWarning: Could not find a git revision with accurate\n'
654 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
655 'the closest sane git revision, which is:\n'
656 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000657 if not sha1:
658 raise gclient_utils.Error(
659 ( 'It appears that either your git-svn remote is incorrectly\n'
660 'configured or the revision in your safesync_url is\n'
661 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
662 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000663 else:
664 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
665 sha1 = rev
666 else:
667 # May exist in origin, but we don't have it yet, so fetch and look
668 # again.
669 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
670 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
671 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000672
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000673 if not sha1:
674 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000675 ( 'We could not find a valid hash for safesync_url response "%s".\n'
676 'Safesync URLs with a git checkout currently require a git-svn\n'
677 'remote or a safesync_url that provides git sha1s. Please add a\n'
678 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000679 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000680 '#Initial_checkout' ) % rev)
681
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000682 return sha1
683
msb@chromium.orge6f78352010-01-13 17:05:33 +0000684 def FullUrlForRelativeUrl(self, url):
685 # Strip from last '/'
686 # Equivalent to unix basename
687 base_url = self.url
688 return base_url[:base_url.rfind('/')] + url
689
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000690 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000691 """Clone a git repository from the given URL.
692
msb@chromium.org786fb682010-06-02 15:16:23 +0000693 Once we've cloned the repo, we checkout a working branch if the specified
694 revision is a branch head. If it is a tag or a specific commit, then we
695 leave HEAD detached as it makes future updates simpler -- in this case the
696 user should first create a new branch or switch to an existing branch before
697 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000698 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000699 # git clone doesn't seem to insert a newline properly before printing
700 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000701 print('')
szager@chromium.orgee10d7d2013-04-24 23:18:20 +0000702 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000703 if revision.startswith('refs/heads/'):
704 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
705 detach_head = False
706 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000707 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000708 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000709 clone_cmd.append('--verbose')
710 clone_cmd.extend([url, self.checkout_path])
711
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000712 # If the parent directory does not exist, Git clone on Windows will not
713 # create it, so we need to do it manually.
714 parent_dir = os.path.dirname(self.checkout_path)
715 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000716 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000717
szager@google.com85d3e3a2011-10-07 17:12:00 +0000718 percent_re = re.compile('.* ([0-9]{1,2})% .*')
719 def _GitFilter(line):
720 # git uses an escape sequence to clear the line; elide it.
721 esc = line.find(unichr(033))
722 if esc > -1:
723 line = line[:esc]
724 match = percent_re.match(line)
725 if not match or not int(match.group(1)) % 10:
726 print '%s' % line
727
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000728 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000729 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000730 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
731 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000732 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000733 except subprocess2.CalledProcessError, e:
734 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000735 # We should check for "transfer closed with NNN bytes remaining to
736 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000737 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000738 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000739 print(str(e))
740 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000741 continue
742 raise e
743
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000744 # Update the "branch-heads" remote-tracking branches, since we might need it
745 # to checkout a specific revision below.
746 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org059cc452013-03-11 15:14:35 +0000747
msb@chromium.org786fb682010-06-02 15:16:23 +0000748 if detach_head:
749 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000750 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000751 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000752 ('Checked out %s to a detached HEAD. Before making any commits\n'
753 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
754 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
755 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000756
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000757 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000758 branch=None, printed_path=False):
759 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000760 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000761 revision = upstream
762 if newbase:
763 revision = newbase
764 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000765 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000766 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000767 printed_path = True
768 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000769 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000770
771 # Build the rebase command here using the args
772 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
773 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000774 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000775 rebase_cmd.append('--verbose')
776 if newbase:
777 rebase_cmd.extend(['--onto', newbase])
778 rebase_cmd.append(upstream)
779 if branch:
780 rebase_cmd.append(branch)
781
782 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000783 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000784 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000785 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
786 re.match(r'cannot rebase: your index contains uncommitted changes',
787 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000788 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000789 rebase_action = ask_for_data(
790 'Cannot rebase because of unstaged changes.\n'
791 '\'git reset --hard HEAD\' ?\n'
792 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000793 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000794 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000795 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000796 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000797 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000798 break
799 elif re.match(r'quit|q', rebase_action, re.I):
800 raise gclient_utils.Error("Please merge or rebase manually\n"
801 "cd %s && git " % self.checkout_path
802 + "%s" % ' '.join(rebase_cmd))
803 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000804 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000805 continue
806 else:
807 gclient_utils.Error("Input not recognized")
808 continue
809 elif re.search(r'^CONFLICT', e.stdout, re.M):
810 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
811 "Fix the conflict and run gclient again.\n"
812 "See 'man git-rebase' for details.\n")
813 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000814 print(e.stdout.strip())
815 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000816 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
817 "manually.\ncd %s && git " %
818 self.checkout_path
819 + "%s" % ' '.join(rebase_cmd))
820
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000821 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000822 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000823 # Make the output a little prettier. It's nice to have some
824 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000825 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000826
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000827 def _IsValidGitRepo(self):
828 """Returns if the directory is a valid git repository.
829
830 Checks if git status works.
831 """
832 try:
833 self._Capture(['status'])
834 return True
835 except subprocess2.CalledProcessError:
836 return False
837
838 def _HasHead(self):
839 """Returns True if any commit is checked out.
840
841 This is done by checking if rev-parse HEAD works in the current repository.
842 """
843 try:
844 self._GetCurrentBranch()
845 return True
846 except subprocess2.CalledProcessError:
847 return False
848
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000849 @staticmethod
850 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000851 (ok, current_version) = scm.GIT.AssertVersion(min_version)
852 if not ok:
853 raise gclient_utils.Error('git version %s < minimum required %s' %
854 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000855
msb@chromium.org786fb682010-06-02 15:16:23 +0000856 def _IsRebasing(self):
857 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
858 # have a plumbing command to determine whether a rebase is in progress, so
859 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
860 g = os.path.join(self.checkout_path, '.git')
861 return (
862 os.path.isdir(os.path.join(g, "rebase-merge")) or
863 os.path.isdir(os.path.join(g, "rebase-apply")))
864
865 def _CheckClean(self, rev_str):
866 # Make sure the tree is clean; see git-rebase.sh for reference
867 try:
868 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000869 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000870 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000871 raise gclient_utils.Error('\n____ %s%s\n'
872 '\tYou have unstaged changes.\n'
873 '\tPlease commit, stash, or reset.\n'
874 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000875 try:
876 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000877 '--ignore-submodules', 'HEAD', '--'],
878 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000879 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000880 raise gclient_utils.Error('\n____ %s%s\n'
881 '\tYour index contains uncommitted changes\n'
882 '\tPlease commit, stash, or reset.\n'
883 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000884
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000885 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000886 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
887 # reference by a commit). If not, error out -- most likely a rebase is
888 # in progress, try to detect so we can give a better error.
889 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000890 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
891 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000892 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000893 # Commit is not contained by any rev. See if the user is rebasing:
894 if self._IsRebasing():
895 # Punt to the user
896 raise gclient_utils.Error('\n____ %s%s\n'
897 '\tAlready in a conflict, i.e. (no branch).\n'
898 '\tFix the conflict and run gclient again.\n'
899 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
900 '\tSee man git-rebase for details.\n'
901 % (self.relpath, rev_str))
902 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000903 name = ('saved-by-gclient-' +
904 self._Capture(['rev-parse', '--short', 'HEAD']))
905 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000906 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000907 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000908
msb@chromium.org5bde4852009-12-14 16:47:12 +0000909 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000910 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000911 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000912 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000913 return None
914 return branch
915
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000916 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000917 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000918 ['git'] + args,
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000919 stderr=subprocess2.VOID,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000920 nag_timer=self.nag_timer,
921 nag_max=self.nag_max,
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000922 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000923
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000924 def _UpdateBranchHeads(self, options, fetch=False):
925 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
926 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
927 backoff_time = 5
928 for _ in range(3):
929 try:
930 config_cmd = ['config', 'remote.origin.fetch',
931 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
932 '^\\+refs/branch-heads/\\*:.*$']
933 self._Run(config_cmd, options)
934 if fetch:
935 fetch_cmd = ['fetch', 'origin']
936 if options.verbose:
937 fetch_cmd.append('--verbose')
938 self._Run(fetch_cmd, options)
939 break
940 except subprocess2.CalledProcessError, e:
941 print(str(e))
942 print('Retrying in %.1f seconds...' % backoff_time)
943 time.sleep(backoff_time)
944 backoff_time *= 1.3
945
maruel@chromium.org37e89872010-09-07 16:11:33 +0000946 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000947 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000948 kwargs.setdefault('print_stdout', True)
szager@chromium.org12b07e72013-05-03 22:06:34 +0000949 kwargs.setdefault('nag_timer', self.nag_timer)
950 kwargs.setdefault('nag_max', self.nag_max)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000951 stdout = kwargs.get('stdout', sys.stdout)
952 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
953 ' '.join(args), kwargs['cwd']))
954 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000955
956
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000957class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000958 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000959
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000960 @staticmethod
961 def BinaryExists():
962 """Returns true if the command exists."""
963 try:
964 result, version = scm.SVN.AssertVersion('1.4')
965 if not result:
966 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
967 return result
968 except OSError:
969 return False
970
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000971 def GetCheckoutRoot(self):
972 return scm.SVN.GetCheckoutRoot(self.checkout_path)
973
floitsch@google.comeaab7842011-04-28 09:07:58 +0000974 def GetRevisionDate(self, revision):
975 """Returns the given revision's date in ISO-8601 format (which contains the
976 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000977 date = scm.SVN.Capture(
978 ['propget', '--revprop', 'svn:date', '-r', revision],
979 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000980 return date.strip()
981
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000982 def cleanup(self, options, args, file_list):
983 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000984 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000985
986 def diff(self, options, args, file_list):
987 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000988 if not os.path.isdir(self.checkout_path):
989 raise gclient_utils.Error('Directory %s is not present.' %
990 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000991 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000992
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000993 def pack(self, options, args, file_list):
994 """Generates a patch file which can be applied to the root of the
995 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000996 if not os.path.isdir(self.checkout_path):
997 raise gclient_utils.Error('Directory %s is not present.' %
998 self.checkout_path)
999 gclient_utils.CheckCallAndFilter(
1000 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1001 cwd=self.checkout_path,
1002 print_stdout=False,
szager@chromium.org12b07e72013-05-03 22:06:34 +00001003 nag_timer=self.nag_timer,
1004 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +00001005 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001006
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001007 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +00001008 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001009
1010 All updated files will be appended to file_list.
1011
1012 Raises:
1013 Error: if can't get URL for relative path.
1014 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +00001015 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001016 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001017 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001018 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001019 return
1020
morrita@chromium.org21dca0e2010-10-05 00:55:12 +00001021 hg_path = os.path.join(self.checkout_path, '.hg')
1022 if os.path.exists(hg_path):
1023 print('________ found .hg directory; skipping %s' % self.relpath)
1024 return
1025
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001026 if args:
1027 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1028
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001029 # revision is the revision to match. It is None if no revision is specified,
1030 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001031 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001032 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001033 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001034 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001035 if options.revision:
1036 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001037 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001038 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001039 if revision != 'unmanaged':
1040 forced_revision = True
1041 # Reconstruct the url.
1042 url = '%s@%s' % (url, revision)
1043 rev_str = ' at %s' % revision
1044 else:
1045 managed = False
1046 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001047 else:
1048 forced_revision = False
1049 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001050
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001051 # Get the existing scm url and the revision number of the current checkout.
1052 exists = os.path.exists(self.checkout_path)
1053 if exists and managed:
1054 try:
1055 from_info = scm.SVN.CaptureLocalInfo(
1056 [], os.path.join(self.checkout_path, '.'))
1057 except (gclient_utils.Error, subprocess2.CalledProcessError):
1058 if options.reset and options.delete_unversioned_trees:
1059 print 'Removing troublesome path %s' % self.checkout_path
1060 gclient_utils.rmtree(self.checkout_path)
1061 exists = False
1062 else:
1063 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1064 'present. Delete the directory and try again.')
1065 raise gclient_utils.Error(msg % self.checkout_path)
1066
1067 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001068 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001069 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001070 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001071 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001072 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001073 return
1074
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001075 if not managed:
1076 print ('________ unmanaged solution; skipping %s' % self.relpath)
1077 return
1078
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001079 if 'URL' not in from_info:
1080 raise gclient_utils.Error(
1081 ('gclient is confused. Couldn\'t get the url for %s.\n'
1082 'Try using @unmanaged.\n%s') % (
1083 self.checkout_path, from_info))
1084
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001085 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001086 dir_info = scm.SVN.CaptureStatus(
1087 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001088 if any(d[0][2] == 'L' for d in dir_info):
1089 try:
1090 self._Run(['cleanup', self.checkout_path], options)
1091 except subprocess2.CalledProcessError, e:
1092 # Get the status again, svn cleanup may have cleaned up at least
1093 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001094 dir_info = scm.SVN.CaptureStatus(
1095 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001096
1097 # Try to fix the failures by removing troublesome files.
1098 for d in dir_info:
1099 if d[0][2] == 'L':
1100 if d[0][0] == '!' and options.force:
1101 print 'Removing troublesome path %s' % d[1]
1102 gclient_utils.rmtree(d[1])
1103 else:
1104 print 'Not removing troublesome path %s automatically.' % d[1]
1105 if d[0][0] == '!':
1106 print 'You can pass --force to enable automatic removal.'
1107 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001108
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001109 # Retrieve the current HEAD version because svn is slow at null updates.
1110 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001111 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001112 revision = str(from_info_live['Revision'])
1113 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001114
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001115 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001116 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001117 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001118 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001119 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001120 # The url is invalid or the server is not accessible, it's safer to bail
1121 # out right now.
1122 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001123 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1124 and (from_info['UUID'] == to_info['UUID']))
1125 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001126 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001127 # We have different roots, so check if we can switch --relocate.
1128 # Subversion only permits this if the repository UUIDs match.
1129 # Perform the switch --relocate, then rewrite the from_url
1130 # to reflect where we "are now." (This is the same way that
1131 # Subversion itself handles the metadata when switch --relocate
1132 # is used.) This makes the checks below for whether we
1133 # can update to a revision or have to switch to a different
1134 # branch work as expected.
1135 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001136 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001137 from_info['Repository Root'],
1138 to_info['Repository Root'],
1139 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001140 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001141 from_info['URL'] = from_info['URL'].replace(
1142 from_info['Repository Root'],
1143 to_info['Repository Root'])
1144 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001145 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001146 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001147 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001148 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001149 raise gclient_utils.Error(
1150 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1151 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001152 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001153 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001154 print('\n_____ switching %s to a new checkout' % self.relpath)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001155 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001156 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001157 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001158 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001159 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001160 return
1161
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001162 # If the provided url has a revision number that matches the revision
1163 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001164 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001165 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001166 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001167 else:
1168 command = ['update', self.checkout_path]
1169 command = self._AddAdditionalUpdateFlags(command, options, revision)
1170 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001171
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001172 # If --reset and --delete_unversioned_trees are specified, remove any
1173 # untracked files and directories.
1174 if options.reset and options.delete_unversioned_trees:
1175 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1176 full_path = os.path.join(self.checkout_path, status[1])
1177 if (status[0][0] == '?'
1178 and os.path.isdir(full_path)
1179 and not os.path.islink(full_path)):
1180 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001181 gclient_utils.rmtree(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001182
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001183 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001184 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001185 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001186 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001187 # Create an empty checkout and then update the one file we want. Future
1188 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001189 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001190 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001191 if os.path.exists(os.path.join(self.checkout_path, filename)):
1192 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001193 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001194 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001195 # After the initial checkout, we can use update as if it were any other
1196 # dep.
1197 self.update(options, args, file_list)
1198 else:
1199 # If the installed version of SVN doesn't support --depth, fallback to
1200 # just exporting the file. This has the downside that revision
1201 # information is not stored next to the file, so we will have to
1202 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001203 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001204 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001205 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001206 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001207 command = self._AddAdditionalUpdateFlags(command, options,
1208 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001209 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001210
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001211 def revert(self, options, args, file_list):
1212 """Reverts local modifications. Subversion specific.
1213
1214 All reverted files will be appended to file_list, even if Subversion
1215 doesn't know about them.
1216 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001217 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001218 if os.path.exists(self.checkout_path):
1219 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001220 # svn revert won't work if the directory doesn't exist. It needs to
1221 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001222 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001223 # Don't reuse the args.
1224 return self.update(options, [], file_list)
1225
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001226 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1227 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1228 print('________ found .git directory; skipping %s' % self.relpath)
1229 return
1230 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1231 print('________ found .hg directory; skipping %s' % self.relpath)
1232 return
1233 if not options.force:
1234 raise gclient_utils.Error('Invalid checkout path, aborting')
1235 print(
1236 '\n_____ %s is not a valid svn checkout, synching instead' %
1237 self.relpath)
1238 gclient_utils.rmtree(self.checkout_path)
1239 # Don't reuse the args.
1240 return self.update(options, [], file_list)
1241
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001242 def printcb(file_status):
1243 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001244 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001245 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001246 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001247 print(os.path.join(self.checkout_path, file_status[1]))
1248 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001249
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001250 # Revert() may delete the directory altogether.
1251 if not os.path.isdir(self.checkout_path):
1252 # Don't reuse the args.
1253 return self.update(options, [], file_list)
1254
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001255 try:
1256 # svn revert is so broken we don't even use it. Using
1257 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001258 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001259 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1260 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001261 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001262 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001263 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001264
msb@chromium.org0f282062009-11-06 20:14:02 +00001265 def revinfo(self, options, args, file_list):
1266 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001267 try:
1268 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001269 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001270 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001271
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001272 def runhooks(self, options, args, file_list):
1273 self.status(options, args, file_list)
1274
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001275 def status(self, options, args, file_list):
1276 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001277 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001278 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001279 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001280 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1281 'The directory does not exist.') %
1282 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001283 # There's no file list to retrieve.
1284 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001285 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001286
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001287 def GetUsableRev(self, rev, options):
1288 """Verifies the validity of the revision for this repository."""
1289 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1290 raise gclient_utils.Error(
1291 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1292 'correct.') % rev)
1293 return rev
1294
msb@chromium.orge6f78352010-01-13 17:05:33 +00001295 def FullUrlForRelativeUrl(self, url):
1296 # Find the forth '/' and strip from there. A bit hackish.
1297 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001298
maruel@chromium.org669600d2010-09-01 19:06:31 +00001299 def _Run(self, args, options, **kwargs):
1300 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001301 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.org12b07e72013-05-03 22:06:34 +00001302 kwargs.setdefault('nag_timer', self.nag_timer)
1303 kwargs.setdefault('nag_max', self.nag_max)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001304 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001305 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001306
1307 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1308 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001309 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001310 scm.SVN.RunAndGetFileList(
1311 options.verbose,
1312 args + ['--ignore-externals'],
1313 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001314 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001315
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001316 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001317 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001318 """Add additional flags to command depending on what options are set.
1319 command should be a list of strings that represents an svn command.
1320
1321 This method returns a new list to be used as a command."""
1322 new_command = command[:]
1323 if revision:
1324 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001325 # We don't want interaction when jobs are used.
1326 if options.jobs > 1:
1327 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001328 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001329 # --accept was added to 'svn update' in svn 1.6.
1330 if not scm.SVN.AssertVersion('1.5')[0]:
1331 return new_command
1332
1333 # It's annoying to have it block in the middle of a sync, just sensible
1334 # defaults.
1335 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001336 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001337 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1338 new_command.extend(('--accept', 'theirs-conflict'))
1339 elif options.manually_grab_svn_rev:
1340 new_command.append('--force')
1341 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1342 new_command.extend(('--accept', 'postpone'))
1343 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1344 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001345 return new_command