blob: 01dfd54675b32151d38eb6fe27629650397a32bd [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
msb@chromium.orge28e4982009-09-25 20:51:45 +0000240 def update(self, options, args, file_list):
241 """Runs git to update or transparently checkout the working copy.
242
243 All updated files will be appended to file_list.
244
245 Raises:
246 Error: if can't get URL for relative path.
247 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000248 if args:
249 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
250
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000251 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000252
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000253 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000254 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000255 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000256 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000257 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000258 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000259 # Override the revision number.
260 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000261 if revision == 'unmanaged':
262 revision = None
263 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000264 if not revision:
265 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000266
floitsch@google.comeaab7842011-04-28 09:07:58 +0000267 if gclient_utils.IsDateRevision(revision):
268 # Date-revisions only work on git-repositories if the reflog hasn't
269 # expired yet. Use rev-list to get the corresponding revision.
270 # git rev-list -n 1 --before='time-stamp' branchname
271 if options.transitive:
272 print('Warning: --transitive only works for SVN repositories.')
273 revision = default_rev
274
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000275 rev_str = ' at %s' % revision
276 files = []
277
278 printed_path = False
279 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000280 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000281 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000282 verbose = ['--verbose']
283 printed_path = True
284
285 if revision.startswith('refs/heads/'):
286 rev_type = "branch"
287 elif revision.startswith('origin/'):
288 # For compatability with old naming, translate 'origin' to 'refs/heads'
289 revision = revision.replace('origin/', 'refs/heads/')
290 rev_type = "branch"
291 else:
292 # hash is also a tag, only make a distinction at checkout
293 rev_type = "hash"
294
szager@google.com873e6672012-03-13 18:53:36 +0000295 if not os.path.exists(self.checkout_path) or (
296 os.path.isdir(self.checkout_path) and
297 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000298 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000299 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000300 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000301 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000302 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000303 if not verbose:
304 # Make the output a little prettier. It's nice to have some whitespace
305 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000306 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000307 return
308
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000309 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000310 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000311 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000312 print ('________ unmanaged solution; skipping %s' % self.relpath)
313 return
314
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000315 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
316 raise gclient_utils.Error('\n____ %s%s\n'
317 '\tPath is not a git repo. No .git dir.\n'
318 '\tTo resolve:\n'
319 '\t\trm -rf %s\n'
320 '\tAnd run gclient sync again\n'
321 % (self.relpath, rev_str, self.relpath))
322
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000323 # See if the url has changed (the unittests use git://foo for the url, let
324 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000325 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000326 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
327 # unit test pass. (and update the comment above)
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000328 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
329 # This allows devs to use experimental repos which have a different url
330 # but whose branch(s) are the same as official repos.
331 if (current_url != url and
332 url != 'git://foo' and
333 subprocess2.capture(
334 ['git', 'config', 'remote.origin.gclient-auto-fix-url'],
335 cwd=self.checkout_path).strip() != 'False'):
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000336 print('_____ switching %s to a new upstream' % self.relpath)
337 # Make sure it's clean
338 self._CheckClean(rev_str)
339 # Switch over to the new upstream
340 self._Run(['remote', 'set-url', 'origin', url], options)
341 quiet = []
342 if not options.verbose:
343 quiet = ['--quiet']
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000344 self._UpdateBranchHeads(options, fetch=False)
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000345 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
bauerb@chromium.org610060e2012-11-19 14:11:35 +0000346 self._Run(['reset', '--hard', revision] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000347 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000348 files = self._Capture(['ls-files']).splitlines()
349 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
350 return
351
msb@chromium.org5bde4852009-12-14 16:47:12 +0000352 cur_branch = self._GetCurrentBranch()
353
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000354 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000355 # 0) HEAD is detached. Probably from our initial clone.
356 # - make sure HEAD is contained by a named ref, then update.
357 # Cases 1-4. HEAD is a branch.
358 # 1) current branch is not tracking a remote branch (could be git-svn)
359 # - try to rebase onto the new hash or branch
360 # 2) current branch is tracking a remote branch with local committed
361 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000362 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000363 # 3) current branch is tracking a remote branch w/or w/out changes,
364 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000365 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000366 # 4) current branch is tracking a remote branch, switches to a different
367 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000368 # - exit
369
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000370 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
371 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000372 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
373 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000374 if cur_branch is None:
375 upstream_branch = None
376 current_type = "detached"
377 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000378 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000379 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
380 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
381 current_type = "hash"
382 logging.debug("Current branch is not tracking an upstream (remote)"
383 " branch.")
384 elif upstream_branch.startswith('refs/remotes'):
385 current_type = "branch"
386 else:
387 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000388
maruel@chromium.org92067382012-06-28 19:58:41 +0000389 if (not re.match(r'^[0-9a-fA-F]{40}$', revision) or
390 not scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=revision)):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000391 # Update the remotes first so we have all the refs.
392 backoff_time = 5
393 for _ in range(10):
394 try:
395 remote_output = scm.GIT.Capture(
396 ['remote'] + verbose + ['update'],
397 cwd=self.checkout_path)
398 break
399 except subprocess2.CalledProcessError, e:
400 # Hackish but at that point, git is known to work so just checking for
401 # 502 in stderr should be fine.
402 if '502' in e.stderr:
403 print(str(e))
404 print('Sleeping %.1f seconds and retrying...' % backoff_time)
405 time.sleep(backoff_time)
406 backoff_time *= 1.3
407 continue
408 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000409
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000410 if verbose:
411 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000412
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000413 self._UpdateBranchHeads(options, fetch=True)
414
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000415 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000416 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000417 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000418
msb@chromium.org786fb682010-06-02 15:16:23 +0000419 if current_type == 'detached':
420 # case 0
421 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000422 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000423 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000424 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000425 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000426 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000427 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000428 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000429 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000430 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000431 newbase=revision, printed_path=printed_path)
432 printed_path = True
433 else:
434 # Can't find a merge-base since we don't know our upstream. That makes
435 # this command VERY likely to produce a rebase failure. For now we
436 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000437 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000438 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000439 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000440 self._AttemptRebase(upstream_branch, files, options,
441 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000442 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000443 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000444 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000445 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000446 newbase=revision, printed_path=printed_path)
447 printed_path = True
448 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
449 # case 4
450 new_base = revision.replace('heads', 'remotes/origin')
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 switch_error = ("Switching upstream branch from %s to %s\n"
454 % (upstream_branch, new_base) +
455 "Please merge or rebase manually:\n" +
456 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
457 "OR git checkout -b <some new branch> %s" % new_base)
458 raise gclient_utils.Error(switch_error)
459 else:
460 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000461 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000462 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000463 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000464 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000465 merge_args = ['merge']
466 if not options.merge:
467 merge_args.append('--ff-only')
468 merge_args.append(upstream_branch)
469 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000470 except subprocess2.CalledProcessError as e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000471 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
472 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000473 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000474 printed_path = True
475 while True:
476 try:
maruel@chromium.org90541732011-04-01 17:54:18 +0000477 action = ask_for_data(
478 'Cannot fast-forward merge, attempt to rebase? '
bratell@opera.com18fa4542013-05-21 13:30:46 +0000479 '(y)es / (q)uit / (s)kip : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000480 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000481 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000482 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000483 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000484 printed_path=printed_path)
485 printed_path = True
486 break
487 elif re.match(r'quit|q', action, re.I):
488 raise gclient_utils.Error("Can't fast-forward, please merge or "
489 "rebase manually.\n"
490 "cd %s && git " % self.checkout_path
491 + "rebase %s" % upstream_branch)
492 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000493 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000494 return
495 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000496 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000497 elif re.match("error: Your local changes to '.*' would be "
498 "overwritten by merge. Aborting.\nPlease, commit your "
499 "changes or stash them before you can merge.\n",
500 e.stderr):
501 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000502 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000503 printed_path = True
504 raise gclient_utils.Error(e.stderr)
505 else:
506 # Some other problem happened with the merge
507 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000508 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000509 raise
510 else:
511 # Fast-forward merge was successful
512 if not re.match('Already up-to-date.', merge_output) or verbose:
513 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000514 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000515 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000516 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000517 if not verbose:
518 # Make the output a little prettier. It's nice to have some
519 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000520 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000521
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000522 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000523 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000524
525 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000526 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000527 raise gclient_utils.Error('\n____ %s%s\n'
528 '\nConflict while rebasing this branch.\n'
529 'Fix the conflict and run gclient again.\n'
530 'See man git-rebase for details.\n'
531 % (self.relpath, rev_str))
532
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000533 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000534 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000535
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000536 # If --reset and --delete_unversioned_trees are specified, remove any
537 # untracked directories.
538 if options.reset and options.delete_unversioned_trees:
539 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
540 # merge-base by default), so doesn't include untracked files. So we use
541 # 'git ls-files --directory --others --exclude-standard' here directly.
542 paths = scm.GIT.Capture(
543 ['ls-files', '--directory', '--others', '--exclude-standard'],
544 self.checkout_path)
545 for path in (p for p in paths.splitlines() if p.endswith('/')):
546 full_path = os.path.join(self.checkout_path, path)
547 if not os.path.islink(full_path):
548 print('\n_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000549 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000550
551
msb@chromium.orge28e4982009-09-25 20:51:45 +0000552 def revert(self, options, args, file_list):
553 """Reverts local modifications.
554
555 All reverted files will be appended to file_list.
556 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000557 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000558 # revert won't work if the directory doesn't exist. It needs to
559 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000560 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000561 # Don't reuse the args.
562 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000563
564 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000565 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000566 if not deps_revision:
567 deps_revision = default_rev
568 if deps_revision.startswith('refs/heads/'):
569 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
570
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000571 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000572 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000573 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000574 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
575
msb@chromium.org0f282062009-11-06 20:14:02 +0000576 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000577 """Returns revision"""
578 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000579
msb@chromium.orge28e4982009-09-25 20:51:45 +0000580 def runhooks(self, options, args, file_list):
581 self.status(options, args, file_list)
582
583 def status(self, options, args, file_list):
584 """Display status information."""
585 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000586 print(('\n________ couldn\'t run status in %s:\n'
587 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000588 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000589 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000590 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000591 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000592 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
593
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000594 def GetUsableRev(self, rev, options):
595 """Finds a useful revision for this repository.
596
597 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
598 will be called on the source."""
599 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000600 if not os.path.isdir(self.checkout_path):
601 raise gclient_utils.Error(
602 ( 'We could not find a valid hash for safesync_url response "%s".\n'
603 'Safesync URLs with a git checkout currently require the repo to\n'
604 'be cloned without a safesync_url before adding the safesync_url.\n'
605 'For more info, see: '
606 'http://code.google.com/p/chromium/wiki/UsingNewGit'
607 '#Initial_checkout' ) % rev)
608 elif rev.isdigit() and len(rev) < 7:
609 # Handles an SVN rev. As an optimization, only verify an SVN revision as
610 # [0-9]{1,6} for now to avoid making a network request.
611 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000612 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
613 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000614 try:
615 logging.debug('Looking for git-svn configuration optimizations.')
616 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
617 cwd=self.checkout_path):
618 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
619 except subprocess2.CalledProcessError:
620 logging.debug('git config --get svn-remote.svn.fetch failed, '
621 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000622 if options.verbose:
623 print('Running git svn fetch. This might take a while.\n')
624 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000625 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000626 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
627 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000628 except gclient_utils.Error, e:
629 sha1 = e.message
630 print('\nWarning: Could not find a git revision with accurate\n'
631 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
632 'the closest sane git revision, which is:\n'
633 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000634 if not sha1:
635 raise gclient_utils.Error(
636 ( 'It appears that either your git-svn remote is incorrectly\n'
637 'configured or the revision in your safesync_url is\n'
638 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
639 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000640 else:
641 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
642 sha1 = rev
643 else:
644 # May exist in origin, but we don't have it yet, so fetch and look
645 # again.
646 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
647 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
648 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000649
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000650 if not sha1:
651 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000652 ( 'We could not find a valid hash for safesync_url response "%s".\n'
653 'Safesync URLs with a git checkout currently require a git-svn\n'
654 'remote or a safesync_url that provides git sha1s. Please add a\n'
655 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000656 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000657 '#Initial_checkout' ) % rev)
658
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000659 return sha1
660
msb@chromium.orge6f78352010-01-13 17:05:33 +0000661 def FullUrlForRelativeUrl(self, url):
662 # Strip from last '/'
663 # Equivalent to unix basename
664 base_url = self.url
665 return base_url[:base_url.rfind('/')] + url
666
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000667 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000668 """Clone a git repository from the given URL.
669
msb@chromium.org786fb682010-06-02 15:16:23 +0000670 Once we've cloned the repo, we checkout a working branch if the specified
671 revision is a branch head. If it is a tag or a specific commit, then we
672 leave HEAD detached as it makes future updates simpler -- in this case the
673 user should first create a new branch or switch to an existing branch before
674 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000675 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000676 # git clone doesn't seem to insert a newline properly before printing
677 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000678 print('')
szager@chromium.orgee10d7d2013-04-24 23:18:20 +0000679 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000680 if revision.startswith('refs/heads/'):
681 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
682 detach_head = False
683 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000684 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000685 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000686 clone_cmd.append('--verbose')
687 clone_cmd.extend([url, self.checkout_path])
688
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000689 # If the parent directory does not exist, Git clone on Windows will not
690 # create it, so we need to do it manually.
691 parent_dir = os.path.dirname(self.checkout_path)
692 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000693 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000694
szager@google.com85d3e3a2011-10-07 17:12:00 +0000695 percent_re = re.compile('.* ([0-9]{1,2})% .*')
696 def _GitFilter(line):
697 # git uses an escape sequence to clear the line; elide it.
698 esc = line.find(unichr(033))
699 if esc > -1:
700 line = line[:esc]
701 match = percent_re.match(line)
702 if not match or not int(match.group(1)) % 10:
703 print '%s' % line
704
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000705 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000706 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000707 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
708 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000709 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000710 except subprocess2.CalledProcessError, e:
711 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000712 # We should check for "transfer closed with NNN bytes remaining to
713 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000714 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000715 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000716 print(str(e))
717 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000718 continue
719 raise e
720
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000721 # Update the "branch-heads" remote-tracking branches, since we might need it
722 # to checkout a specific revision below.
723 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org059cc452013-03-11 15:14:35 +0000724
msb@chromium.org786fb682010-06-02 15:16:23 +0000725 if detach_head:
726 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000727 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000728 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000729 ('Checked out %s to a detached HEAD. Before making any commits\n'
730 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
731 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
732 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000733
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000734 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000735 branch=None, printed_path=False):
736 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000737 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000738 revision = upstream
739 if newbase:
740 revision = newbase
741 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000742 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000743 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000744 printed_path = True
745 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000746 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000747
748 # Build the rebase command here using the args
749 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
750 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000751 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000752 rebase_cmd.append('--verbose')
753 if newbase:
754 rebase_cmd.extend(['--onto', newbase])
755 rebase_cmd.append(upstream)
756 if branch:
757 rebase_cmd.append(branch)
758
759 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000760 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000761 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000762 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
763 re.match(r'cannot rebase: your index contains uncommitted changes',
764 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000765 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000766 rebase_action = ask_for_data(
767 'Cannot rebase because of unstaged changes.\n'
768 '\'git reset --hard HEAD\' ?\n'
769 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000770 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000771 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000772 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000773 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000774 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000775 break
776 elif re.match(r'quit|q', rebase_action, re.I):
777 raise gclient_utils.Error("Please merge or rebase manually\n"
778 "cd %s && git " % self.checkout_path
779 + "%s" % ' '.join(rebase_cmd))
780 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000781 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000782 continue
783 else:
784 gclient_utils.Error("Input not recognized")
785 continue
786 elif re.search(r'^CONFLICT', e.stdout, re.M):
787 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
788 "Fix the conflict and run gclient again.\n"
789 "See 'man git-rebase' for details.\n")
790 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000791 print(e.stdout.strip())
792 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000793 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
794 "manually.\ncd %s && git " %
795 self.checkout_path
796 + "%s" % ' '.join(rebase_cmd))
797
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000798 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000799 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000800 # Make the output a little prettier. It's nice to have some
801 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000802 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000803
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000804 @staticmethod
805 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000806 (ok, current_version) = scm.GIT.AssertVersion(min_version)
807 if not ok:
808 raise gclient_utils.Error('git version %s < minimum required %s' %
809 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000810
msb@chromium.org786fb682010-06-02 15:16:23 +0000811 def _IsRebasing(self):
812 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
813 # have a plumbing command to determine whether a rebase is in progress, so
814 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
815 g = os.path.join(self.checkout_path, '.git')
816 return (
817 os.path.isdir(os.path.join(g, "rebase-merge")) or
818 os.path.isdir(os.path.join(g, "rebase-apply")))
819
820 def _CheckClean(self, rev_str):
821 # Make sure the tree is clean; see git-rebase.sh for reference
822 try:
823 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000824 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000825 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000826 raise gclient_utils.Error('\n____ %s%s\n'
827 '\tYou have unstaged changes.\n'
828 '\tPlease commit, stash, or reset.\n'
829 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000830 try:
831 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000832 '--ignore-submodules', 'HEAD', '--'],
833 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000834 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000835 raise gclient_utils.Error('\n____ %s%s\n'
836 '\tYour index contains uncommitted changes\n'
837 '\tPlease commit, stash, or reset.\n'
838 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000839
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000840 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000841 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
842 # reference by a commit). If not, error out -- most likely a rebase is
843 # in progress, try to detect so we can give a better error.
844 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000845 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
846 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000847 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000848 # Commit is not contained by any rev. See if the user is rebasing:
849 if self._IsRebasing():
850 # Punt to the user
851 raise gclient_utils.Error('\n____ %s%s\n'
852 '\tAlready in a conflict, i.e. (no branch).\n'
853 '\tFix the conflict and run gclient again.\n'
854 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
855 '\tSee man git-rebase for details.\n'
856 % (self.relpath, rev_str))
857 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000858 name = ('saved-by-gclient-' +
859 self._Capture(['rev-parse', '--short', 'HEAD']))
860 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000861 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000862 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000863
msb@chromium.org5bde4852009-12-14 16:47:12 +0000864 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000865 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000866 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000867 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000868 return None
869 return branch
870
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000871 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000872 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000873 ['git'] + args,
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000874 stderr=subprocess2.VOID,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000875 nag_timer=self.nag_timer,
876 nag_max=self.nag_max,
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000877 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000878
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000879 def _UpdateBranchHeads(self, options, fetch=False):
880 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
881 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
882 backoff_time = 5
883 for _ in range(3):
884 try:
885 config_cmd = ['config', 'remote.origin.fetch',
886 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
887 '^\\+refs/branch-heads/\\*:.*$']
888 self._Run(config_cmd, options)
889 if fetch:
890 fetch_cmd = ['fetch', 'origin']
891 if options.verbose:
892 fetch_cmd.append('--verbose')
893 self._Run(fetch_cmd, options)
894 break
895 except subprocess2.CalledProcessError, e:
896 print(str(e))
897 print('Retrying in %.1f seconds...' % backoff_time)
898 time.sleep(backoff_time)
899 backoff_time *= 1.3
900
maruel@chromium.org37e89872010-09-07 16:11:33 +0000901 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000902 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000903 kwargs.setdefault('print_stdout', True)
szager@chromium.org12b07e72013-05-03 22:06:34 +0000904 kwargs.setdefault('nag_timer', self.nag_timer)
905 kwargs.setdefault('nag_max', self.nag_max)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000906 stdout = kwargs.get('stdout', sys.stdout)
907 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
908 ' '.join(args), kwargs['cwd']))
909 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000910
911
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000912class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000913 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000914
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000915 @staticmethod
916 def BinaryExists():
917 """Returns true if the command exists."""
918 try:
919 result, version = scm.SVN.AssertVersion('1.4')
920 if not result:
921 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
922 return result
923 except OSError:
924 return False
925
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000926 def GetCheckoutRoot(self):
927 return scm.SVN.GetCheckoutRoot(self.checkout_path)
928
floitsch@google.comeaab7842011-04-28 09:07:58 +0000929 def GetRevisionDate(self, revision):
930 """Returns the given revision's date in ISO-8601 format (which contains the
931 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000932 date = scm.SVN.Capture(
933 ['propget', '--revprop', 'svn:date', '-r', revision],
934 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000935 return date.strip()
936
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000937 def cleanup(self, options, args, file_list):
938 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000939 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000940
941 def diff(self, options, args, file_list):
942 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000943 if not os.path.isdir(self.checkout_path):
944 raise gclient_utils.Error('Directory %s is not present.' %
945 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000946 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000947
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000948 def pack(self, options, args, file_list):
949 """Generates a patch file which can be applied to the root of the
950 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000951 if not os.path.isdir(self.checkout_path):
952 raise gclient_utils.Error('Directory %s is not present.' %
953 self.checkout_path)
954 gclient_utils.CheckCallAndFilter(
955 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
956 cwd=self.checkout_path,
957 print_stdout=False,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000958 nag_timer=self.nag_timer,
959 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000960 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000961
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000962 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000963 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000964
965 All updated files will be appended to file_list.
966
967 Raises:
968 Error: if can't get URL for relative path.
969 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000970 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000971 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000972 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000973 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000974 return
975
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000976 hg_path = os.path.join(self.checkout_path, '.hg')
977 if os.path.exists(hg_path):
978 print('________ found .hg directory; skipping %s' % self.relpath)
979 return
980
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000981 if args:
982 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
983
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000984 # revision is the revision to match. It is None if no revision is specified,
985 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000986 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000987 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000988 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000989 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000990 if options.revision:
991 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000992 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000993 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000994 if revision != 'unmanaged':
995 forced_revision = True
996 # Reconstruct the url.
997 url = '%s@%s' % (url, revision)
998 rev_str = ' at %s' % revision
999 else:
1000 managed = False
1001 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001002 else:
1003 forced_revision = False
1004 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001005
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001006 # Get the existing scm url and the revision number of the current checkout.
1007 exists = os.path.exists(self.checkout_path)
1008 if exists and managed:
1009 try:
1010 from_info = scm.SVN.CaptureLocalInfo(
1011 [], os.path.join(self.checkout_path, '.'))
1012 except (gclient_utils.Error, subprocess2.CalledProcessError):
1013 if options.reset and options.delete_unversioned_trees:
1014 print 'Removing troublesome path %s' % self.checkout_path
1015 gclient_utils.rmtree(self.checkout_path)
1016 exists = False
1017 else:
1018 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1019 'present. Delete the directory and try again.')
1020 raise gclient_utils.Error(msg % self.checkout_path)
1021
1022 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001023 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001024 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001025 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001026 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001027 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001028 return
1029
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001030 if not managed:
1031 print ('________ unmanaged solution; skipping %s' % self.relpath)
1032 return
1033
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001034 if 'URL' not in from_info:
1035 raise gclient_utils.Error(
1036 ('gclient is confused. Couldn\'t get the url for %s.\n'
1037 'Try using @unmanaged.\n%s') % (
1038 self.checkout_path, from_info))
1039
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001040 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001041 dir_info = scm.SVN.CaptureStatus(
1042 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001043 if any(d[0][2] == 'L' for d in dir_info):
1044 try:
1045 self._Run(['cleanup', self.checkout_path], options)
1046 except subprocess2.CalledProcessError, e:
1047 # Get the status again, svn cleanup may have cleaned up at least
1048 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001049 dir_info = scm.SVN.CaptureStatus(
1050 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001051
1052 # Try to fix the failures by removing troublesome files.
1053 for d in dir_info:
1054 if d[0][2] == 'L':
1055 if d[0][0] == '!' and options.force:
1056 print 'Removing troublesome path %s' % d[1]
1057 gclient_utils.rmtree(d[1])
1058 else:
1059 print 'Not removing troublesome path %s automatically.' % d[1]
1060 if d[0][0] == '!':
1061 print 'You can pass --force to enable automatic removal.'
1062 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001063
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001064 # Retrieve the current HEAD version because svn is slow at null updates.
1065 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001066 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001067 revision = str(from_info_live['Revision'])
1068 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001069
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001070 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001071 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001072 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001073 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001074 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001075 # The url is invalid or the server is not accessible, it's safer to bail
1076 # out right now.
1077 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001078 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1079 and (from_info['UUID'] == to_info['UUID']))
1080 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001081 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001082 # We have different roots, so check if we can switch --relocate.
1083 # Subversion only permits this if the repository UUIDs match.
1084 # Perform the switch --relocate, then rewrite the from_url
1085 # to reflect where we "are now." (This is the same way that
1086 # Subversion itself handles the metadata when switch --relocate
1087 # is used.) This makes the checks below for whether we
1088 # can update to a revision or have to switch to a different
1089 # branch work as expected.
1090 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001091 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001092 from_info['Repository Root'],
1093 to_info['Repository Root'],
1094 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001095 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001096 from_info['URL'] = from_info['URL'].replace(
1097 from_info['Repository Root'],
1098 to_info['Repository Root'])
1099 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001100 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001101 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001102 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001103 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001104 raise gclient_utils.Error(
1105 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1106 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001107 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001108 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001109 print('\n_____ switching %s to a new checkout' % self.relpath)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001110 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001111 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001112 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001113 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001114 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001115 return
1116
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001117 # If the provided url has a revision number that matches the revision
1118 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001119 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001120 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001121 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001122 else:
1123 command = ['update', self.checkout_path]
1124 command = self._AddAdditionalUpdateFlags(command, options, revision)
1125 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001126
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001127 # If --reset and --delete_unversioned_trees are specified, remove any
1128 # untracked files and directories.
1129 if options.reset and options.delete_unversioned_trees:
1130 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1131 full_path = os.path.join(self.checkout_path, status[1])
1132 if (status[0][0] == '?'
1133 and os.path.isdir(full_path)
1134 and not os.path.islink(full_path)):
1135 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001136 gclient_utils.rmtree(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001137
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001138 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001139 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001140 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001141 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001142 # Create an empty checkout and then update the one file we want. Future
1143 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001144 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001145 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001146 if os.path.exists(os.path.join(self.checkout_path, filename)):
1147 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001148 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001149 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001150 # After the initial checkout, we can use update as if it were any other
1151 # dep.
1152 self.update(options, args, file_list)
1153 else:
1154 # If the installed version of SVN doesn't support --depth, fallback to
1155 # just exporting the file. This has the downside that revision
1156 # information is not stored next to the file, so we will have to
1157 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001158 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001159 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001160 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001161 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001162 command = self._AddAdditionalUpdateFlags(command, options,
1163 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001164 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001165
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001166 def revert(self, options, args, file_list):
1167 """Reverts local modifications. Subversion specific.
1168
1169 All reverted files will be appended to file_list, even if Subversion
1170 doesn't know about them.
1171 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001172 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001173 if os.path.exists(self.checkout_path):
1174 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001175 # svn revert won't work if the directory doesn't exist. It needs to
1176 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001177 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001178 # Don't reuse the args.
1179 return self.update(options, [], file_list)
1180
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001181 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1182 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1183 print('________ found .git directory; skipping %s' % self.relpath)
1184 return
1185 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1186 print('________ found .hg directory; skipping %s' % self.relpath)
1187 return
1188 if not options.force:
1189 raise gclient_utils.Error('Invalid checkout path, aborting')
1190 print(
1191 '\n_____ %s is not a valid svn checkout, synching instead' %
1192 self.relpath)
1193 gclient_utils.rmtree(self.checkout_path)
1194 # Don't reuse the args.
1195 return self.update(options, [], file_list)
1196
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001197 def printcb(file_status):
1198 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001199 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001200 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001201 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001202 print(os.path.join(self.checkout_path, file_status[1]))
1203 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001204
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001205 # Revert() may delete the directory altogether.
1206 if not os.path.isdir(self.checkout_path):
1207 # Don't reuse the args.
1208 return self.update(options, [], file_list)
1209
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001210 try:
1211 # svn revert is so broken we don't even use it. Using
1212 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001213 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001214 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1215 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001216 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001217 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001218 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001219
msb@chromium.org0f282062009-11-06 20:14:02 +00001220 def revinfo(self, options, args, file_list):
1221 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001222 try:
1223 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001224 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001225 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001226
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001227 def runhooks(self, options, args, file_list):
1228 self.status(options, args, file_list)
1229
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001230 def status(self, options, args, file_list):
1231 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001232 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001233 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001234 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001235 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1236 'The directory does not exist.') %
1237 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001238 # There's no file list to retrieve.
1239 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001240 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001241
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001242 def GetUsableRev(self, rev, options):
1243 """Verifies the validity of the revision for this repository."""
1244 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1245 raise gclient_utils.Error(
1246 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1247 'correct.') % rev)
1248 return rev
1249
msb@chromium.orge6f78352010-01-13 17:05:33 +00001250 def FullUrlForRelativeUrl(self, url):
1251 # Find the forth '/' and strip from there. A bit hackish.
1252 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001253
maruel@chromium.org669600d2010-09-01 19:06:31 +00001254 def _Run(self, args, options, **kwargs):
1255 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001256 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.org12b07e72013-05-03 22:06:34 +00001257 kwargs.setdefault('nag_timer', self.nag_timer)
1258 kwargs.setdefault('nag_max', self.nag_max)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001259 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001260 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001261
1262 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1263 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001264 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001265 scm.SVN.RunAndGetFileList(
1266 options.verbose,
1267 args + ['--ignore-externals'],
1268 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001269 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001270
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001271 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001272 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001273 """Add additional flags to command depending on what options are set.
1274 command should be a list of strings that represents an svn command.
1275
1276 This method returns a new list to be used as a command."""
1277 new_command = command[:]
1278 if revision:
1279 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001280 # We don't want interaction when jobs are used.
1281 if options.jobs > 1:
1282 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001283 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001284 # --accept was added to 'svn update' in svn 1.6.
1285 if not scm.SVN.AssertVersion('1.5')[0]:
1286 return new_command
1287
1288 # It's annoying to have it block in the middle of a sync, just sensible
1289 # defaults.
1290 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001291 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001292 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1293 new_command.extend(('--accept', 'theirs-conflict'))
1294 elif options.manually_grab_svn_rev:
1295 new_command.append('--force')
1296 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1297 new_command.extend(('--accept', 'postpone'))
1298 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1299 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001300 return new_command