blob: 5ae69eed2baf58181da124614fa008af96a15a29 [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
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00007import collections
maruel@chromium.org754960e2009-09-21 12:31:05 +00008import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00009import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000010import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000011import re
maruel@chromium.org90541732011-04-01 17:54:18 +000012import sys
iannucci@chromium.org53456aa2013-07-03 19:38:34 +000013import threading
maruel@chromium.orgfd876172010-04-30 14:01:05 +000014import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015
16import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000017import scm
18import subprocess2
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000019
20
szager@chromium.org71cbb502013-04-19 23:30:15 +000021THIS_FILE_PATH = os.path.abspath(__file__)
22
23
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000024class DiffFiltererWrapper(object):
25 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000026 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000027 working copy lines of the svn/git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000028 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000029 original_prefix = "--- "
30 working_prefix = "+++ "
31
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000032 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000033 # Note that we always use '/' as the path separator to be
34 # consistent with svn's cygwin-style output on Windows
35 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000036 self._current_file = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000037
maruel@chromium.org6e29d572010-06-04 17:32:20 +000038 def SetCurrentFile(self, current_file):
39 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000040
iannucci@chromium.org3830a672013-02-19 20:15:14 +000041 @property
42 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000043 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000044
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000045 def _Replace(self, line):
46 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000047
48 def Filter(self, line):
49 if (line.startswith(self.index_string)):
50 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000051 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000052 else:
53 if (line.startswith(self.original_prefix) or
54 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000055 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000056 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000057
58
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000059class SvnDiffFilterer(DiffFiltererWrapper):
60 index_string = "Index: "
61
62
63class GitDiffFilterer(DiffFiltererWrapper):
64 index_string = "diff --git "
65
66 def SetCurrentFile(self, current_file):
67 # Get filename by parsing "a/<filename> b/<filename>"
68 self._current_file = current_file[:(len(current_file)/2)][2:]
69
70 def _Replace(self, line):
71 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
72
73
bratell@opera.com18fa4542013-05-21 13:30:46 +000074def ask_for_data(prompt, options):
75 if options.jobs > 1:
76 raise gclient_utils.Error("Background task requires input. Rerun "
77 "gclient with --jobs=1 so that\n"
78 "interaction is possible.")
maruel@chromium.org90541732011-04-01 17:54:18 +000079 try:
80 return raw_input(prompt)
81 except KeyboardInterrupt:
82 # Hide the exception.
83 sys.exit(1)
84
85
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000086### SCM abstraction layer
87
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000088# Factory Method for SCM wrapper creation
89
maruel@chromium.org9eda4112010-06-11 18:56:10 +000090def GetScmName(url):
91 if url:
92 url, _ = gclient_utils.SplitUrlRevision(url)
93 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000094 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000095 url.endswith('.git')):
96 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000097 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000098 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000099 return 'svn'
100 return None
101
102
103def CreateSCM(url, root_dir=None, relpath=None):
104 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000105 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +0000106 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000107 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000108
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000109 scm_name = GetScmName(url)
110 if not scm_name in SCM_MAP:
111 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000112 scm_class = SCM_MAP[scm_name]
113 if not scm_class.BinaryExists():
114 raise gclient_utils.Error('%s command not found' % scm_name)
115 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000116
117
118# SCMWrapper base class
119
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000120class SCMWrapper(object):
121 """Add necessary glue between all the supported SCM.
122
msb@chromium.orgd6504212010-01-13 17:34:31 +0000123 This is the abstraction layer to bind to different SCM.
124 """
szager@chromium.org12b07e72013-05-03 22:06:34 +0000125 nag_timer = 30
szager@chromium.org41da24b2013-05-23 19:37:04 +0000126 nag_max = 6
szager@chromium.org12b07e72013-05-03 22:06:34 +0000127
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000128 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000129 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000130 self._root_dir = root_dir
131 if self._root_dir:
132 self._root_dir = self._root_dir.replace('/', os.sep)
133 self.relpath = relpath
134 if self.relpath:
135 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000136 if self.relpath and self._root_dir:
137 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000138
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000139 def RunCommand(self, command, options, args, file_list=None):
140 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000141 if file_list is None:
142 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000143
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000144 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000145 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000146
147 if not command in commands:
148 raise gclient_utils.Error('Unknown command %s' % command)
149
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000150 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000151 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000152 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000153
154 return getattr(self, command)(options, args, file_list)
155
156
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000157class GitFilter(object):
158 """A filter_fn implementation for quieting down git output messages.
159
160 Allows a custom function to skip certain lines (predicate), and will throttle
161 the output of percentage completed lines to only output every X seconds.
162 """
163 PERCENT_RE = re.compile('.* ([0-9]{1,2})% .*')
164
165 def __init__(self, time_throttle=0, predicate=None):
166 """
167 Args:
168 time_throttle (int): GitFilter will throttle 'noisy' output (such as the
169 XX% complete messages) to only be printed at least |time_throttle|
170 seconds apart.
171 predicate (f(line)): An optional function which is invoked for every line.
172 The line will be skipped if predicate(line) returns False.
173 """
174 self.last_time = 0
175 self.time_throttle = time_throttle
176 self.predicate = predicate
177
178 def __call__(self, line):
179 # git uses an escape sequence to clear the line; elide it.
180 esc = line.find(unichr(033))
181 if esc > -1:
182 line = line[:esc]
183 if self.predicate and not self.predicate(line):
184 return
185 now = time.time()
186 match = self.PERCENT_RE.match(line)
187 if not match:
188 self.last_time = 0
189 if (now - self.last_time) >= self.time_throttle:
190 self.last_time = now
191 print line
192
193
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000194class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000195 """Wrapper for Git"""
196
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000197 cache_dir = None
198 # If a given cache is used in a solution more than once, prevent multiple
199 # threads from updating it simultaneously.
200 cache_locks = collections.defaultdict(threading.Lock)
201
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000202 def __init__(self, url=None, root_dir=None, relpath=None):
203 """Removes 'git+' fake prefix from git URL."""
204 if url.startswith('git+http://') or url.startswith('git+https://'):
205 url = url[4:]
206 SCMWrapper.__init__(self, url, root_dir, relpath)
207
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000208 @staticmethod
209 def BinaryExists():
210 """Returns true if the command exists."""
211 try:
212 # We assume git is newer than 1.7. See: crbug.com/114483
213 result, version = scm.GIT.AssertVersion('1.7')
214 if not result:
215 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
216 return result
217 except OSError:
218 return False
219
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000220 def GetCheckoutRoot(self):
221 return scm.GIT.GetCheckoutRoot(self.checkout_path)
222
floitsch@google.comeaab7842011-04-28 09:07:58 +0000223 def GetRevisionDate(self, revision):
224 """Returns the given revision's date in ISO-8601 format (which contains the
225 time zone)."""
226 # TODO(floitsch): get the time-stamp of the given revision and not just the
227 # time-stamp of the currently checked out revision.
228 return self._Capture(['log', '-n', '1', '--format=%ai'])
229
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000230 @staticmethod
231 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000232 """'Cleanup' the repo.
233
234 There's no real git equivalent for the svn cleanup command, do a no-op.
235 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000236
237 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000238 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000239 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000240
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000241 def pack(self, options, args, file_list):
242 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000243 repository.
244
245 The patch file is generated from a diff of the merge base of HEAD and
246 its upstream branch.
247 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000248 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000249 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000250 ['git', 'diff', merge_base],
251 cwd=self.checkout_path,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000252 nag_timer=self.nag_timer,
253 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000254 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000255
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000256 def UpdateSubmoduleConfig(self):
257 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
258 'submodule.$name.ignore', '||',
259 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000260 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000261 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000262 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000263 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000264 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000265 kwargs = {'cwd': self.checkout_path,
266 'print_stdout': False,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000267 'nag_timer': self.nag_timer,
268 'nag_max': self.nag_max,
szager@chromium.org987b0612012-07-09 23:41:08 +0000269 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000270 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000271 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
272 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000273 except subprocess2.CalledProcessError:
274 # Not a fatal error, or even very interesting in a non-git-submodule
275 # world. So just keep it quiet.
276 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000277 try:
278 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
279 except subprocess2.CalledProcessError:
280 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000281
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000282 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
283
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000284 def _FetchAndReset(self, revision, file_list, options):
285 """Equivalent to git fetch; git reset."""
286 quiet = []
287 if not options.verbose:
288 quiet = ['--quiet']
289 self._UpdateBranchHeads(options, fetch=False)
iannucci@chromium.orgb8376882013-07-01 20:08:10 +0000290
291 fetch_cmd = [
292 '-c', 'core.deltaBaseCacheLimit=2g', 'fetch', 'origin', '--prune']
293 self._Run(fetch_cmd + quiet, options)
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000294 self._Run(['reset', '--hard', revision] + quiet, options)
295 self.UpdateSubmoduleConfig()
296 files = self._Capture(['ls-files']).splitlines()
297 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
298
msb@chromium.orge28e4982009-09-25 20:51:45 +0000299 def update(self, options, args, file_list):
300 """Runs git to update or transparently checkout the working copy.
301
302 All updated files will be appended to file_list.
303
304 Raises:
305 Error: if can't get URL for relative path.
306 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000307 if args:
308 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
309
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000310 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000311
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000312 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000313 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000314 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000315 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000316 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000317 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000318 # Override the revision number.
319 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000320 if revision == 'unmanaged':
321 revision = None
322 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000323 if not revision:
324 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000325
floitsch@google.comeaab7842011-04-28 09:07:58 +0000326 if gclient_utils.IsDateRevision(revision):
327 # Date-revisions only work on git-repositories if the reflog hasn't
328 # expired yet. Use rev-list to get the corresponding revision.
329 # git rev-list -n 1 --before='time-stamp' branchname
330 if options.transitive:
331 print('Warning: --transitive only works for SVN repositories.')
332 revision = default_rev
333
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000334 rev_str = ' at %s' % revision
335 files = []
336
337 printed_path = False
338 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000339 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000340 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000341 verbose = ['--verbose']
342 printed_path = True
343
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000344 url = self._CreateOrUpdateCache(url, options)
345
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000346 if revision.startswith('refs/'):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000347 rev_type = "branch"
348 elif revision.startswith('origin/'):
349 # For compatability with old naming, translate 'origin' to 'refs/heads'
350 revision = revision.replace('origin/', 'refs/heads/')
351 rev_type = "branch"
352 else:
353 # hash is also a tag, only make a distinction at checkout
354 rev_type = "hash"
355
szager@google.com873e6672012-03-13 18:53:36 +0000356 if not os.path.exists(self.checkout_path) or (
357 os.path.isdir(self.checkout_path) and
358 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000359 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000360 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000361 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000362 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000363 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000364 if not verbose:
365 # Make the output a little prettier. It's nice to have some whitespace
366 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000367 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000368 return
369
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000370 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000371 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000372 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000373 print ('________ unmanaged solution; skipping %s' % self.relpath)
374 return
375
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000376 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
377 raise gclient_utils.Error('\n____ %s%s\n'
378 '\tPath is not a git repo. No .git dir.\n'
379 '\tTo resolve:\n'
380 '\t\trm -rf %s\n'
381 '\tAnd run gclient sync again\n'
382 % (self.relpath, rev_str, self.relpath))
383
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000384 # See if the url has changed (the unittests use git://foo for the url, let
385 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000386 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000387 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
388 # unit test pass. (and update the comment above)
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000389 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
390 # This allows devs to use experimental repos which have a different url
391 # but whose branch(s) are the same as official repos.
392 if (current_url != url and
393 url != 'git://foo' and
394 subprocess2.capture(
395 ['git', 'config', 'remote.origin.gclient-auto-fix-url'],
396 cwd=self.checkout_path).strip() != 'False'):
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000397 print('_____ switching %s to a new upstream' % self.relpath)
398 # Make sure it's clean
399 self._CheckClean(rev_str)
400 # Switch over to the new upstream
401 self._Run(['remote', 'set-url', 'origin', url], options)
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000402 self._FetchAndReset(revision, file_list, options)
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000403 return
404
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000405 if not self._IsValidGitRepo():
406 # .git directory is hosed for some reason, set it back up.
407 print('_____ %s/.git is corrupted, rebuilding' % self.relpath)
408 self._Run(['init'], options)
409 self._Run(['remote', 'set-url', 'origin', url], options)
410
411 if not self._HasHead():
412 # Previous checkout was aborted before branches could be created in repo,
413 # so we need to reconstruct them here.
iannucci@chromium.orgb8376882013-07-01 20:08:10 +0000414 self._Run(['-c', 'core.deltaBaseCacheLimit=2g', 'pull', 'origin',
415 'master'], options)
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000416 self._FetchAndReset(revision, file_list, options)
417
msb@chromium.org5bde4852009-12-14 16:47:12 +0000418 cur_branch = self._GetCurrentBranch()
419
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000420 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000421 # 0) HEAD is detached. Probably from our initial clone.
422 # - make sure HEAD is contained by a named ref, then update.
423 # Cases 1-4. HEAD is a branch.
424 # 1) current branch is not tracking a remote branch (could be git-svn)
425 # - try to rebase onto the new hash or branch
426 # 2) current branch is tracking a remote branch with local committed
427 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000428 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000429 # 3) current branch is tracking a remote branch w/or w/out changes,
430 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000431 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000432 # 4) current branch is tracking a remote branch, switches to a different
433 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000434 # - exit
435
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000436 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
437 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000438 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
439 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000440 if cur_branch is None:
441 upstream_branch = None
442 current_type = "detached"
443 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000444 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000445 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
446 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
447 current_type = "hash"
448 logging.debug("Current branch is not tracking an upstream (remote)"
449 " branch.")
450 elif upstream_branch.startswith('refs/remotes'):
451 current_type = "branch"
452 else:
453 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000454
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000455 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000456 # Update the remotes first so we have all the refs.
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000457 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000458 cwd=self.checkout_path)
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000459 if verbose:
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000460 print(remote_output)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000461
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000462 self._UpdateBranchHeads(options, fetch=True)
463
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000464 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000465 if options.force or options.reset:
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000466 target = 'HEAD'
467 if options.upstream and upstream_branch:
468 target = upstream_branch
469 self._Run(['reset', '--hard', target], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470
msb@chromium.org786fb682010-06-02 15:16:23 +0000471 if current_type == 'detached':
472 # case 0
473 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000474 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000475 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000476 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000477 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000478 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000479 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000480 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000481 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000482 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 newbase=revision, printed_path=printed_path)
484 printed_path = True
485 else:
486 # Can't find a merge-base since we don't know our upstream. That makes
487 # this command VERY likely to produce a rebase failure. For now we
488 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000489 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000490 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000491 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000492 self._AttemptRebase(upstream_branch, files, options,
493 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000494 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000495 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000496 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000497 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000498 newbase=revision, printed_path=printed_path)
499 printed_path = True
500 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
501 # case 4
502 new_base = revision.replace('heads', 'remotes/origin')
503 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000504 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000505 switch_error = ("Switching upstream branch from %s to %s\n"
506 % (upstream_branch, new_base) +
507 "Please merge or rebase manually:\n" +
508 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
509 "OR git checkout -b <some new branch> %s" % new_base)
510 raise gclient_utils.Error(switch_error)
511 else:
512 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000513 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000514 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000515 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000516 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000517 merge_args = ['merge']
518 if not options.merge:
519 merge_args.append('--ff-only')
520 merge_args.append(upstream_branch)
521 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000522 except subprocess2.CalledProcessError as e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000523 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
524 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000525 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000526 printed_path = True
527 while True:
528 try:
maruel@chromium.org90541732011-04-01 17:54:18 +0000529 action = ask_for_data(
530 'Cannot fast-forward merge, attempt to rebase? '
bratell@opera.com18fa4542013-05-21 13:30:46 +0000531 '(y)es / (q)uit / (s)kip : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000532 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000533 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000534 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000535 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000536 printed_path=printed_path)
537 printed_path = True
538 break
539 elif re.match(r'quit|q', action, re.I):
540 raise gclient_utils.Error("Can't fast-forward, please merge or "
541 "rebase manually.\n"
542 "cd %s && git " % self.checkout_path
543 + "rebase %s" % upstream_branch)
544 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000545 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000546 return
547 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000548 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000549 elif re.match("error: Your local changes to '.*' would be "
550 "overwritten by merge. Aborting.\nPlease, commit your "
551 "changes or stash them before you can merge.\n",
552 e.stderr):
553 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000554 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000555 printed_path = True
556 raise gclient_utils.Error(e.stderr)
557 else:
558 # Some other problem happened with the merge
559 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000560 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000561 raise
562 else:
563 # Fast-forward merge was successful
564 if not re.match('Already up-to-date.', merge_output) or verbose:
565 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000566 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000567 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000568 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000569 if not verbose:
570 # Make the output a little prettier. It's nice to have some
571 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000572 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000573
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000574 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000575 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000576
577 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000578 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000579 raise gclient_utils.Error('\n____ %s%s\n'
580 '\nConflict while rebasing this branch.\n'
581 'Fix the conflict and run gclient again.\n'
582 'See man git-rebase for details.\n'
583 % (self.relpath, rev_str))
584
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000585 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000586 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000587
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000588 # If --reset and --delete_unversioned_trees are specified, remove any
589 # untracked directories.
590 if options.reset and options.delete_unversioned_trees:
591 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
592 # merge-base by default), so doesn't include untracked files. So we use
593 # 'git ls-files --directory --others --exclude-standard' here directly.
594 paths = scm.GIT.Capture(
595 ['ls-files', '--directory', '--others', '--exclude-standard'],
596 self.checkout_path)
597 for path in (p for p in paths.splitlines() if p.endswith('/')):
598 full_path = os.path.join(self.checkout_path, path)
599 if not os.path.islink(full_path):
600 print('\n_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000601 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000602
603
msb@chromium.orge28e4982009-09-25 20:51:45 +0000604 def revert(self, options, args, file_list):
605 """Reverts local modifications.
606
607 All reverted files will be appended to file_list.
608 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000609 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000610 # revert won't work if the directory doesn't exist. It needs to
611 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000612 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000613 # Don't reuse the args.
614 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000615
616 default_rev = "refs/heads/master"
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000617 if options.upstream:
618 if self._GetCurrentBranch():
619 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
620 default_rev = upstream_branch or default_rev
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000621 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000622 if not deps_revision:
623 deps_revision = default_rev
624 if deps_revision.startswith('refs/heads/'):
625 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
626
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000627 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000628 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000629 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000630 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
631
msb@chromium.org0f282062009-11-06 20:14:02 +0000632 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000633 """Returns revision"""
634 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000635
msb@chromium.orge28e4982009-09-25 20:51:45 +0000636 def runhooks(self, options, args, file_list):
637 self.status(options, args, file_list)
638
639 def status(self, options, args, file_list):
640 """Display status information."""
641 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000642 print(('\n________ couldn\'t run status in %s:\n'
643 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000644 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000645 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000646 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000647 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000648 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
649
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000650 def GetUsableRev(self, rev, options):
651 """Finds a useful revision for this repository.
652
653 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
654 will be called on the source."""
655 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000656 if not os.path.isdir(self.checkout_path):
657 raise gclient_utils.Error(
658 ( 'We could not find a valid hash for safesync_url response "%s".\n'
659 'Safesync URLs with a git checkout currently require the repo to\n'
660 'be cloned without a safesync_url before adding the safesync_url.\n'
661 'For more info, see: '
662 'http://code.google.com/p/chromium/wiki/UsingNewGit'
663 '#Initial_checkout' ) % rev)
664 elif rev.isdigit() and len(rev) < 7:
665 # Handles an SVN rev. As an optimization, only verify an SVN revision as
666 # [0-9]{1,6} for now to avoid making a network request.
667 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000668 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
669 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000670 try:
671 logging.debug('Looking for git-svn configuration optimizations.')
672 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
673 cwd=self.checkout_path):
674 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
675 except subprocess2.CalledProcessError:
676 logging.debug('git config --get svn-remote.svn.fetch failed, '
677 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000678 if options.verbose:
679 print('Running git svn fetch. This might take a while.\n')
680 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000681 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000682 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
683 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000684 except gclient_utils.Error, e:
685 sha1 = e.message
686 print('\nWarning: Could not find a git revision with accurate\n'
687 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
688 'the closest sane git revision, which is:\n'
689 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000690 if not sha1:
691 raise gclient_utils.Error(
692 ( 'It appears that either your git-svn remote is incorrectly\n'
693 'configured or the revision in your safesync_url is\n'
694 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
695 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000696 else:
697 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
698 sha1 = rev
699 else:
700 # May exist in origin, but we don't have it yet, so fetch and look
701 # again.
702 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
703 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
704 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000705
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000706 if not sha1:
707 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000708 ( 'We could not find a valid hash for safesync_url response "%s".\n'
709 'Safesync URLs with a git checkout currently require a git-svn\n'
710 'remote or a safesync_url that provides git sha1s. Please add a\n'
711 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000712 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000713 '#Initial_checkout' ) % rev)
714
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000715 return sha1
716
msb@chromium.orge6f78352010-01-13 17:05:33 +0000717 def FullUrlForRelativeUrl(self, url):
718 # Strip from last '/'
719 # Equivalent to unix basename
720 base_url = self.url
721 return base_url[:base_url.rfind('/')] + url
722
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000723 @staticmethod
724 def _NormalizeGitURL(url):
725 '''Takes a git url, strips the scheme, and ensures it ends with '.git'.'''
726 idx = url.find('://')
727 if idx != -1:
728 url = url[idx+3:]
729 if not url.endswith('.git'):
730 url += '.git'
731 return url
732
733 def _CreateOrUpdateCache(self, url, options):
734 """Make a new git mirror or update existing mirror for |url|, and return the
735 mirror URI to clone from.
736
737 If no cache-dir is specified, just return |url| unchanged.
738 """
739 if not self.cache_dir:
740 return url
741
742 # Replace - with -- to avoid ambiguity. / with - to flatten folder structure
743 folder = os.path.join(
744 self.cache_dir,
745 self._NormalizeGitURL(url).replace('-', '--').replace('/', '-'))
746
747 v = ['-v'] if options.verbose else []
748 filter_fn = lambda l: '[up to date]' not in l
749 with self.cache_locks[folder]:
750 gclient_utils.safe_makedirs(self.cache_dir)
751 if not os.path.exists(os.path.join(folder, 'config')):
752 gclient_utils.rmtree(folder)
753 self._Run(['clone'] + v + ['-c', 'core.deltaBaseCacheLimit=2g',
754 '--progress', '--mirror', url, folder],
755 options, git_filter=True, filter_fn=filter_fn,
756 cwd=self.cache_dir)
757 else:
758 # For now, assert that host/path/to/repo.git is identical. We may want
759 # to relax this restriction in the future to allow for smarter cache
760 # repo update schemes (such as pulling the same repo, but from a
761 # different host).
762 existing_url = self._Capture(['config', 'remote.origin.url'],
763 cwd=folder)
764 assert self._NormalizeGitURL(existing_url) == self._NormalizeGitURL(url)
765
766 # Would normally use `git remote update`, but it doesn't support
767 # --progress, so use fetch instead.
768 self._Run(['fetch'] + v + ['--multiple', '--progress', '--all'],
769 options, git_filter=True, filter_fn=filter_fn, cwd=folder)
770 return folder
771
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000772 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000773 """Clone a git repository from the given URL.
774
msb@chromium.org786fb682010-06-02 15:16:23 +0000775 Once we've cloned the repo, we checkout a working branch if the specified
776 revision is a branch head. If it is a tag or a specific commit, then we
777 leave HEAD detached as it makes future updates simpler -- in this case the
778 user should first create a new branch or switch to an existing branch before
779 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000780 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000781 # git clone doesn't seem to insert a newline properly before printing
782 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000783 print('')
iannucci@chromium.orgb8376882013-07-01 20:08:10 +0000784 clone_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'clone', '--progress']
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000785 if self.cache_dir:
786 clone_cmd.append('--shared')
msb@chromium.org786fb682010-06-02 15:16:23 +0000787 if revision.startswith('refs/heads/'):
788 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
789 detach_head = False
790 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000791 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000792 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000793 clone_cmd.append('--verbose')
794 clone_cmd.extend([url, self.checkout_path])
795
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000796 # If the parent directory does not exist, Git clone on Windows will not
797 # create it, so we need to do it manually.
798 parent_dir = os.path.dirname(self.checkout_path)
799 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000800 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000801
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000802 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000803 try:
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000804 self._Run(clone_cmd, options, cwd=self._root_dir, git_filter=True)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000805 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000806 except subprocess2.CalledProcessError, e:
807 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000808 # We should check for "transfer closed with NNN bytes remaining to
809 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000810 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000811 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000812 print(str(e))
813 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000814 continue
815 raise e
816
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000817 # Update the "branch-heads" remote-tracking branches, since we might need it
818 # to checkout a specific revision below.
819 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org059cc452013-03-11 15:14:35 +0000820
msb@chromium.org786fb682010-06-02 15:16:23 +0000821 if detach_head:
822 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000823 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000824 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000825 ('Checked out %s to a detached HEAD. Before making any commits\n'
826 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
827 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
828 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000829
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000830 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000831 branch=None, printed_path=False):
832 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000833 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000834 revision = upstream
835 if newbase:
836 revision = newbase
837 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000838 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000839 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000840 printed_path = True
841 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000842 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000843
844 # Build the rebase command here using the args
845 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
846 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000847 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000848 rebase_cmd.append('--verbose')
849 if newbase:
850 rebase_cmd.extend(['--onto', newbase])
851 rebase_cmd.append(upstream)
852 if branch:
853 rebase_cmd.append(branch)
854
855 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000856 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000857 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000858 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
859 re.match(r'cannot rebase: your index contains uncommitted changes',
860 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000861 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000862 rebase_action = ask_for_data(
863 'Cannot rebase because of unstaged changes.\n'
864 '\'git reset --hard HEAD\' ?\n'
865 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000866 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000867 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000868 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000869 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000870 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000871 break
872 elif re.match(r'quit|q', rebase_action, re.I):
873 raise gclient_utils.Error("Please merge or rebase manually\n"
874 "cd %s && git " % self.checkout_path
875 + "%s" % ' '.join(rebase_cmd))
876 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000877 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000878 continue
879 else:
880 gclient_utils.Error("Input not recognized")
881 continue
882 elif re.search(r'^CONFLICT', e.stdout, re.M):
883 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
884 "Fix the conflict and run gclient again.\n"
885 "See 'man git-rebase' for details.\n")
886 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000887 print(e.stdout.strip())
888 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000889 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
890 "manually.\ncd %s && git " %
891 self.checkout_path
892 + "%s" % ' '.join(rebase_cmd))
893
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000894 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000895 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000896 # Make the output a little prettier. It's nice to have some
897 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000898 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000899
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000900 def _IsValidGitRepo(self):
901 """Returns if the directory is a valid git repository.
902
903 Checks if git status works.
904 """
905 try:
906 self._Capture(['status'])
907 return True
908 except subprocess2.CalledProcessError:
909 return False
910
911 def _HasHead(self):
912 """Returns True if any commit is checked out.
913
914 This is done by checking if rev-parse HEAD works in the current repository.
915 """
916 try:
917 self._GetCurrentBranch()
918 return True
919 except subprocess2.CalledProcessError:
920 return False
921
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000922 @staticmethod
923 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000924 (ok, current_version) = scm.GIT.AssertVersion(min_version)
925 if not ok:
926 raise gclient_utils.Error('git version %s < minimum required %s' %
927 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000928
msb@chromium.org786fb682010-06-02 15:16:23 +0000929 def _IsRebasing(self):
930 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
931 # have a plumbing command to determine whether a rebase is in progress, so
932 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
933 g = os.path.join(self.checkout_path, '.git')
934 return (
935 os.path.isdir(os.path.join(g, "rebase-merge")) or
936 os.path.isdir(os.path.join(g, "rebase-apply")))
937
938 def _CheckClean(self, rev_str):
939 # Make sure the tree is clean; see git-rebase.sh for reference
940 try:
941 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000942 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000943 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000944 raise gclient_utils.Error('\n____ %s%s\n'
945 '\tYou have unstaged changes.\n'
946 '\tPlease commit, stash, or reset.\n'
947 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000948 try:
949 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000950 '--ignore-submodules', 'HEAD', '--'],
951 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000952 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000953 raise gclient_utils.Error('\n____ %s%s\n'
954 '\tYour index contains uncommitted changes\n'
955 '\tPlease commit, stash, or reset.\n'
956 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000957
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000958 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000959 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
960 # reference by a commit). If not, error out -- most likely a rebase is
961 # in progress, try to detect so we can give a better error.
962 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000963 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
964 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000965 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000966 # Commit is not contained by any rev. See if the user is rebasing:
967 if self._IsRebasing():
968 # Punt to the user
969 raise gclient_utils.Error('\n____ %s%s\n'
970 '\tAlready in a conflict, i.e. (no branch).\n'
971 '\tFix the conflict and run gclient again.\n'
972 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
973 '\tSee man git-rebase for details.\n'
974 % (self.relpath, rev_str))
975 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000976 name = ('saved-by-gclient-' +
977 self._Capture(['rev-parse', '--short', 'HEAD']))
978 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000979 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000980 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000981
msb@chromium.org5bde4852009-12-14 16:47:12 +0000982 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000983 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000984 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000985 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000986 return None
987 return branch
988
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000989 def _Capture(self, args, cwd=None):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000990 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000991 ['git'] + args,
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000992 stderr=subprocess2.VOID,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000993 nag_timer=self.nag_timer,
994 nag_max=self.nag_max,
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000995 cwd=cwd or self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000996
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000997 def _UpdateBranchHeads(self, options, fetch=False):
998 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
999 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
1000 backoff_time = 5
1001 for _ in range(3):
1002 try:
1003 config_cmd = ['config', 'remote.origin.fetch',
1004 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1005 '^\\+refs/branch-heads/\\*:.*$']
1006 self._Run(config_cmd, options)
1007 if fetch:
iannucci@chromium.orgb8376882013-07-01 20:08:10 +00001008 fetch_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'fetch', 'origin']
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001009 if options.verbose:
1010 fetch_cmd.append('--verbose')
1011 self._Run(fetch_cmd, options)
1012 break
1013 except subprocess2.CalledProcessError, e:
1014 print(str(e))
1015 print('Retrying in %.1f seconds...' % backoff_time)
1016 time.sleep(backoff_time)
1017 backoff_time *= 1.3
1018
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001019 def _Run(self, args, _options, git_filter=False, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001020 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.org12b07e72013-05-03 22:06:34 +00001021 kwargs.setdefault('nag_timer', self.nag_timer)
1022 kwargs.setdefault('nag_max', self.nag_max)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001023 if git_filter:
1024 kwargs['filter_fn'] = GitFilter(kwargs['nag_timer'] / 2,
1025 kwargs.get('filter_fn'))
1026 kwargs.setdefault('print_stdout', False)
1027 else:
1028 kwargs.setdefault('print_stdout', True)
szager@google.com85d3e3a2011-10-07 17:12:00 +00001029 stdout = kwargs.get('stdout', sys.stdout)
1030 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
1031 ' '.join(args), kwargs['cwd']))
1032 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +00001033
1034
maruel@chromium.org55e724e2010-03-11 19:36:49 +00001035class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001036 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001037
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +00001038 @staticmethod
1039 def BinaryExists():
1040 """Returns true if the command exists."""
1041 try:
1042 result, version = scm.SVN.AssertVersion('1.4')
1043 if not result:
1044 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1045 return result
1046 except OSError:
1047 return False
1048
xusydoc@chromium.org885a9602013-05-31 09:54:40 +00001049 def GetCheckoutRoot(self):
1050 return scm.SVN.GetCheckoutRoot(self.checkout_path)
1051
floitsch@google.comeaab7842011-04-28 09:07:58 +00001052 def GetRevisionDate(self, revision):
1053 """Returns the given revision's date in ISO-8601 format (which contains the
1054 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001055 date = scm.SVN.Capture(
1056 ['propget', '--revprop', 'svn:date', '-r', revision],
1057 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +00001058 return date.strip()
1059
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001060 def cleanup(self, options, args, file_list):
1061 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001062 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001063
1064 def diff(self, options, args, file_list):
1065 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001066 if not os.path.isdir(self.checkout_path):
1067 raise gclient_utils.Error('Directory %s is not present.' %
1068 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001069 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001070
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001071 def pack(self, options, args, file_list):
1072 """Generates a patch file which can be applied to the root of the
1073 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001074 if not os.path.isdir(self.checkout_path):
1075 raise gclient_utils.Error('Directory %s is not present.' %
1076 self.checkout_path)
1077 gclient_utils.CheckCallAndFilter(
1078 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1079 cwd=self.checkout_path,
1080 print_stdout=False,
szager@chromium.org12b07e72013-05-03 22:06:34 +00001081 nag_timer=self.nag_timer,
1082 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +00001083 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001084
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001085 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +00001086 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001087
1088 All updated files will be appended to file_list.
1089
1090 Raises:
1091 Error: if can't get URL for relative path.
1092 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +00001093 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001094 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001095 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001096 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001097 return
1098
morrita@chromium.org21dca0e2010-10-05 00:55:12 +00001099 hg_path = os.path.join(self.checkout_path, '.hg')
1100 if os.path.exists(hg_path):
1101 print('________ found .hg directory; skipping %s' % self.relpath)
1102 return
1103
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001104 if args:
1105 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1106
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001107 # revision is the revision to match. It is None if no revision is specified,
1108 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001109 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001110 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001111 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001112 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001113 if options.revision:
1114 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001115 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001116 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001117 if revision != 'unmanaged':
1118 forced_revision = True
1119 # Reconstruct the url.
1120 url = '%s@%s' % (url, revision)
1121 rev_str = ' at %s' % revision
1122 else:
1123 managed = False
1124 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001125 else:
1126 forced_revision = False
1127 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001128
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001129 # Get the existing scm url and the revision number of the current checkout.
1130 exists = os.path.exists(self.checkout_path)
1131 if exists and managed:
1132 try:
1133 from_info = scm.SVN.CaptureLocalInfo(
1134 [], os.path.join(self.checkout_path, '.'))
1135 except (gclient_utils.Error, subprocess2.CalledProcessError):
1136 if options.reset and options.delete_unversioned_trees:
1137 print 'Removing troublesome path %s' % self.checkout_path
1138 gclient_utils.rmtree(self.checkout_path)
1139 exists = False
1140 else:
1141 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1142 'present. Delete the directory and try again.')
1143 raise gclient_utils.Error(msg % self.checkout_path)
1144
1145 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001146 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001147 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001148 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001149 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001150 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001151 return
1152
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001153 if not managed:
1154 print ('________ unmanaged solution; skipping %s' % self.relpath)
1155 return
1156
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001157 if 'URL' not in from_info:
1158 raise gclient_utils.Error(
1159 ('gclient is confused. Couldn\'t get the url for %s.\n'
1160 'Try using @unmanaged.\n%s') % (
1161 self.checkout_path, from_info))
1162
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001163 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001164 dir_info = scm.SVN.CaptureStatus(
1165 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001166 if any(d[0][2] == 'L' for d in dir_info):
1167 try:
1168 self._Run(['cleanup', self.checkout_path], options)
1169 except subprocess2.CalledProcessError, e:
1170 # Get the status again, svn cleanup may have cleaned up at least
1171 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001172 dir_info = scm.SVN.CaptureStatus(
1173 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001174
1175 # Try to fix the failures by removing troublesome files.
1176 for d in dir_info:
1177 if d[0][2] == 'L':
1178 if d[0][0] == '!' and options.force:
1179 print 'Removing troublesome path %s' % d[1]
1180 gclient_utils.rmtree(d[1])
1181 else:
1182 print 'Not removing troublesome path %s automatically.' % d[1]
1183 if d[0][0] == '!':
1184 print 'You can pass --force to enable automatic removal.'
1185 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001186
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001187 # Retrieve the current HEAD version because svn is slow at null updates.
1188 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001189 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001190 revision = str(from_info_live['Revision'])
1191 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001192
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001193 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001194 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001195 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001196 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001197 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001198 # The url is invalid or the server is not accessible, it's safer to bail
1199 # out right now.
1200 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001201 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1202 and (from_info['UUID'] == to_info['UUID']))
1203 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001204 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001205 # We have different roots, so check if we can switch --relocate.
1206 # Subversion only permits this if the repository UUIDs match.
1207 # Perform the switch --relocate, then rewrite the from_url
1208 # to reflect where we "are now." (This is the same way that
1209 # Subversion itself handles the metadata when switch --relocate
1210 # is used.) This makes the checks below for whether we
1211 # can update to a revision or have to switch to a different
1212 # branch work as expected.
1213 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001214 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001215 from_info['Repository Root'],
1216 to_info['Repository Root'],
1217 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001218 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001219 from_info['URL'] = from_info['URL'].replace(
1220 from_info['Repository Root'],
1221 to_info['Repository Root'])
1222 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001223 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001224 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001225 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001226 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001227 raise gclient_utils.Error(
1228 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1229 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001230 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001231 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001232 print('\n_____ switching %s to a new checkout' % self.relpath)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001233 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001234 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001235 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001236 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001237 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001238 return
1239
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001240 # If the provided url has a revision number that matches the revision
1241 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001242 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001243 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001244 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001245 else:
1246 command = ['update', self.checkout_path]
1247 command = self._AddAdditionalUpdateFlags(command, options, revision)
1248 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001249
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001250 # If --reset and --delete_unversioned_trees are specified, remove any
1251 # untracked files and directories.
1252 if options.reset and options.delete_unversioned_trees:
1253 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1254 full_path = os.path.join(self.checkout_path, status[1])
1255 if (status[0][0] == '?'
1256 and os.path.isdir(full_path)
1257 and not os.path.islink(full_path)):
1258 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001259 gclient_utils.rmtree(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001260
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001261 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001262 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001263 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001264 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001265 # Create an empty checkout and then update the one file we want. Future
1266 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001267 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001268 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001269 if os.path.exists(os.path.join(self.checkout_path, filename)):
1270 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001271 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001272 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001273 # After the initial checkout, we can use update as if it were any other
1274 # dep.
1275 self.update(options, args, file_list)
1276 else:
1277 # If the installed version of SVN doesn't support --depth, fallback to
1278 # just exporting the file. This has the downside that revision
1279 # information is not stored next to the file, so we will have to
1280 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001281 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001282 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001283 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001284 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001285 command = self._AddAdditionalUpdateFlags(command, options,
1286 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001287 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001288
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001289 def revert(self, options, args, file_list):
1290 """Reverts local modifications. Subversion specific.
1291
1292 All reverted files will be appended to file_list, even if Subversion
1293 doesn't know about them.
1294 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001295 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001296 if os.path.exists(self.checkout_path):
1297 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001298 # svn revert won't work if the directory doesn't exist. It needs to
1299 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001300 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001301 # Don't reuse the args.
1302 return self.update(options, [], file_list)
1303
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001304 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1305 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1306 print('________ found .git directory; skipping %s' % self.relpath)
1307 return
1308 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1309 print('________ found .hg directory; skipping %s' % self.relpath)
1310 return
1311 if not options.force:
1312 raise gclient_utils.Error('Invalid checkout path, aborting')
1313 print(
1314 '\n_____ %s is not a valid svn checkout, synching instead' %
1315 self.relpath)
1316 gclient_utils.rmtree(self.checkout_path)
1317 # Don't reuse the args.
1318 return self.update(options, [], file_list)
1319
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001320 def printcb(file_status):
1321 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001322 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001323 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001324 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001325 print(os.path.join(self.checkout_path, file_status[1]))
1326 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001327
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001328 # Revert() may delete the directory altogether.
1329 if not os.path.isdir(self.checkout_path):
1330 # Don't reuse the args.
1331 return self.update(options, [], file_list)
1332
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001333 try:
1334 # svn revert is so broken we don't even use it. Using
1335 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001336 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001337 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1338 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001339 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001340 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001341 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001342
msb@chromium.org0f282062009-11-06 20:14:02 +00001343 def revinfo(self, options, args, file_list):
1344 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001345 try:
1346 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001347 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001348 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001349
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001350 def runhooks(self, options, args, file_list):
1351 self.status(options, args, file_list)
1352
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001353 def status(self, options, args, file_list):
1354 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001355 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001356 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001357 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001358 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1359 'The directory does not exist.') %
1360 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001361 # There's no file list to retrieve.
1362 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001363 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001364
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001365 def GetUsableRev(self, rev, options):
1366 """Verifies the validity of the revision for this repository."""
1367 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1368 raise gclient_utils.Error(
1369 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1370 'correct.') % rev)
1371 return rev
1372
msb@chromium.orge6f78352010-01-13 17:05:33 +00001373 def FullUrlForRelativeUrl(self, url):
1374 # Find the forth '/' and strip from there. A bit hackish.
1375 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001376
maruel@chromium.org669600d2010-09-01 19:06:31 +00001377 def _Run(self, args, options, **kwargs):
1378 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001379 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.org12b07e72013-05-03 22:06:34 +00001380 kwargs.setdefault('nag_timer', self.nag_timer)
1381 kwargs.setdefault('nag_max', self.nag_max)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001382 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001383 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001384
1385 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1386 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001387 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001388 scm.SVN.RunAndGetFileList(
1389 options.verbose,
1390 args + ['--ignore-externals'],
1391 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001392 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001393
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001394 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001395 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001396 """Add additional flags to command depending on what options are set.
1397 command should be a list of strings that represents an svn command.
1398
1399 This method returns a new list to be used as a command."""
1400 new_command = command[:]
1401 if revision:
1402 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001403 # We don't want interaction when jobs are used.
1404 if options.jobs > 1:
1405 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001406 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001407 # --accept was added to 'svn update' in svn 1.6.
1408 if not scm.SVN.AssertVersion('1.5')[0]:
1409 return new_command
1410
1411 # It's annoying to have it block in the middle of a sync, just sensible
1412 # defaults.
1413 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001414 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001415 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1416 new_command.extend(('--accept', 'theirs-conflict'))
1417 elif options.manually_grab_svn_rev:
1418 new_command.append('--force')
1419 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1420 new_command.extend(('--accept', 'postpone'))
1421 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1422 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001423 return new_command