blob: 42b8142d19a76313fbe5ee75a957e75e853fa59b [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
ilevy@chromium.org3534aa52013-07-20 01:58:08 +000013import tempfile
iannucci@chromium.org53456aa2013-07-03 19:38:34 +000014import threading
maruel@chromium.orgfd876172010-04-30 14:01:05 +000015import time
hinoka@google.com2f2ca142014-01-07 03:59:18 +000016import urlparse
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000017
hinoka@google.com2f2ca142014-01-07 03:59:18 +000018import download_from_google_storage
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000019import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000020import scm
21import subprocess2
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000022
23
szager@chromium.org71cbb502013-04-19 23:30:15 +000024THIS_FILE_PATH = os.path.abspath(__file__)
25
hinoka@google.com2f2ca142014-01-07 03:59:18 +000026GSUTIL_DEFAULT_PATH = os.path.join(
27 os.path.dirname(os.path.abspath(__file__)),
28 'third_party', 'gsutil', 'gsutil')
29
szager@chromium.org71cbb502013-04-19 23:30:15 +000030
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000031class DiffFiltererWrapper(object):
32 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000033 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000034 working copy lines of the svn/git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000035 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000036 original_prefix = "--- "
37 working_prefix = "+++ "
38
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000039 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000040 # Note that we always use '/' as the path separator to be
41 # consistent with svn's cygwin-style output on Windows
42 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000043 self._current_file = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000044
maruel@chromium.org6e29d572010-06-04 17:32:20 +000045 def SetCurrentFile(self, current_file):
46 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000047
iannucci@chromium.org3830a672013-02-19 20:15:14 +000048 @property
49 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000050 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000051
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000052 def _Replace(self, line):
53 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000054
55 def Filter(self, line):
56 if (line.startswith(self.index_string)):
57 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000058 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000059 else:
60 if (line.startswith(self.original_prefix) or
61 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000062 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000063 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000064
65
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000066class SvnDiffFilterer(DiffFiltererWrapper):
67 index_string = "Index: "
68
69
70class GitDiffFilterer(DiffFiltererWrapper):
71 index_string = "diff --git "
72
73 def SetCurrentFile(self, current_file):
74 # Get filename by parsing "a/<filename> b/<filename>"
75 self._current_file = current_file[:(len(current_file)/2)][2:]
76
77 def _Replace(self, line):
78 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
79
80
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000081### SCM abstraction layer
82
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000083# Factory Method for SCM wrapper creation
84
maruel@chromium.org9eda4112010-06-11 18:56:10 +000085def GetScmName(url):
86 if url:
87 url, _ = gclient_utils.SplitUrlRevision(url)
88 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000089 url.startswith('git+http://') or url.startswith('git+https://') or
mariakhomenko@chromium.orga2ede5c2014-02-05 22:05:17 +000090 url.endswith('.git') or url.startswith('sso://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000091 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000092 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000093 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000094 return 'svn'
95 return None
96
97
98def CreateSCM(url, root_dir=None, relpath=None):
99 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000100 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +0000101 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000102 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000103
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000104 scm_name = GetScmName(url)
105 if not scm_name in SCM_MAP:
106 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000107 scm_class = SCM_MAP[scm_name]
108 if not scm_class.BinaryExists():
109 raise gclient_utils.Error('%s command not found' % scm_name)
110 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000111
112
113# SCMWrapper base class
114
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000115class SCMWrapper(object):
116 """Add necessary glue between all the supported SCM.
117
msb@chromium.orgd6504212010-01-13 17:34:31 +0000118 This is the abstraction layer to bind to different SCM.
119 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000120 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000121 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000122 self._root_dir = root_dir
123 if self._root_dir:
124 self._root_dir = self._root_dir.replace('/', os.sep)
125 self.relpath = relpath
126 if self.relpath:
127 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000128 if self.relpath and self._root_dir:
129 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000130
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000131 def RunCommand(self, command, options, args, file_list=None):
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000132 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000133 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000134
135 if not command in commands:
136 raise gclient_utils.Error('Unknown command %s' % command)
137
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000138 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000139 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000140 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000141
142 return getattr(self, command)(options, args, file_list)
143
144
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000145class GitFilter(object):
146 """A filter_fn implementation for quieting down git output messages.
147
148 Allows a custom function to skip certain lines (predicate), and will throttle
149 the output of percentage completed lines to only output every X seconds.
150 """
151 PERCENT_RE = re.compile('.* ([0-9]{1,2})% .*')
152
153 def __init__(self, time_throttle=0, predicate=None):
154 """
155 Args:
156 time_throttle (int): GitFilter will throttle 'noisy' output (such as the
157 XX% complete messages) to only be printed at least |time_throttle|
158 seconds apart.
159 predicate (f(line)): An optional function which is invoked for every line.
160 The line will be skipped if predicate(line) returns False.
161 """
162 self.last_time = 0
163 self.time_throttle = time_throttle
164 self.predicate = predicate
165
166 def __call__(self, line):
167 # git uses an escape sequence to clear the line; elide it.
168 esc = line.find(unichr(033))
169 if esc > -1:
170 line = line[:esc]
171 if self.predicate and not self.predicate(line):
172 return
173 now = time.time()
174 match = self.PERCENT_RE.match(line)
175 if not match:
176 self.last_time = 0
177 if (now - self.last_time) >= self.time_throttle:
178 self.last_time = now
179 print line
180
181
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000182class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000183 """Wrapper for Git"""
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000184 name = 'git'
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000185 remote = 'origin'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000186
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000187 cache_dir = None
188 # If a given cache is used in a solution more than once, prevent multiple
189 # threads from updating it simultaneously.
190 cache_locks = collections.defaultdict(threading.Lock)
191
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000192 def __init__(self, url=None, root_dir=None, relpath=None):
193 """Removes 'git+' fake prefix from git URL."""
194 if url.startswith('git+http://') or url.startswith('git+https://'):
195 url = url[4:]
196 SCMWrapper.__init__(self, url, root_dir, relpath)
197
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000198 @staticmethod
199 def BinaryExists():
200 """Returns true if the command exists."""
201 try:
202 # We assume git is newer than 1.7. See: crbug.com/114483
203 result, version = scm.GIT.AssertVersion('1.7')
204 if not result:
205 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
206 return result
207 except OSError:
208 return False
209
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000210 def GetCheckoutRoot(self):
211 return scm.GIT.GetCheckoutRoot(self.checkout_path)
212
borenet@google.com8456c482014-02-05 22:30:40 +0000213 def GetRemoteURL(self, options, cwd=None):
214 try:
215 return self._Capture(['config', 'remote.%s.url' % self.remote],
216 cwd=cwd or self.checkout_path).rstrip()
217 except (OSError, subprocess2.CalledProcessError):
218 pass
219 try:
220 # This may occur if we have a git-svn checkout.
221 if scm.GIT.IsGitSvn(os.curdir):
222 return scm.GIT.Capture(['config', '--local', '--get',
223 'svn-remote.svn.url'], os.curdir).rstrip()
224 except (OSError, subprocess2.CalledProcessError):
225 pass
226 return None
227
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000228 def GetRevisionDate(self, _revision):
floitsch@google.comeaab7842011-04-28 09:07:58 +0000229 """Returns the given revision's date in ISO-8601 format (which contains the
230 time zone)."""
231 # TODO(floitsch): get the time-stamp of the given revision and not just the
232 # time-stamp of the currently checked out revision.
233 return self._Capture(['log', '-n', '1', '--format=%ai'])
234
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000235 @staticmethod
236 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000237 """'Cleanup' the repo.
238
239 There's no real git equivalent for the svn cleanup command, do a no-op.
240 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000241
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000242 def diff(self, options, _args, _file_list):
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000243 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000244 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000245
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000246 def pack(self, _options, _args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000247 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000248 repository.
249
250 The patch file is generated from a diff of the merge base of HEAD and
251 its upstream branch.
252 """
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000253 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000254 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000255 ['git', 'diff', merge_base],
256 cwd=self.checkout_path,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000257 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000258
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000259 def UpdateSubmoduleConfig(self):
260 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000261 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000262 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000263 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000264 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000265 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000266 kwargs = {'cwd': self.checkout_path,
267 'print_stdout': False,
268 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000269 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000270 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
271 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000272 except subprocess2.CalledProcessError:
273 # Not a fatal error, or even very interesting in a non-git-submodule
274 # world. So just keep it quiet.
275 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000276 try:
277 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
278 except subprocess2.CalledProcessError:
279 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000280
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000281 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
282
msb@chromium.orge28e4982009-09-25 20:51:45 +0000283 def update(self, options, args, file_list):
284 """Runs git to update or transparently checkout the working copy.
285
286 All updated files will be appended to file_list.
287
288 Raises:
289 Error: if can't get URL for relative path.
290 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000291 if args:
292 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
293
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000294 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000295
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000296 # If a dependency is not pinned, track the default remote branch.
297 default_rev = 'refs/remotes/%s/master' % self.remote
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000298 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000299 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000300 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000301 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000302 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000303 # Override the revision number.
304 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000305 if revision == 'unmanaged':
306 revision = None
307 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000308 if not revision:
309 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000310
floitsch@google.comeaab7842011-04-28 09:07:58 +0000311 if gclient_utils.IsDateRevision(revision):
312 # Date-revisions only work on git-repositories if the reflog hasn't
313 # expired yet. Use rev-list to get the corresponding revision.
314 # git rev-list -n 1 --before='time-stamp' branchname
315 if options.transitive:
316 print('Warning: --transitive only works for SVN repositories.')
317 revision = default_rev
318
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000319 rev_str = ' at %s' % revision
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000320 files = [] if file_list is not None else None
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000321
322 printed_path = False
323 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000324 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000325 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000326 verbose = ['--verbose']
327 printed_path = True
328
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000329 url = self._CreateOrUpdateCache(url, options)
330
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000331 if revision.startswith('refs/'):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000332 rev_type = "branch"
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000333 elif revision.startswith(self.remote + '/'):
334 # For compatibility with old naming, translate 'origin' to 'refs/heads'
335 revision = revision.replace(self.remote + '/', 'refs/heads/')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000336 rev_type = "branch"
337 else:
338 # hash is also a tag, only make a distinction at checkout
339 rev_type = "hash"
340
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000341 if (not os.path.exists(self.checkout_path) or
342 (os.path.isdir(self.checkout_path) and
343 not os.path.exists(os.path.join(self.checkout_path, '.git')))):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000344 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000345 self.UpdateSubmoduleConfig()
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000346 if file_list is not None:
347 files = self._Capture(['ls-files']).splitlines()
348 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000349 if not verbose:
350 # Make the output a little prettier. It's nice to have some whitespace
351 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000352 print('')
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000353 return self._Capture(['rev-parse', '--verify', 'HEAD'])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000354
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000355 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000356 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000357 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000358 print ('________ unmanaged solution; skipping %s' % self.relpath)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000359 return self._Capture(['rev-parse', '--verify', 'HEAD'])
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000360
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000361 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
362 raise gclient_utils.Error('\n____ %s%s\n'
363 '\tPath is not a git repo. No .git dir.\n'
364 '\tTo resolve:\n'
365 '\t\trm -rf %s\n'
366 '\tAnd run gclient sync again\n'
367 % (self.relpath, rev_str, self.relpath))
368
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000369 # Need to do this in the normal path as well as in the post-remote-switch
370 # path.
371 self._PossiblySwitchCache(url, options)
372
msb@chromium.org5bde4852009-12-14 16:47:12 +0000373 cur_branch = self._GetCurrentBranch()
374
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000375 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000376 # 0) HEAD is detached. Probably from our initial clone.
377 # - make sure HEAD is contained by a named ref, then update.
378 # Cases 1-4. HEAD is a branch.
379 # 1) current branch is not tracking a remote branch (could be git-svn)
380 # - try to rebase onto the new hash or branch
381 # 2) current branch is tracking a remote branch with local committed
382 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000383 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000384 # 3) current branch is tracking a remote branch w/or w/out changes,
385 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000386 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000387 # 4) current branch is tracking a remote branch, switches to a different
388 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000389 # - exit
390
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000391 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
392 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000393 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
394 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000395 if cur_branch is None:
396 upstream_branch = None
397 current_type = "detached"
398 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000399 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000400 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
401 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
402 current_type = "hash"
403 logging.debug("Current branch is not tracking an upstream (remote)"
404 " branch.")
405 elif upstream_branch.startswith('refs/remotes'):
406 current_type = "branch"
407 else:
408 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000409
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000410 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000411 # Update the remotes first so we have all the refs.
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000412 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000413 cwd=self.checkout_path)
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000414 if verbose:
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000415 print(remote_output)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000416
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000417 self._UpdateBranchHeads(options, fetch=True)
418
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000419 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000420 if options.force or options.reset:
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000421 target = 'HEAD'
422 if options.upstream and upstream_branch:
423 target = upstream_branch
424 self._Run(['reset', '--hard', target], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000425
msb@chromium.org786fb682010-06-02 15:16:23 +0000426 if current_type == 'detached':
427 # case 0
428 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000429 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000430 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000431 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000432 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000433 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000434 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000435 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000436 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000437 self._AttemptRebase(upstream_branch, files, options,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000438 newbase=revision, printed_path=printed_path,
439 merge=options.merge)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000440 printed_path = True
441 else:
442 # Can't find a merge-base since we don't know our upstream. That makes
443 # this command VERY likely to produce a rebase failure. For now we
444 # assume origin is our upstream since that's what the old behavior was.
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000445 upstream_branch = self.remote
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000446 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000447 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000448 self._AttemptRebase(upstream_branch, files, options,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000449 printed_path=printed_path, merge=options.merge)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000450 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000451 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000452 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000453 self._AttemptRebase(upstream_branch, files, options,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000454 newbase=revision, printed_path=printed_path,
455 merge=options.merge)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000456 printed_path = True
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000457 elif revision.replace('heads', 'remotes/' + self.remote) != upstream_branch:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000458 # case 4
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000459 new_base = revision.replace('heads', 'remotes/' + self.remote)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000460 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000461 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000462 switch_error = ("Switching upstream branch from %s to %s\n"
463 % (upstream_branch, new_base) +
464 "Please merge or rebase manually:\n" +
465 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
466 "OR git checkout -b <some new branch> %s" % new_base)
467 raise gclient_utils.Error(switch_error)
468 else:
469 # case 3 - the default case
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000470 if files is not None:
471 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000472 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000473 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000474 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000475 merge_args = ['merge']
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000476 if options.merge:
477 merge_args.append('--ff')
478 else:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000479 merge_args.append('--ff-only')
480 merge_args.append(upstream_branch)
481 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000482 except subprocess2.CalledProcessError as e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000484 files = []
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000485 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000486 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000487 printed_path = True
488 while True:
489 try:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000490 action = self._AskForData(
491 'Cannot %s, attempt to rebase? '
492 '(y)es / (q)uit / (s)kip : ' %
493 ('merge' if options.merge else 'fast-forward merge'),
494 options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000495 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000496 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000497 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000498 self._AttemptRebase(upstream_branch, files, options,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000499 printed_path=printed_path, merge=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000500 printed_path = True
501 break
502 elif re.match(r'quit|q', action, re.I):
503 raise gclient_utils.Error("Can't fast-forward, please merge or "
504 "rebase manually.\n"
505 "cd %s && git " % self.checkout_path
506 + "rebase %s" % upstream_branch)
507 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000508 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000509 return
510 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000511 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000512 elif re.match("error: Your local changes to '.*' would be "
513 "overwritten by merge. Aborting.\nPlease, commit your "
514 "changes or stash them before you can merge.\n",
515 e.stderr):
516 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000517 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000518 printed_path = True
519 raise gclient_utils.Error(e.stderr)
520 else:
521 # Some other problem happened with the merge
522 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000523 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000524 raise
525 else:
526 # Fast-forward merge was successful
527 if not re.match('Already up-to-date.', merge_output) or verbose:
528 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000529 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000530 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000531 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000532 if not verbose:
533 # Make the output a little prettier. It's nice to have some
534 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000535 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000536
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000537 self.UpdateSubmoduleConfig()
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000538 if file_list is not None:
539 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000540
541 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000542 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000543 raise gclient_utils.Error('\n____ %s%s\n'
544 '\nConflict while rebasing this branch.\n'
545 'Fix the conflict and run gclient again.\n'
546 'See man git-rebase for details.\n'
547 % (self.relpath, rev_str))
548
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000549 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000550 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000551
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000552 # If --reset and --delete_unversioned_trees are specified, remove any
553 # untracked directories.
554 if options.reset and options.delete_unversioned_trees:
555 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
556 # merge-base by default), so doesn't include untracked files. So we use
557 # 'git ls-files --directory --others --exclude-standard' here directly.
558 paths = scm.GIT.Capture(
559 ['ls-files', '--directory', '--others', '--exclude-standard'],
560 self.checkout_path)
561 for path in (p for p in paths.splitlines() if p.endswith('/')):
562 full_path = os.path.join(self.checkout_path, path)
563 if not os.path.islink(full_path):
564 print('\n_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000565 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000566
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000567 return self._Capture(['rev-parse', '--verify', 'HEAD'])
568
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000569
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000570 def revert(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000571 """Reverts local modifications.
572
573 All reverted files will be appended to file_list.
574 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000575 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000576 # revert won't work if the directory doesn't exist. It needs to
577 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000578 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000579 # Don't reuse the args.
580 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000581
582 default_rev = "refs/heads/master"
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000583 if options.upstream:
584 if self._GetCurrentBranch():
585 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
586 default_rev = upstream_branch or default_rev
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000587 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000588 if not deps_revision:
589 deps_revision = default_rev
590 if deps_revision.startswith('refs/heads/'):
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000591 deps_revision = deps_revision.replace('refs/heads/', self.remote + '/')
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000592
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000593 if file_list is not None:
594 files = self._Capture(['diff', deps_revision, '--name-only']).split()
595
maruel@chromium.org37e89872010-09-07 16:11:33 +0000596 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000597 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000598
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000599 if file_list is not None:
600 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
601
602 def revinfo(self, _options, _args, _file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000603 """Returns revision"""
604 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000605
msb@chromium.orge28e4982009-09-25 20:51:45 +0000606 def runhooks(self, options, args, file_list):
607 self.status(options, args, file_list)
608
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000609 def status(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000610 """Display status information."""
611 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000612 print(('\n________ couldn\'t run status in %s:\n'
613 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000614 else:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000615 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000616 self._Run(['diff', '--name-status', merge_base], options)
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000617 if file_list is not None:
618 files = self._Capture(['diff', '--name-only', merge_base]).split()
619 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000620
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000621 def GetUsableRev(self, rev, options):
622 """Finds a useful revision for this repository.
623
624 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
625 will be called on the source."""
626 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000627 if not os.path.isdir(self.checkout_path):
628 raise gclient_utils.Error(
629 ( 'We could not find a valid hash for safesync_url response "%s".\n'
630 'Safesync URLs with a git checkout currently require the repo to\n'
631 'be cloned without a safesync_url before adding the safesync_url.\n'
632 'For more info, see: '
633 'http://code.google.com/p/chromium/wiki/UsingNewGit'
634 '#Initial_checkout' ) % rev)
635 elif rev.isdigit() and len(rev) < 7:
636 # Handles an SVN rev. As an optimization, only verify an SVN revision as
637 # [0-9]{1,6} for now to avoid making a network request.
638 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000639 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
640 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000641 try:
642 logging.debug('Looking for git-svn configuration optimizations.')
643 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
644 cwd=self.checkout_path):
645 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
646 except subprocess2.CalledProcessError:
647 logging.debug('git config --get svn-remote.svn.fetch failed, '
648 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000649 if options.verbose:
650 print('Running git svn fetch. This might take a while.\n')
651 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000652 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000653 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
654 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000655 except gclient_utils.Error, e:
656 sha1 = e.message
657 print('\nWarning: Could not find a git revision with accurate\n'
658 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
659 'the closest sane git revision, which is:\n'
660 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000661 if not sha1:
662 raise gclient_utils.Error(
663 ( 'It appears that either your git-svn remote is incorrectly\n'
664 'configured or the revision in your safesync_url is\n'
665 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
666 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000667 else:
668 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
669 sha1 = rev
670 else:
671 # May exist in origin, but we don't have it yet, so fetch and look
672 # again.
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000673 scm.GIT.Capture(['fetch', self.remote], cwd=self.checkout_path)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000674 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
675 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000676
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000677 if not sha1:
678 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000679 ( 'We could not find a valid hash for safesync_url response "%s".\n'
680 'Safesync URLs with a git checkout currently require a git-svn\n'
681 'remote or a safesync_url that provides git sha1s. Please add a\n'
682 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000683 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000684 '#Initial_checkout' ) % rev)
685
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000686 return sha1
687
msb@chromium.orge6f78352010-01-13 17:05:33 +0000688 def FullUrlForRelativeUrl(self, url):
689 # Strip from last '/'
690 # Equivalent to unix basename
691 base_url = self.url
692 return base_url[:base_url.rfind('/')] + url
693
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000694 @staticmethod
695 def _NormalizeGitURL(url):
696 '''Takes a git url, strips the scheme, and ensures it ends with '.git'.'''
697 idx = url.find('://')
698 if idx != -1:
699 url = url[idx+3:]
700 if not url.endswith('.git'):
701 url += '.git'
702 return url
703
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000704 def _PossiblySwitchCache(self, url, options):
705 """Handles switching a repo from with-cache to direct, or vice versa.
706
707 When we go from direct to with-cache, the remote url changes from the
708 'real' url to the local file url (in cache_dir). Therefore, this function
709 assumes that |url| points to the correctly-switched-over local file url, if
710 we're in cache_mode.
711
712 When we go from with-cache to direct, assume that the normal url-switching
713 code already flipped the remote over, and we just need to repack and break
714 the dependency to the cache.
715 """
716
717 altfile = os.path.join(
718 self.checkout_path, '.git', 'objects', 'info', 'alternates')
719 if self.cache_dir:
720 if not os.path.exists(altfile):
721 try:
iannucci@chromium.org578e5e52013-07-18 20:55:16 +0000722 with open(altfile, 'w') as f:
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000723 f.write(os.path.join(url, 'objects'))
724 # pylint: disable=C0301
725 # This dance is necessary according to emperical evidence, also at:
726 # http://lists-archives.com/git/713652-retrospectively-add-alternates-to-a-repository.html
727 self._Run(['repack', '-ad'], options)
728 self._Run(['repack', '-adl'], options)
729 except Exception:
730 # If something goes wrong, try to remove the altfile so we'll go down
731 # this path again next time.
732 try:
733 os.remove(altfile)
iannucci@chromium.org578e5e52013-07-18 20:55:16 +0000734 except OSError as e:
735 print >> sys.stderr, "FAILED: os.remove('%s') -> %s" % (altfile, e)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000736 raise
737 else:
738 if os.path.exists(altfile):
739 self._Run(['repack', '-a'], options)
740 os.remove(altfile)
741
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000742 def _CreateOrUpdateCache(self, url, options):
743 """Make a new git mirror or update existing mirror for |url|, and return the
744 mirror URI to clone from.
745
746 If no cache-dir is specified, just return |url| unchanged.
747 """
748 if not self.cache_dir:
749 return url
750
751 # Replace - with -- to avoid ambiguity. / with - to flatten folder structure
752 folder = os.path.join(
753 self.cache_dir,
754 self._NormalizeGitURL(url).replace('-', '--').replace('/', '-'))
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000755 altfile = os.path.join(folder, 'objects', 'info', 'alternates')
756
757 # If we're bringing an old cache up to date or cloning a new cache, and the
758 # existing repo is currently a direct clone, use its objects to help out
759 # the fetch here.
760 checkout_objects = os.path.join(self.checkout_path, '.git', 'objects')
761 checkout_altfile = os.path.join(checkout_objects, 'info', 'alternates')
762 use_reference = (
763 os.path.exists(checkout_objects) and
764 not os.path.exists(checkout_altfile))
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000765
766 v = ['-v'] if options.verbose else []
767 filter_fn = lambda l: '[up to date]' not in l
768 with self.cache_locks[folder]:
769 gclient_utils.safe_makedirs(self.cache_dir)
770 if not os.path.exists(os.path.join(folder, 'config')):
771 gclient_utils.rmtree(folder)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000772 cmd = ['clone'] + v + ['-c', 'core.deltaBaseCacheLimit=2g',
773 '--progress', '--mirror']
774
775 if use_reference:
776 cmd += ['--reference', os.path.abspath(self.checkout_path)]
777
778 self._Run(cmd + [url, folder],
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000779 options, filter_fn=filter_fn, cwd=self.cache_dir, retry=True)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000780 else:
781 # For now, assert that host/path/to/repo.git is identical. We may want
782 # to relax this restriction in the future to allow for smarter cache
783 # repo update schemes (such as pulling the same repo, but from a
784 # different host).
borenet@google.com8456c482014-02-05 22:30:40 +0000785 existing_url = self.GetRemoteURL(options, cwd=folder)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000786 assert self._NormalizeGitURL(existing_url) == self._NormalizeGitURL(url)
787
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000788 if use_reference:
789 with open(altfile, 'w') as f:
790 f.write(os.path.abspath(checkout_objects))
791
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000792 # Would normally use `git remote update`, but it doesn't support
793 # --progress, so use fetch instead.
794 self._Run(['fetch'] + v + ['--multiple', '--progress', '--all'],
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000795 options, filter_fn=filter_fn, cwd=folder, retry=True)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000796
797 # If the clone has an object dependency on the existing repo, break it
798 # with repack and remove the linkage.
799 if os.path.exists(altfile):
800 self._Run(['repack', '-a'], options, cwd=folder)
801 os.remove(altfile)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000802 return folder
803
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000804 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000805 """Clone a git repository from the given URL.
806
msb@chromium.org786fb682010-06-02 15:16:23 +0000807 Once we've cloned the repo, we checkout a working branch if the specified
808 revision is a branch head. If it is a tag or a specific commit, then we
809 leave HEAD detached as it makes future updates simpler -- in this case the
810 user should first create a new branch or switch to an existing branch before
811 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000812 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000813 # git clone doesn't seem to insert a newline properly before printing
814 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000815 print('')
szager@chromium.orgecb75422013-07-12 21:57:33 +0000816 template_path = os.path.join(
817 os.path.dirname(THIS_FILE_PATH), 'git-templates')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000818 clone_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'clone', '--no-checkout',
819 '--progress', '--template=%s' % template_path]
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000820 if self.cache_dir:
821 clone_cmd.append('--shared')
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000822 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000823 clone_cmd.append('--verbose')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000824 clone_cmd.append(url)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000825 # If the parent directory does not exist, Git clone on Windows will not
826 # create it, so we need to do it manually.
827 parent_dir = os.path.dirname(self.checkout_path)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000828 gclient_utils.safe_makedirs(parent_dir)
829 tmp_dir = tempfile.mkdtemp(
830 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
831 dir=parent_dir)
832 try:
833 clone_cmd.append(tmp_dir)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000834 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000835 gclient_utils.safe_makedirs(self.checkout_path)
cyrille@nnamrak.orgef509e42013-09-20 13:19:08 +0000836 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
837 os.path.join(self.checkout_path, '.git'))
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000838 finally:
839 if os.listdir(tmp_dir):
840 print('\n_____ removing non-empty tmp dir %s' % tmp_dir)
841 gclient_utils.rmtree(tmp_dir)
842 if revision.startswith('refs/heads/'):
843 self._Run(
844 ['checkout', '--quiet', revision.replace('refs/heads/', '')], options)
845 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000846 # Squelch git's very verbose detached HEAD warning and use our own
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000847 self._Run(['checkout', '--quiet', revision], options)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000848 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000849 ('Checked out %s to a detached HEAD. Before making any commits\n'
850 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000851 'an existing branch or use \'git checkout %s -b <branch>\' to\n'
852 'create a new branch for your work.') % (revision, self.remote))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000853
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000854 @staticmethod
855 def _AskForData(prompt, options):
856 if options.jobs > 1:
857 raise gclient_utils.Error("Background task requires input. Rerun "
858 "gclient with --jobs=1 so that\n"
859 "interaction is possible.")
860 try:
861 return raw_input(prompt)
862 except KeyboardInterrupt:
863 # Hide the exception.
864 sys.exit(1)
865
866
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000867 def _AttemptRebase(self, upstream, files, options, newbase=None,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000868 branch=None, printed_path=False, merge=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000869 """Attempt to rebase onto either upstream or, if specified, newbase."""
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000870 if files is not None:
871 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000872 revision = upstream
873 if newbase:
874 revision = newbase
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000875 action = 'merge' if merge else 'rebase'
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000876 if not printed_path:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000877 print('\n_____ %s : Attempting %s onto %s...' % (
878 self.relpath, action, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000879 printed_path = True
880 else:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000881 print('Attempting %s onto %s...' % (action, revision))
882
883 if merge:
884 merge_output = self._Capture(['merge', revision])
885 if options.verbose:
886 print(merge_output)
887 return
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000888
889 # Build the rebase command here using the args
890 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
891 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000892 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000893 rebase_cmd.append('--verbose')
894 if newbase:
895 rebase_cmd.extend(['--onto', newbase])
896 rebase_cmd.append(upstream)
897 if branch:
898 rebase_cmd.append(branch)
899
900 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000901 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000902 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000903 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
904 re.match(r'cannot rebase: your index contains uncommitted changes',
905 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000906 while True:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000907 rebase_action = self._AskForData(
maruel@chromium.org90541732011-04-01 17:54:18 +0000908 'Cannot rebase because of unstaged changes.\n'
909 '\'git reset --hard HEAD\' ?\n'
910 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000911 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000912 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000913 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000914 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000915 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000916 break
917 elif re.match(r'quit|q', rebase_action, re.I):
918 raise gclient_utils.Error("Please merge or rebase manually\n"
919 "cd %s && git " % self.checkout_path
920 + "%s" % ' '.join(rebase_cmd))
921 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000922 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000923 continue
924 else:
925 gclient_utils.Error("Input not recognized")
926 continue
927 elif re.search(r'^CONFLICT', e.stdout, re.M):
928 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
929 "Fix the conflict and run gclient again.\n"
930 "See 'man git-rebase' for details.\n")
931 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000932 print(e.stdout.strip())
933 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000934 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
935 "manually.\ncd %s && git " %
936 self.checkout_path
937 + "%s" % ' '.join(rebase_cmd))
938
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000939 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000940 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000941 # Make the output a little prettier. It's nice to have some
942 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000943 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000944
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000945 @staticmethod
946 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000947 (ok, current_version) = scm.GIT.AssertVersion(min_version)
948 if not ok:
949 raise gclient_utils.Error('git version %s < minimum required %s' %
950 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000951
msb@chromium.org786fb682010-06-02 15:16:23 +0000952 def _IsRebasing(self):
953 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
954 # have a plumbing command to determine whether a rebase is in progress, so
955 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
956 g = os.path.join(self.checkout_path, '.git')
957 return (
958 os.path.isdir(os.path.join(g, "rebase-merge")) or
959 os.path.isdir(os.path.join(g, "rebase-apply")))
960
961 def _CheckClean(self, rev_str):
962 # Make sure the tree is clean; see git-rebase.sh for reference
963 try:
964 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000965 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000966 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000967 raise gclient_utils.Error('\n____ %s%s\n'
968 '\tYou have unstaged changes.\n'
969 '\tPlease commit, stash, or reset.\n'
970 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000971 try:
972 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000973 '--ignore-submodules', 'HEAD', '--'],
974 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000975 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000976 raise gclient_utils.Error('\n____ %s%s\n'
977 '\tYour index contains uncommitted changes\n'
978 '\tPlease commit, stash, or reset.\n'
979 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000980
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000981 def _CheckDetachedHead(self, rev_str, _options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000982 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
983 # reference by a commit). If not, error out -- most likely a rebase is
984 # in progress, try to detect so we can give a better error.
985 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000986 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
987 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000988 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000989 # Commit is not contained by any rev. See if the user is rebasing:
990 if self._IsRebasing():
991 # Punt to the user
992 raise gclient_utils.Error('\n____ %s%s\n'
993 '\tAlready in a conflict, i.e. (no branch).\n'
994 '\tFix the conflict and run gclient again.\n'
995 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
996 '\tSee man git-rebase for details.\n'
997 % (self.relpath, rev_str))
998 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000999 name = ('saved-by-gclient-' +
1000 self._Capture(['rev-parse', '--short', 'HEAD']))
mmoss@chromium.org77bd7362013-09-25 23:46:14 +00001001 self._Capture(['branch', '-f', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001002 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +00001003 name)
msb@chromium.org786fb682010-06-02 15:16:23 +00001004
msb@chromium.org5bde4852009-12-14 16:47:12 +00001005 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +00001006 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001007 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +00001008 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +00001009 return None
1010 return branch
1011
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001012 def _Capture(self, args, cwd=None):
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001013 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +00001014 ['git'] + args,
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +00001015 stderr=subprocess2.VOID,
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001016 cwd=cwd or self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001017
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001018 def _UpdateBranchHeads(self, options, fetch=False):
1019 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
1020 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +00001021 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +00001022 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1023 '^\\+refs/branch-heads/\\*:.*$']
1024 self._Run(config_cmd, options)
1025 if fetch:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +00001026 fetch_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'fetch', self.remote]
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +00001027 if options.verbose:
1028 fetch_cmd.append('--verbose')
1029 self._Run(fetch_cmd, options, retry=True)
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001030
agable@chromium.orgfd5b6382013-10-25 20:54:34 +00001031 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001032 kwargs.setdefault('cwd', self.checkout_path)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +00001033 git_filter = not options.verbose
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001034 if git_filter:
scottmg@chromium.orgf547c802013-09-27 17:55:26 +00001035 kwargs['filter_fn'] = GitFilter(kwargs.get('filter_fn'))
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001036 kwargs.setdefault('print_stdout', False)
szager@chromium.org7f834ad2013-07-10 00:22:17 +00001037 # Don't prompt for passwords; just fail quickly and noisily.
szager@chromium.org3ce41842013-07-11 17:38:57 +00001038 # By default, git will use an interactive terminal prompt when a username/
1039 # password is needed. That shouldn't happen in the chromium workflow,
1040 # and if it does, then gclient may hide the prompt in the midst of a flood
1041 # of terminal spew. The only indication that something has gone wrong
1042 # will be when gclient hangs unresponsively. Instead, we disable the
1043 # password prompt and simply allow git to fail noisily. The error
1044 # message produced by git will be copied to gclient's output.
szager@chromium.org7f834ad2013-07-10 00:22:17 +00001045 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
1046 env.setdefault('GIT_ASKPASS', 'true')
1047 env.setdefault('SSH_ASKPASS', 'true')
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001048 else:
1049 kwargs.setdefault('print_stdout', True)
szager@google.com85d3e3a2011-10-07 17:12:00 +00001050 stdout = kwargs.get('stdout', sys.stdout)
1051 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
1052 ' '.join(args), kwargs['cwd']))
1053 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +00001054
1055
maruel@chromium.org55e724e2010-03-11 19:36:49 +00001056class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001057 """ Wrapper for SVN """
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001058 name = 'svn'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001059
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +00001060 @staticmethod
1061 def BinaryExists():
1062 """Returns true if the command exists."""
1063 try:
1064 result, version = scm.SVN.AssertVersion('1.4')
1065 if not result:
1066 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1067 return result
1068 except OSError:
1069 return False
1070
xusydoc@chromium.org885a9602013-05-31 09:54:40 +00001071 def GetCheckoutRoot(self):
1072 return scm.SVN.GetCheckoutRoot(self.checkout_path)
1073
borenet@google.com8456c482014-02-05 22:30:40 +00001074 def GetRemoteURL(self, options):
1075 try:
1076 return scm.SVN.CaptureLocalInfo([os.curdir],
1077 self.checkout_path).get('URL')
1078 except (OSError, subprocess2.CalledProcessError):
1079 pass
1080 try:
1081 # This may occur if we have a git-svn checkout.
1082 if scm.GIT.IsGitSvn(os.curdir):
1083 return scm.GIT.Capture(['config', '--local', '--get',
1084 'svn-remote.svn.url'], os.curdir).rstrip()
1085 except (OSError, subprocess2.CalledProcessError):
1086 pass
1087 return None
1088
1089
floitsch@google.comeaab7842011-04-28 09:07:58 +00001090 def GetRevisionDate(self, revision):
1091 """Returns the given revision's date in ISO-8601 format (which contains the
1092 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001093 date = scm.SVN.Capture(
1094 ['propget', '--revprop', 'svn:date', '-r', revision],
1095 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +00001096 return date.strip()
1097
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001098 def cleanup(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001099 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001100 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001101
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001102 def diff(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001103 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001104 if not os.path.isdir(self.checkout_path):
1105 raise gclient_utils.Error('Directory %s is not present.' %
1106 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001107 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001108
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001109 def pack(self, _options, args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001110 """Generates a patch file which can be applied to the root of the
1111 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001112 if not os.path.isdir(self.checkout_path):
1113 raise gclient_utils.Error('Directory %s is not present.' %
1114 self.checkout_path)
1115 gclient_utils.CheckCallAndFilter(
1116 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1117 cwd=self.checkout_path,
1118 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +00001119 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001120
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001121 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +00001122 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001123
1124 All updated files will be appended to file_list.
1125
1126 Raises:
1127 Error: if can't get URL for relative path.
1128 """
borenet@google.com8456c482014-02-05 22:30:40 +00001129 exists = os.path.exists(self.checkout_path)
thakis@chromium.org0a0e3102014-01-17 16:57:09 +00001130
borenet@google.com8456c482014-02-05 22:30:40 +00001131 if exists and scm.GIT.IsGitSvn(self.checkout_path):
1132 print '________ %s looks like git-svn; skipping.' % self.relpath
thakis@chromium.org0a0e3102014-01-17 16:57:09 +00001133 return
1134
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001135 if args:
1136 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1137
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001138 # revision is the revision to match. It is None if no revision is specified,
1139 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001140 url, revision = gclient_utils.SplitUrlRevision(self.url)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001141 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001142 if options.revision:
1143 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001144 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001145 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001146 if revision != 'unmanaged':
1147 forced_revision = True
1148 # Reconstruct the url.
1149 url = '%s@%s' % (url, revision)
1150 rev_str = ' at %s' % revision
1151 else:
1152 managed = False
1153 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001154 else:
1155 forced_revision = False
1156 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001157
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001158 # Get the existing scm url and the revision number of the current checkout.
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001159 if exists and managed:
1160 try:
1161 from_info = scm.SVN.CaptureLocalInfo(
1162 [], os.path.join(self.checkout_path, '.'))
1163 except (gclient_utils.Error, subprocess2.CalledProcessError):
1164 if options.reset and options.delete_unversioned_trees:
1165 print 'Removing troublesome path %s' % self.checkout_path
1166 gclient_utils.rmtree(self.checkout_path)
1167 exists = False
1168 else:
1169 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1170 'present. Delete the directory and try again.')
1171 raise gclient_utils.Error(msg % self.checkout_path)
1172
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001173 BASE_URLS = {
1174 '/chrome/trunk/src': 'gs://chromium-svn-checkout/chrome/',
1175 '/blink/trunk': 'gs://chromium-svn-checkout/blink/',
1176 }
hinoka@google.comca35be32014-01-17 01:48:18 +00001177 WHITELISTED_ROOTS = [
1178 'svn://svn.chromium.org',
1179 'svn://svn-mirror.golo.chromium.org',
1180 ]
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001181 if not exists:
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001182 try:
1183 # Split out the revision number since it's not useful for us.
1184 base_path = urlparse.urlparse(url).path.split('@')[0]
hinoka@google.comca35be32014-01-17 01:48:18 +00001185 # Check to see if we're on a whitelisted root. We do this because
1186 # only some svn servers have matching UUIDs.
1187 local_parsed = urlparse.urlparse(url)
1188 local_root = '%s://%s' % (local_parsed.scheme, local_parsed.netloc)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001189 if ('CHROME_HEADLESS' in os.environ
1190 and sys.platform == 'linux2' # TODO(hinoka): Enable for win/mac.
hinoka@google.comca35be32014-01-17 01:48:18 +00001191 and base_path in BASE_URLS
1192 and local_root in WHITELISTED_ROOTS):
1193
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001194 # Use a tarball for initial sync if we are on a bot.
1195 # Get an unauthenticated gsutil instance.
1196 gsutil = download_from_google_storage.Gsutil(
1197 GSUTIL_DEFAULT_PATH, boto_path=os.devnull)
1198
1199 gs_path = BASE_URLS[base_path]
1200 _, out, _ = gsutil.check_call('ls', gs_path)
1201 # So that we can get the most recent revision.
1202 sorted_items = sorted(out.splitlines())
1203 latest_checkout = sorted_items[-1]
1204
1205 tempdir = tempfile.mkdtemp()
1206 print 'Downloading %s...' % latest_checkout
1207 code, out, err = gsutil.check_call('cp', latest_checkout, tempdir)
1208 if code:
1209 print '%s\n%s' % (out, err)
1210 raise Exception()
1211 filename = latest_checkout.split('/')[-1]
1212 tarball = os.path.join(tempdir, filename)
1213 print 'Unpacking into %s...' % self.checkout_path
1214 gclient_utils.safe_makedirs(self.checkout_path)
1215 # TODO(hinoka): Use 7z for windows.
1216 cmd = ['tar', '--extract', '--ungzip',
1217 '--directory', self.checkout_path,
1218 '--file', tarball]
1219 gclient_utils.CheckCallAndFilter(
1220 cmd, stdout=sys.stdout, print_stdout=True)
1221
1222 print 'Deleting temp file'
1223 gclient_utils.rmtree(tempdir)
1224
1225 # Rewrite the repository root to match.
1226 tarball_url = scm.SVN.CaptureLocalInfo(
1227 ['.'], self.checkout_path)['Repository Root']
1228 tarball_parsed = urlparse.urlparse(tarball_url)
1229 tarball_root = '%s://%s' % (tarball_parsed.scheme,
1230 tarball_parsed.netloc)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001231
1232 if tarball_root != local_root:
1233 print 'Switching repository root to %s' % local_root
1234 self._Run(['switch', '--relocate', tarball_root,
1235 local_root, self.checkout_path],
1236 options)
1237 except Exception as e:
1238 print 'We tried to get a source tarball but failed.'
1239 print 'Resuming normal operations.'
1240 print str(e)
1241
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001242 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001243 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001244 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001245 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001246 self._RunAndGetFileList(command, options, file_list, self._root_dir)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001247 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001248
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001249 if not managed:
1250 print ('________ unmanaged solution; skipping %s' % self.relpath)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001251 return self.Svnversion()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001252
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001253 if 'URL' not in from_info:
1254 raise gclient_utils.Error(
1255 ('gclient is confused. Couldn\'t get the url for %s.\n'
1256 'Try using @unmanaged.\n%s') % (
1257 self.checkout_path, from_info))
1258
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001259 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001260 dir_info = scm.SVN.CaptureStatus(
1261 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001262 if any(d[0][2] == 'L' for d in dir_info):
1263 try:
1264 self._Run(['cleanup', self.checkout_path], options)
1265 except subprocess2.CalledProcessError, e:
1266 # Get the status again, svn cleanup may have cleaned up at least
1267 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001268 dir_info = scm.SVN.CaptureStatus(
1269 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001270
1271 # Try to fix the failures by removing troublesome files.
1272 for d in dir_info:
1273 if d[0][2] == 'L':
1274 if d[0][0] == '!' and options.force:
kustermann@google.com1580d952013-08-19 07:31:40 +00001275 # We don't pass any files/directories to CaptureStatus and set
1276 # cwd=self.checkout_path, so we should get relative paths here.
1277 assert not os.path.isabs(d[1])
1278 path_to_remove = os.path.normpath(
1279 os.path.join(self.checkout_path, d[1]))
1280 print 'Removing troublesome path %s' % path_to_remove
1281 gclient_utils.rmtree(path_to_remove)
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001282 else:
1283 print 'Not removing troublesome path %s automatically.' % d[1]
1284 if d[0][0] == '!':
1285 print 'You can pass --force to enable automatic removal.'
1286 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001287
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001288 # Retrieve the current HEAD version because svn is slow at null updates.
1289 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001290 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001291 revision = str(from_info_live['Revision'])
1292 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001293
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001294 # If the provided url has a revision number that matches the revision
1295 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001296 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001297 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001298 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001299 else:
1300 command = ['update', self.checkout_path]
1301 command = self._AddAdditionalUpdateFlags(command, options, revision)
1302 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001303
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001304 # If --reset and --delete_unversioned_trees are specified, remove any
1305 # untracked files and directories.
1306 if options.reset and options.delete_unversioned_trees:
1307 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1308 full_path = os.path.join(self.checkout_path, status[1])
1309 if (status[0][0] == '?'
1310 and os.path.isdir(full_path)
1311 and not os.path.islink(full_path)):
1312 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001313 gclient_utils.rmtree(full_path)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001314 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001315
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001316 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001317 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001318 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001319 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001320 # Create an empty checkout and then update the one file we want. Future
1321 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001322 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001323 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001324 if os.path.exists(os.path.join(self.checkout_path, filename)):
1325 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001326 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001327 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001328 # After the initial checkout, we can use update as if it were any other
1329 # dep.
1330 self.update(options, args, file_list)
1331 else:
1332 # If the installed version of SVN doesn't support --depth, fallback to
1333 # just exporting the file. This has the downside that revision
1334 # information is not stored next to the file, so we will have to
1335 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001336 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001337 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001338 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001339 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001340 command = self._AddAdditionalUpdateFlags(command, options,
1341 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001342 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001343
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001344 def revert(self, options, _args, file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001345 """Reverts local modifications. Subversion specific.
1346
1347 All reverted files will be appended to file_list, even if Subversion
1348 doesn't know about them.
1349 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001350 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001351 if os.path.exists(self.checkout_path):
1352 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001353 # svn revert won't work if the directory doesn't exist. It needs to
1354 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001355 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001356 # Don't reuse the args.
1357 return self.update(options, [], file_list)
1358
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001359 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
borenet@google.com8456c482014-02-05 22:30:40 +00001360 if scm.GIT.IsGitSvn(self.checkout_path):
1361 print '________ %s looks like git-svn; skipping.' % self.relpath
thakis@chromium.org0a0e3102014-01-17 16:57:09 +00001362 return
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001363 if not options.force:
1364 raise gclient_utils.Error('Invalid checkout path, aborting')
1365 print(
1366 '\n_____ %s is not a valid svn checkout, synching instead' %
1367 self.relpath)
1368 gclient_utils.rmtree(self.checkout_path)
1369 # Don't reuse the args.
1370 return self.update(options, [], file_list)
1371
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001372 def printcb(file_status):
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001373 if file_list is not None:
1374 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001375 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001376 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001377 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001378 print(os.path.join(self.checkout_path, file_status[1]))
1379 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001380
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001381 # Revert() may delete the directory altogether.
1382 if not os.path.isdir(self.checkout_path):
1383 # Don't reuse the args.
1384 return self.update(options, [], file_list)
1385
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001386 try:
1387 # svn revert is so broken we don't even use it. Using
1388 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001389 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001390 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1391 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001392 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001393 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001394 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001395
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001396 def revinfo(self, _options, _args, _file_list):
msb@chromium.org0f282062009-11-06 20:14:02 +00001397 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001398 try:
1399 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001400 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001401 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001402
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001403 def runhooks(self, options, args, file_list):
1404 self.status(options, args, file_list)
1405
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001406 def status(self, options, args, file_list):
1407 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001408 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001409 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001410 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001411 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1412 'The directory does not exist.') %
1413 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001414 # There's no file list to retrieve.
1415 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001416 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001417
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001418 def GetUsableRev(self, rev, _options):
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001419 """Verifies the validity of the revision for this repository."""
1420 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1421 raise gclient_utils.Error(
1422 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1423 'correct.') % rev)
1424 return rev
1425
msb@chromium.orge6f78352010-01-13 17:05:33 +00001426 def FullUrlForRelativeUrl(self, url):
1427 # Find the forth '/' and strip from there. A bit hackish.
1428 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001429
maruel@chromium.org669600d2010-09-01 19:06:31 +00001430 def _Run(self, args, options, **kwargs):
1431 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001432 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001433 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001434 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001435
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001436 def Svnversion(self):
1437 """Runs the lowest checked out revision in the current project."""
1438 info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1439 return info['Revision']
1440
maruel@chromium.org669600d2010-09-01 19:06:31 +00001441 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1442 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001443 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001444 scm.SVN.RunAndGetFileList(
1445 options.verbose,
1446 args + ['--ignore-externals'],
1447 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001448 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001449
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001450 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001451 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001452 """Add additional flags to command depending on what options are set.
1453 command should be a list of strings that represents an svn command.
1454
1455 This method returns a new list to be used as a command."""
1456 new_command = command[:]
1457 if revision:
1458 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001459 # We don't want interaction when jobs are used.
1460 if options.jobs > 1:
1461 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001462 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001463 # --accept was added to 'svn update' in svn 1.6.
1464 if not scm.SVN.AssertVersion('1.5')[0]:
1465 return new_command
1466
1467 # It's annoying to have it block in the middle of a sync, just sensible
1468 # defaults.
1469 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001470 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001471 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1472 new_command.extend(('--accept', 'theirs-conflict'))
1473 elif options.manually_grab_svn_rev:
1474 new_command.append('--force')
1475 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1476 new_command.extend(('--accept', 'postpone'))
1477 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1478 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001479 return new_command