blob: 85d0d503265df5390f4eddd2a2b9b9e91ce29eea [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
124 nag_max = 3
125
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
floitsch@google.comeaab7842011-04-28 09:07:58 +0000176 def GetRevisionDate(self, revision):
177 """Returns the given revision's date in ISO-8601 format (which contains the
178 time zone)."""
179 # TODO(floitsch): get the time-stamp of the given revision and not just the
180 # time-stamp of the currently checked out revision.
181 return self._Capture(['log', '-n', '1', '--format=%ai'])
182
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000183 @staticmethod
184 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000185 """'Cleanup' the repo.
186
187 There's no real git equivalent for the svn cleanup command, do a no-op.
188 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000189
190 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000191 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000192 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000193
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000194 def pack(self, options, args, file_list):
195 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000196 repository.
197
198 The patch file is generated from a diff of the merge base of HEAD and
199 its upstream branch.
200 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000201 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000202 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000203 ['git', 'diff', merge_base],
204 cwd=self.checkout_path,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000205 nag_timer=self.nag_timer,
206 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000207 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000208
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000209 def UpdateSubmoduleConfig(self):
210 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
211 'submodule.$name.ignore', '||',
212 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000213 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000214 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000215 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000216 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000217 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000218 kwargs = {'cwd': self.checkout_path,
219 'print_stdout': False,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000220 'nag_timer': self.nag_timer,
221 'nag_max': self.nag_max,
szager@chromium.org987b0612012-07-09 23:41:08 +0000222 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000223 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000224 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
225 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000226 except subprocess2.CalledProcessError:
227 # Not a fatal error, or even very interesting in a non-git-submodule
228 # world. So just keep it quiet.
229 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000230 try:
231 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
232 except subprocess2.CalledProcessError:
233 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000234
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000235 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
236
msb@chromium.orge28e4982009-09-25 20:51:45 +0000237 def update(self, options, args, file_list):
238 """Runs git to update or transparently checkout the working copy.
239
240 All updated files will be appended to file_list.
241
242 Raises:
243 Error: if can't get URL for relative path.
244 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000245 if args:
246 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
247
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000248 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000249
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000250 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000251 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000252 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000253 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000254 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000255 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000256 # Override the revision number.
257 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000258 if revision == 'unmanaged':
259 revision = None
260 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000261 if not revision:
262 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000263
floitsch@google.comeaab7842011-04-28 09:07:58 +0000264 if gclient_utils.IsDateRevision(revision):
265 # Date-revisions only work on git-repositories if the reflog hasn't
266 # expired yet. Use rev-list to get the corresponding revision.
267 # git rev-list -n 1 --before='time-stamp' branchname
268 if options.transitive:
269 print('Warning: --transitive only works for SVN repositories.')
270 revision = default_rev
271
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000272 rev_str = ' at %s' % revision
273 files = []
274
275 printed_path = False
276 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000277 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000278 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000279 verbose = ['--verbose']
280 printed_path = True
281
282 if revision.startswith('refs/heads/'):
283 rev_type = "branch"
284 elif revision.startswith('origin/'):
285 # For compatability with old naming, translate 'origin' to 'refs/heads'
286 revision = revision.replace('origin/', 'refs/heads/')
287 rev_type = "branch"
288 else:
289 # hash is also a tag, only make a distinction at checkout
290 rev_type = "hash"
291
szager@google.com873e6672012-03-13 18:53:36 +0000292 if not os.path.exists(self.checkout_path) or (
293 os.path.isdir(self.checkout_path) and
294 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000295 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000296 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000297 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000298 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000299 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000300 if not verbose:
301 # Make the output a little prettier. It's nice to have some whitespace
302 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000303 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000304 return
305
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000306 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000307 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000308 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000309 print ('________ unmanaged solution; skipping %s' % self.relpath)
310 return
311
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000312 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
313 raise gclient_utils.Error('\n____ %s%s\n'
314 '\tPath is not a git repo. No .git dir.\n'
315 '\tTo resolve:\n'
316 '\t\trm -rf %s\n'
317 '\tAnd run gclient sync again\n'
318 % (self.relpath, rev_str, self.relpath))
319
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000320 # See if the url has changed (the unittests use git://foo for the url, let
321 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000322 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000323 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
324 # unit test pass. (and update the comment above)
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000325 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
326 # This allows devs to use experimental repos which have a different url
327 # but whose branch(s) are the same as official repos.
328 if (current_url != url and
329 url != 'git://foo' and
330 subprocess2.capture(
331 ['git', 'config', 'remote.origin.gclient-auto-fix-url'],
332 cwd=self.checkout_path).strip() != 'False'):
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000333 print('_____ switching %s to a new upstream' % self.relpath)
334 # Make sure it's clean
335 self._CheckClean(rev_str)
336 # Switch over to the new upstream
337 self._Run(['remote', 'set-url', 'origin', url], options)
338 quiet = []
339 if not options.verbose:
340 quiet = ['--quiet']
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000341 self._UpdateBranchHeads(options, fetch=False)
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000342 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
bauerb@chromium.org610060e2012-11-19 14:11:35 +0000343 self._Run(['reset', '--hard', revision] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000344 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000345 files = self._Capture(['ls-files']).splitlines()
346 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
347 return
348
msb@chromium.org5bde4852009-12-14 16:47:12 +0000349 cur_branch = self._GetCurrentBranch()
350
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000351 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000352 # 0) HEAD is detached. Probably from our initial clone.
353 # - make sure HEAD is contained by a named ref, then update.
354 # Cases 1-4. HEAD is a branch.
355 # 1) current branch is not tracking a remote branch (could be git-svn)
356 # - try to rebase onto the new hash or branch
357 # 2) current branch is tracking a remote branch with local committed
358 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000359 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000360 # 3) current branch is tracking a remote branch w/or w/out changes,
361 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000362 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000363 # 4) current branch is tracking a remote branch, switches to a different
364 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000365 # - exit
366
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000367 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
368 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000369 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
370 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000371 if cur_branch is None:
372 upstream_branch = None
373 current_type = "detached"
374 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000375 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000376 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
377 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
378 current_type = "hash"
379 logging.debug("Current branch is not tracking an upstream (remote)"
380 " branch.")
381 elif upstream_branch.startswith('refs/remotes'):
382 current_type = "branch"
383 else:
384 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000385
maruel@chromium.org92067382012-06-28 19:58:41 +0000386 if (not re.match(r'^[0-9a-fA-F]{40}$', revision) or
387 not scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=revision)):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000388 # Update the remotes first so we have all the refs.
389 backoff_time = 5
390 for _ in range(10):
391 try:
392 remote_output = scm.GIT.Capture(
393 ['remote'] + verbose + ['update'],
394 cwd=self.checkout_path)
395 break
396 except subprocess2.CalledProcessError, e:
397 # Hackish but at that point, git is known to work so just checking for
398 # 502 in stderr should be fine.
399 if '502' in e.stderr:
400 print(str(e))
401 print('Sleeping %.1f seconds and retrying...' % backoff_time)
402 time.sleep(backoff_time)
403 backoff_time *= 1.3
404 continue
405 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000406
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000407 if verbose:
408 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000409
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000410 self._UpdateBranchHeads(options, fetch=True)
411
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000412 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000413 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000414 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000415
msb@chromium.org786fb682010-06-02 15:16:23 +0000416 if current_type == 'detached':
417 # case 0
418 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000419 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000420 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000421 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000422 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000423 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000424 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000425 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000426 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000427 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000428 newbase=revision, printed_path=printed_path)
429 printed_path = True
430 else:
431 # Can't find a merge-base since we don't know our upstream. That makes
432 # this command VERY likely to produce a rebase failure. For now we
433 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000434 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000435 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000436 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000437 self._AttemptRebase(upstream_branch, files, options,
438 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000439 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000440 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000441 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000442 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000443 newbase=revision, printed_path=printed_path)
444 printed_path = True
445 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
446 # case 4
447 new_base = revision.replace('heads', 'remotes/origin')
448 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000449 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000450 switch_error = ("Switching upstream branch from %s to %s\n"
451 % (upstream_branch, new_base) +
452 "Please merge or rebase manually:\n" +
453 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
454 "OR git checkout -b <some new branch> %s" % new_base)
455 raise gclient_utils.Error(switch_error)
456 else:
457 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000458 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000459 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000460 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000461 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000462 merge_args = ['merge']
463 if not options.merge:
464 merge_args.append('--ff-only')
465 merge_args.append(upstream_branch)
466 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000467 except subprocess2.CalledProcessError as e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000468 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
469 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000470 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000471 printed_path = True
472 while True:
473 try:
maruel@chromium.org90541732011-04-01 17:54:18 +0000474 action = ask_for_data(
475 'Cannot fast-forward merge, attempt to rebase? '
bratell@opera.com18fa4542013-05-21 13:30:46 +0000476 '(y)es / (q)uit / (s)kip : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000477 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000478 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000479 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000480 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000481 printed_path=printed_path)
482 printed_path = True
483 break
484 elif re.match(r'quit|q', action, re.I):
485 raise gclient_utils.Error("Can't fast-forward, please merge or "
486 "rebase manually.\n"
487 "cd %s && git " % self.checkout_path
488 + "rebase %s" % upstream_branch)
489 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000490 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000491 return
492 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000493 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000494 elif re.match("error: Your local changes to '.*' would be "
495 "overwritten by merge. Aborting.\nPlease, commit your "
496 "changes or stash them before you can merge.\n",
497 e.stderr):
498 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000499 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000500 printed_path = True
501 raise gclient_utils.Error(e.stderr)
502 else:
503 # Some other problem happened with the merge
504 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000505 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000506 raise
507 else:
508 # Fast-forward merge was successful
509 if not re.match('Already up-to-date.', merge_output) or verbose:
510 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000511 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000512 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000513 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000514 if not verbose:
515 # Make the output a little prettier. It's nice to have some
516 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000517 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000518
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000519 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000520 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000521
522 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000523 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000524 raise gclient_utils.Error('\n____ %s%s\n'
525 '\nConflict while rebasing this branch.\n'
526 'Fix the conflict and run gclient again.\n'
527 'See man git-rebase for details.\n'
528 % (self.relpath, rev_str))
529
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000530 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000531 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000532
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000533 # If --reset and --delete_unversioned_trees are specified, remove any
534 # untracked directories.
535 if options.reset and options.delete_unversioned_trees:
536 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
537 # merge-base by default), so doesn't include untracked files. So we use
538 # 'git ls-files --directory --others --exclude-standard' here directly.
539 paths = scm.GIT.Capture(
540 ['ls-files', '--directory', '--others', '--exclude-standard'],
541 self.checkout_path)
542 for path in (p for p in paths.splitlines() if p.endswith('/')):
543 full_path = os.path.join(self.checkout_path, path)
544 if not os.path.islink(full_path):
545 print('\n_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000546 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000547
548
msb@chromium.orge28e4982009-09-25 20:51:45 +0000549 def revert(self, options, args, file_list):
550 """Reverts local modifications.
551
552 All reverted files will be appended to file_list.
553 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000554 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000555 # revert won't work if the directory doesn't exist. It needs to
556 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000557 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000558 # Don't reuse the args.
559 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000560
561 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000562 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000563 if not deps_revision:
564 deps_revision = default_rev
565 if deps_revision.startswith('refs/heads/'):
566 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
567
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000568 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000569 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000570 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000571 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
572
msb@chromium.org0f282062009-11-06 20:14:02 +0000573 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000574 """Returns revision"""
575 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000576
msb@chromium.orge28e4982009-09-25 20:51:45 +0000577 def runhooks(self, options, args, file_list):
578 self.status(options, args, file_list)
579
580 def status(self, options, args, file_list):
581 """Display status information."""
582 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000583 print(('\n________ couldn\'t run status in %s:\n'
584 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000585 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000586 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000587 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000588 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000589 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
590
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000591 def GetUsableRev(self, rev, options):
592 """Finds a useful revision for this repository.
593
594 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
595 will be called on the source."""
596 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000597 if not os.path.isdir(self.checkout_path):
598 raise gclient_utils.Error(
599 ( 'We could not find a valid hash for safesync_url response "%s".\n'
600 'Safesync URLs with a git checkout currently require the repo to\n'
601 'be cloned without a safesync_url before adding the safesync_url.\n'
602 'For more info, see: '
603 'http://code.google.com/p/chromium/wiki/UsingNewGit'
604 '#Initial_checkout' ) % rev)
605 elif rev.isdigit() and len(rev) < 7:
606 # Handles an SVN rev. As an optimization, only verify an SVN revision as
607 # [0-9]{1,6} for now to avoid making a network request.
608 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000609 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
610 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000611 try:
612 logging.debug('Looking for git-svn configuration optimizations.')
613 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
614 cwd=self.checkout_path):
615 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
616 except subprocess2.CalledProcessError:
617 logging.debug('git config --get svn-remote.svn.fetch failed, '
618 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000619 if options.verbose:
620 print('Running git svn fetch. This might take a while.\n')
621 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000622 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000623 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
624 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000625 except gclient_utils.Error, e:
626 sha1 = e.message
627 print('\nWarning: Could not find a git revision with accurate\n'
628 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
629 'the closest sane git revision, which is:\n'
630 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000631 if not sha1:
632 raise gclient_utils.Error(
633 ( 'It appears that either your git-svn remote is incorrectly\n'
634 'configured or the revision in your safesync_url is\n'
635 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
636 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000637 else:
638 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
639 sha1 = rev
640 else:
641 # May exist in origin, but we don't have it yet, so fetch and look
642 # again.
643 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
644 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
645 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000646
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000647 if not sha1:
648 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000649 ( 'We could not find a valid hash for safesync_url response "%s".\n'
650 'Safesync URLs with a git checkout currently require a git-svn\n'
651 'remote or a safesync_url that provides git sha1s. Please add a\n'
652 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000653 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000654 '#Initial_checkout' ) % rev)
655
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000656 return sha1
657
msb@chromium.orge6f78352010-01-13 17:05:33 +0000658 def FullUrlForRelativeUrl(self, url):
659 # Strip from last '/'
660 # Equivalent to unix basename
661 base_url = self.url
662 return base_url[:base_url.rfind('/')] + url
663
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000664 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000665 """Clone a git repository from the given URL.
666
msb@chromium.org786fb682010-06-02 15:16:23 +0000667 Once we've cloned the repo, we checkout a working branch if the specified
668 revision is a branch head. If it is a tag or a specific commit, then we
669 leave HEAD detached as it makes future updates simpler -- in this case the
670 user should first create a new branch or switch to an existing branch before
671 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000672 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000673 # git clone doesn't seem to insert a newline properly before printing
674 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000675 print('')
szager@chromium.orgee10d7d2013-04-24 23:18:20 +0000676 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000677 if revision.startswith('refs/heads/'):
678 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
679 detach_head = False
680 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000681 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000682 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000683 clone_cmd.append('--verbose')
684 clone_cmd.extend([url, self.checkout_path])
685
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000686 # If the parent directory does not exist, Git clone on Windows will not
687 # create it, so we need to do it manually.
688 parent_dir = os.path.dirname(self.checkout_path)
689 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000690 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000691
szager@google.com85d3e3a2011-10-07 17:12:00 +0000692 percent_re = re.compile('.* ([0-9]{1,2})% .*')
693 def _GitFilter(line):
694 # git uses an escape sequence to clear the line; elide it.
695 esc = line.find(unichr(033))
696 if esc > -1:
697 line = line[:esc]
698 match = percent_re.match(line)
699 if not match or not int(match.group(1)) % 10:
700 print '%s' % line
701
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000702 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000703 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000704 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
705 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000706 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000707 except subprocess2.CalledProcessError, e:
708 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000709 # We should check for "transfer closed with NNN bytes remaining to
710 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000711 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000712 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000713 print(str(e))
714 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000715 continue
716 raise e
717
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000718 # Update the "branch-heads" remote-tracking branches, since we might need it
719 # to checkout a specific revision below.
720 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org059cc452013-03-11 15:14:35 +0000721
msb@chromium.org786fb682010-06-02 15:16:23 +0000722 if detach_head:
723 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000724 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000725 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000726 ('Checked out %s to a detached HEAD. Before making any commits\n'
727 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
728 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
729 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000730
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000731 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000732 branch=None, printed_path=False):
733 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000734 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000735 revision = upstream
736 if newbase:
737 revision = newbase
738 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000739 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000740 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000741 printed_path = True
742 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000743 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000744
745 # Build the rebase command here using the args
746 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
747 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000748 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000749 rebase_cmd.append('--verbose')
750 if newbase:
751 rebase_cmd.extend(['--onto', newbase])
752 rebase_cmd.append(upstream)
753 if branch:
754 rebase_cmd.append(branch)
755
756 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000757 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000758 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000759 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
760 re.match(r'cannot rebase: your index contains uncommitted changes',
761 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000762 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000763 rebase_action = ask_for_data(
764 'Cannot rebase because of unstaged changes.\n'
765 '\'git reset --hard HEAD\' ?\n'
766 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000767 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000768 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000769 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000770 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000771 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000772 break
773 elif re.match(r'quit|q', rebase_action, re.I):
774 raise gclient_utils.Error("Please merge or rebase manually\n"
775 "cd %s && git " % self.checkout_path
776 + "%s" % ' '.join(rebase_cmd))
777 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000778 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000779 continue
780 else:
781 gclient_utils.Error("Input not recognized")
782 continue
783 elif re.search(r'^CONFLICT', e.stdout, re.M):
784 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
785 "Fix the conflict and run gclient again.\n"
786 "See 'man git-rebase' for details.\n")
787 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000788 print(e.stdout.strip())
789 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000790 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
791 "manually.\ncd %s && git " %
792 self.checkout_path
793 + "%s" % ' '.join(rebase_cmd))
794
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000795 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000796 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000797 # Make the output a little prettier. It's nice to have some
798 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000799 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000800
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000801 @staticmethod
802 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000803 (ok, current_version) = scm.GIT.AssertVersion(min_version)
804 if not ok:
805 raise gclient_utils.Error('git version %s < minimum required %s' %
806 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000807
msb@chromium.org786fb682010-06-02 15:16:23 +0000808 def _IsRebasing(self):
809 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
810 # have a plumbing command to determine whether a rebase is in progress, so
811 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
812 g = os.path.join(self.checkout_path, '.git')
813 return (
814 os.path.isdir(os.path.join(g, "rebase-merge")) or
815 os.path.isdir(os.path.join(g, "rebase-apply")))
816
817 def _CheckClean(self, rev_str):
818 # Make sure the tree is clean; see git-rebase.sh for reference
819 try:
820 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000821 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000822 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000823 raise gclient_utils.Error('\n____ %s%s\n'
824 '\tYou have unstaged changes.\n'
825 '\tPlease commit, stash, or reset.\n'
826 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000827 try:
828 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000829 '--ignore-submodules', 'HEAD', '--'],
830 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000831 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000832 raise gclient_utils.Error('\n____ %s%s\n'
833 '\tYour index contains uncommitted changes\n'
834 '\tPlease commit, stash, or reset.\n'
835 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000836
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000837 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000838 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
839 # reference by a commit). If not, error out -- most likely a rebase is
840 # in progress, try to detect so we can give a better error.
841 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000842 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
843 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000844 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000845 # Commit is not contained by any rev. See if the user is rebasing:
846 if self._IsRebasing():
847 # Punt to the user
848 raise gclient_utils.Error('\n____ %s%s\n'
849 '\tAlready in a conflict, i.e. (no branch).\n'
850 '\tFix the conflict and run gclient again.\n'
851 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
852 '\tSee man git-rebase for details.\n'
853 % (self.relpath, rev_str))
854 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000855 name = ('saved-by-gclient-' +
856 self._Capture(['rev-parse', '--short', 'HEAD']))
857 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000858 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000859 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000860
msb@chromium.org5bde4852009-12-14 16:47:12 +0000861 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000862 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000863 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000864 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000865 return None
866 return branch
867
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000868 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000869 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000870 ['git'] + args,
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000871 stderr=subprocess2.VOID,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000872 nag_timer=self.nag_timer,
873 nag_max=self.nag_max,
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000874 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000875
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000876 def _UpdateBranchHeads(self, options, fetch=False):
877 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
878 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
879 backoff_time = 5
880 for _ in range(3):
881 try:
882 config_cmd = ['config', 'remote.origin.fetch',
883 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
884 '^\\+refs/branch-heads/\\*:.*$']
885 self._Run(config_cmd, options)
886 if fetch:
887 fetch_cmd = ['fetch', 'origin']
888 if options.verbose:
889 fetch_cmd.append('--verbose')
890 self._Run(fetch_cmd, options)
891 break
892 except subprocess2.CalledProcessError, e:
893 print(str(e))
894 print('Retrying in %.1f seconds...' % backoff_time)
895 time.sleep(backoff_time)
896 backoff_time *= 1.3
897
maruel@chromium.org37e89872010-09-07 16:11:33 +0000898 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000899 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000900 kwargs.setdefault('print_stdout', True)
szager@chromium.org12b07e72013-05-03 22:06:34 +0000901 kwargs.setdefault('nag_timer', self.nag_timer)
902 kwargs.setdefault('nag_max', self.nag_max)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000903 stdout = kwargs.get('stdout', sys.stdout)
904 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
905 ' '.join(args), kwargs['cwd']))
906 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000907
908
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000909class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000910 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000911
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000912 @staticmethod
913 def BinaryExists():
914 """Returns true if the command exists."""
915 try:
916 result, version = scm.SVN.AssertVersion('1.4')
917 if not result:
918 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
919 return result
920 except OSError:
921 return False
922
floitsch@google.comeaab7842011-04-28 09:07:58 +0000923 def GetRevisionDate(self, revision):
924 """Returns the given revision's date in ISO-8601 format (which contains the
925 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000926 date = scm.SVN.Capture(
927 ['propget', '--revprop', 'svn:date', '-r', revision],
928 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000929 return date.strip()
930
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000931 def cleanup(self, options, args, file_list):
932 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000933 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000934
935 def diff(self, options, args, file_list):
936 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000937 if not os.path.isdir(self.checkout_path):
938 raise gclient_utils.Error('Directory %s is not present.' %
939 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000940 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000941
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000942 def pack(self, options, args, file_list):
943 """Generates a patch file which can be applied to the root of the
944 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000945 if not os.path.isdir(self.checkout_path):
946 raise gclient_utils.Error('Directory %s is not present.' %
947 self.checkout_path)
948 gclient_utils.CheckCallAndFilter(
949 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
950 cwd=self.checkout_path,
951 print_stdout=False,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000952 nag_timer=self.nag_timer,
953 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000954 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000955
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000956 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000957 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000958
959 All updated files will be appended to file_list.
960
961 Raises:
962 Error: if can't get URL for relative path.
963 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000964 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000965 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000966 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000967 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000968 return
969
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000970 hg_path = os.path.join(self.checkout_path, '.hg')
971 if os.path.exists(hg_path):
972 print('________ found .hg directory; skipping %s' % self.relpath)
973 return
974
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000975 if args:
976 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
977
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000978 # revision is the revision to match. It is None if no revision is specified,
979 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000980 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000981 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000982 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000983 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000984 if options.revision:
985 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000986 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000987 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000988 if revision != 'unmanaged':
989 forced_revision = True
990 # Reconstruct the url.
991 url = '%s@%s' % (url, revision)
992 rev_str = ' at %s' % revision
993 else:
994 managed = False
995 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000996 else:
997 forced_revision = False
998 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000999
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001000 # Get the existing scm url and the revision number of the current checkout.
1001 exists = os.path.exists(self.checkout_path)
1002 if exists and managed:
1003 try:
1004 from_info = scm.SVN.CaptureLocalInfo(
1005 [], os.path.join(self.checkout_path, '.'))
1006 except (gclient_utils.Error, subprocess2.CalledProcessError):
1007 if options.reset and options.delete_unversioned_trees:
1008 print 'Removing troublesome path %s' % self.checkout_path
1009 gclient_utils.rmtree(self.checkout_path)
1010 exists = False
1011 else:
1012 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1013 'present. Delete the directory and try again.')
1014 raise gclient_utils.Error(msg % self.checkout_path)
1015
1016 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001017 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001018 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001019 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001020 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001021 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001022 return
1023
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001024 if not managed:
1025 print ('________ unmanaged solution; skipping %s' % self.relpath)
1026 return
1027
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001028 if 'URL' not in from_info:
1029 raise gclient_utils.Error(
1030 ('gclient is confused. Couldn\'t get the url for %s.\n'
1031 'Try using @unmanaged.\n%s') % (
1032 self.checkout_path, from_info))
1033
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001034 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001035 dir_info = scm.SVN.CaptureStatus(
1036 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001037 if any(d[0][2] == 'L' for d in dir_info):
1038 try:
1039 self._Run(['cleanup', self.checkout_path], options)
1040 except subprocess2.CalledProcessError, e:
1041 # Get the status again, svn cleanup may have cleaned up at least
1042 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001043 dir_info = scm.SVN.CaptureStatus(
1044 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001045
1046 # Try to fix the failures by removing troublesome files.
1047 for d in dir_info:
1048 if d[0][2] == 'L':
1049 if d[0][0] == '!' and options.force:
1050 print 'Removing troublesome path %s' % d[1]
1051 gclient_utils.rmtree(d[1])
1052 else:
1053 print 'Not removing troublesome path %s automatically.' % d[1]
1054 if d[0][0] == '!':
1055 print 'You can pass --force to enable automatic removal.'
1056 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001057
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001058 # Retrieve the current HEAD version because svn is slow at null updates.
1059 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001060 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001061 revision = str(from_info_live['Revision'])
1062 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001063
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001064 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001065 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001066 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001067 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001068 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001069 # The url is invalid or the server is not accessible, it's safer to bail
1070 # out right now.
1071 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001072 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1073 and (from_info['UUID'] == to_info['UUID']))
1074 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001075 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001076 # We have different roots, so check if we can switch --relocate.
1077 # Subversion only permits this if the repository UUIDs match.
1078 # Perform the switch --relocate, then rewrite the from_url
1079 # to reflect where we "are now." (This is the same way that
1080 # Subversion itself handles the metadata when switch --relocate
1081 # is used.) This makes the checks below for whether we
1082 # can update to a revision or have to switch to a different
1083 # branch work as expected.
1084 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001085 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001086 from_info['Repository Root'],
1087 to_info['Repository Root'],
1088 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001089 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001090 from_info['URL'] = from_info['URL'].replace(
1091 from_info['Repository Root'],
1092 to_info['Repository Root'])
1093 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001094 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001095 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001096 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001097 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001098 raise gclient_utils.Error(
1099 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1100 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001101 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001102 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001103 print('\n_____ switching %s to a new checkout' % self.relpath)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001104 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001105 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001106 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001107 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001108 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001109 return
1110
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001111 # If the provided url has a revision number that matches the revision
1112 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001113 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001114 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001115 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001116 else:
1117 command = ['update', self.checkout_path]
1118 command = self._AddAdditionalUpdateFlags(command, options, revision)
1119 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001120
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001121 # If --reset and --delete_unversioned_trees are specified, remove any
1122 # untracked files and directories.
1123 if options.reset and options.delete_unversioned_trees:
1124 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1125 full_path = os.path.join(self.checkout_path, status[1])
1126 if (status[0][0] == '?'
1127 and os.path.isdir(full_path)
1128 and not os.path.islink(full_path)):
1129 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001130 gclient_utils.rmtree(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001131
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001132 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001133 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001134 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001135 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001136 # Create an empty checkout and then update the one file we want. Future
1137 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001138 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001139 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001140 if os.path.exists(os.path.join(self.checkout_path, filename)):
1141 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001142 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001143 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001144 # After the initial checkout, we can use update as if it were any other
1145 # dep.
1146 self.update(options, args, file_list)
1147 else:
1148 # If the installed version of SVN doesn't support --depth, fallback to
1149 # just exporting the file. This has the downside that revision
1150 # information is not stored next to the file, so we will have to
1151 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001152 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001153 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001154 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001155 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001156 command = self._AddAdditionalUpdateFlags(command, options,
1157 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001158 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001159
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001160 def revert(self, options, args, file_list):
1161 """Reverts local modifications. Subversion specific.
1162
1163 All reverted files will be appended to file_list, even if Subversion
1164 doesn't know about them.
1165 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001166 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001167 if os.path.exists(self.checkout_path):
1168 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001169 # svn revert won't work if the directory doesn't exist. It needs to
1170 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001171 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001172 # Don't reuse the args.
1173 return self.update(options, [], file_list)
1174
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001175 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1176 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1177 print('________ found .git directory; skipping %s' % self.relpath)
1178 return
1179 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1180 print('________ found .hg directory; skipping %s' % self.relpath)
1181 return
1182 if not options.force:
1183 raise gclient_utils.Error('Invalid checkout path, aborting')
1184 print(
1185 '\n_____ %s is not a valid svn checkout, synching instead' %
1186 self.relpath)
1187 gclient_utils.rmtree(self.checkout_path)
1188 # Don't reuse the args.
1189 return self.update(options, [], file_list)
1190
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001191 def printcb(file_status):
1192 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001193 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001194 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001195 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001196 print(os.path.join(self.checkout_path, file_status[1]))
1197 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001198
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001199 # Revert() may delete the directory altogether.
1200 if not os.path.isdir(self.checkout_path):
1201 # Don't reuse the args.
1202 return self.update(options, [], file_list)
1203
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001204 try:
1205 # svn revert is so broken we don't even use it. Using
1206 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001207 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001208 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1209 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001210 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001211 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001212 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001213
msb@chromium.org0f282062009-11-06 20:14:02 +00001214 def revinfo(self, options, args, file_list):
1215 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001216 try:
1217 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001218 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001219 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001220
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001221 def runhooks(self, options, args, file_list):
1222 self.status(options, args, file_list)
1223
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001224 def status(self, options, args, file_list):
1225 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001226 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001227 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001228 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001229 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1230 'The directory does not exist.') %
1231 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001232 # There's no file list to retrieve.
1233 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001234 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001235
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001236 def GetUsableRev(self, rev, options):
1237 """Verifies the validity of the revision for this repository."""
1238 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1239 raise gclient_utils.Error(
1240 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1241 'correct.') % rev)
1242 return rev
1243
msb@chromium.orge6f78352010-01-13 17:05:33 +00001244 def FullUrlForRelativeUrl(self, url):
1245 # Find the forth '/' and strip from there. A bit hackish.
1246 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001247
maruel@chromium.org669600d2010-09-01 19:06:31 +00001248 def _Run(self, args, options, **kwargs):
1249 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001250 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.org12b07e72013-05-03 22:06:34 +00001251 kwargs.setdefault('nag_timer', self.nag_timer)
1252 kwargs.setdefault('nag_max', self.nag_max)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001253 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001254 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001255
1256 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1257 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001258 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001259 scm.SVN.RunAndGetFileList(
1260 options.verbose,
1261 args + ['--ignore-externals'],
1262 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001263 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001264
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001265 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001266 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001267 """Add additional flags to command depending on what options are set.
1268 command should be a list of strings that represents an svn command.
1269
1270 This method returns a new list to be used as a command."""
1271 new_command = command[:]
1272 if revision:
1273 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001274 # We don't want interaction when jobs are used.
1275 if options.jobs > 1:
1276 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001277 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001278 # --accept was added to 'svn update' in svn 1.6.
1279 if not scm.SVN.AssertVersion('1.5')[0]:
1280 return new_command
1281
1282 # It's annoying to have it block in the middle of a sync, just sensible
1283 # defaults.
1284 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001285 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001286 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1287 new_command.extend(('--accept', 'theirs-conflict'))
1288 elif options.manually_grab_svn_rev:
1289 new_command.append('--force')
1290 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1291 new_command.extend(('--accept', 'postpone'))
1292 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1293 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001294 return new_command