blob: 5ba1cd619c67ed17e75c45ff8b98462d86d036d0 [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
zty@chromium.org6279e8a2014-02-13 01:45:25 +000015import traceback
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
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000145class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000146 """Wrapper for Git"""
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000147 name = 'git'
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000148 remote = 'origin'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000149
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000150 cache_dir = None
151 # If a given cache is used in a solution more than once, prevent multiple
152 # threads from updating it simultaneously.
153 cache_locks = collections.defaultdict(threading.Lock)
154
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000155 def __init__(self, url=None, root_dir=None, relpath=None):
156 """Removes 'git+' fake prefix from git URL."""
157 if url.startswith('git+http://') or url.startswith('git+https://'):
158 url = url[4:]
159 SCMWrapper.__init__(self, url, root_dir, relpath)
160
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000161 @staticmethod
162 def BinaryExists():
163 """Returns true if the command exists."""
164 try:
165 # We assume git is newer than 1.7. See: crbug.com/114483
166 result, version = scm.GIT.AssertVersion('1.7')
167 if not result:
168 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
169 return result
170 except OSError:
171 return False
172
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000173 def GetCheckoutRoot(self):
174 return scm.GIT.GetCheckoutRoot(self.checkout_path)
175
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000176 def GetRevisionDate(self, _revision):
floitsch@google.comeaab7842011-04-28 09:07:58 +0000177 """Returns the given revision's date in ISO-8601 format (which contains the
178 time zone)."""
179 # TODO(floitsch): get the time-stamp of the given revision and not just the
180 # time-stamp of the currently checked out revision.
181 return self._Capture(['log', '-n', '1', '--format=%ai'])
182
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000183 @staticmethod
184 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000185 """'Cleanup' the repo.
186
187 There's no real git equivalent for the svn cleanup command, do a no-op.
188 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000189
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000190 def diff(self, options, _args, _file_list):
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000191 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000192 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000193
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000194 def pack(self, _options, _args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000195 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000196 repository.
197
198 The patch file is generated from a diff of the merge base of HEAD and
199 its upstream branch.
200 """
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000201 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000202 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000203 ['git', 'diff', merge_base],
204 cwd=self.checkout_path,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000205 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000206
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000207 def UpdateSubmoduleConfig(self):
208 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000209 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000210 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000211 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000212 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000213 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000214 kwargs = {'cwd': self.checkout_path,
215 'print_stdout': False,
216 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000217 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000218 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
219 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000220 except subprocess2.CalledProcessError:
221 # Not a fatal error, or even very interesting in a non-git-submodule
222 # world. So just keep it quiet.
223 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000224 try:
225 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
226 except subprocess2.CalledProcessError:
227 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000228
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000229 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
230
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000231 def _FetchAndReset(self, revision, file_list, options):
232 """Equivalent to git fetch; git reset."""
233 quiet = []
234 if not options.verbose:
235 quiet = ['--quiet']
236 self._UpdateBranchHeads(options, fetch=False)
237
238 fetch_cmd = [
239 '-c', 'core.deltaBaseCacheLimit=2g', 'fetch', self.remote, '--prune']
240 self._Run(fetch_cmd + quiet, options, retry=True)
241 self._Run(['reset', '--hard', revision] + quiet, options)
242 self.UpdateSubmoduleConfig()
243 if file_list is not None:
244 files = self._Capture(['ls-files']).splitlines()
245 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
246
msb@chromium.orge28e4982009-09-25 20:51:45 +0000247 def update(self, options, args, file_list):
248 """Runs git to update or transparently checkout the working copy.
249
250 All updated files will be appended to file_list.
251
252 Raises:
253 Error: if can't get URL for relative path.
254 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000255 if args:
256 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
257
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000258 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000259
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000260 # If a dependency is not pinned, track the default remote branch.
261 default_rev = 'refs/remotes/%s/master' % self.remote
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000262 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000263 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000264 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000265 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000266 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000267 # Override the revision number.
268 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000269 if revision == 'unmanaged':
270 revision = None
271 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000272 if not revision:
273 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000274
floitsch@google.comeaab7842011-04-28 09:07:58 +0000275 if gclient_utils.IsDateRevision(revision):
276 # Date-revisions only work on git-repositories if the reflog hasn't
277 # expired yet. Use rev-list to get the corresponding revision.
278 # git rev-list -n 1 --before='time-stamp' branchname
279 if options.transitive:
280 print('Warning: --transitive only works for SVN repositories.')
281 revision = default_rev
282
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000283 rev_str = ' at %s' % revision
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000284 files = [] if file_list is not None else None
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000285
286 printed_path = False
287 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000288 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000289 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000290 verbose = ['--verbose']
291 printed_path = True
292
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000293 url = self._CreateOrUpdateCache(url, options)
294
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000295 if revision.startswith('refs/'):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000296 rev_type = "branch"
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000297 elif revision.startswith(self.remote + '/'):
298 # For compatibility with old naming, translate 'origin' to 'refs/heads'
299 revision = revision.replace(self.remote + '/', 'refs/heads/')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000300 rev_type = "branch"
301 else:
302 # hash is also a tag, only make a distinction at checkout
303 rev_type = "hash"
304
borenet@google.com6ff54482014-02-26 23:09:33 +0000305 if not managed:
306 self._UpdateBranchHeads(options, fetch=False)
307 self.UpdateSubmoduleConfig()
308 print ('________ unmanaged solution; skipping %s' % self.relpath)
309 return self._Capture(['rev-parse', '--verify', 'HEAD'])
310
311 needs_delete = False
312 exists = os.path.exists(self.checkout_path)
313 if exists and not os.path.exists(os.path.join(self.checkout_path, '.git')):
314 needs_delete = True
315
316 # See if the url has changed (the unittests use git://foo for the url, let
317 # that through).
318 return_early = False
319 if exists and not needs_delete:
320 current_url = self._Capture(['config', 'remote.%s.url' % self.remote])
321 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
322 # unit test pass. (and update the comment above)
323 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
324 # This allows devs to use experimental repos which have a different url
325 # but whose branch(s) are the same as official repos.
326 if (current_url != url and url != 'git://foo'):
327 auto_fix = 'True'
328 try:
329 auto_fix = self._Capture(
330 ['config', 'remote.%s.gclient-auto-fix-url' % self.remote],
331 cwd=self.checkout_path).strip()
332 except subprocess2.CalledProcessError:
333 pass
334 if auto_fix in ('1', 'true', 'True', 'yes', 'Yes', 'y', 'Y'):
335 print('_____ switching %s to a new upstream' % self.relpath)
336 # Make sure it's clean
337 self._CheckClean(rev_str)
338 # Switch over to the new upstream
339 self._Run(['remote', 'set-url', self.remote, url], options)
340 self._FetchAndReset(revision, file_list, options)
341 return_early = True
342
343 if (needs_delete and
344 gclient_utils.enable_deletion_of_conflicting_checkouts()):
345 if options.force:
346 print('Conflicting directory found in %s. Removing.'
347 % self.checkout_path)
348 gclient_utils.rmtree(self.checkout_path)
349 else:
350 raise gclient_utils.Error('Conflicting directory found in %s. Please '
351 'delete it or run with --force.'
352 % self.checkout_path)
353
354 if not os.path.exists(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000355 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000356 self.UpdateSubmoduleConfig()
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000357 if file_list is not None:
358 files = self._Capture(['ls-files']).splitlines()
359 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000360 if not verbose:
361 # Make the output a little prettier. It's nice to have some whitespace
362 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000363 print('')
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000364 return self._Capture(['rev-parse', '--verify', 'HEAD'])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000365
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000366 # Need to do this in the normal path as well as in the post-remote-switch
367 # path.
368 self._PossiblySwitchCache(url, options)
369
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000370 if return_early:
371 return self._Capture(['rev-parse', '--verify', 'HEAD'])
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 + '/')
iannucci@chromium.org9a8b0662014-02-20 00:56:15 +0000592 deps_revision = self.GetUsableRev(deps_revision, options)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000593
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000594 if file_list is not None:
595 files = self._Capture(['diff', deps_revision, '--name-only']).split()
596
maruel@chromium.org37e89872010-09-07 16:11:33 +0000597 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000598 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000599
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000600 if file_list is not None:
601 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
602
603 def revinfo(self, _options, _args, _file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000604 """Returns revision"""
605 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000606
msb@chromium.orge28e4982009-09-25 20:51:45 +0000607 def runhooks(self, options, args, file_list):
608 self.status(options, args, file_list)
609
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000610 def status(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000611 """Display status information."""
612 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000613 print(('\n________ couldn\'t run status in %s:\n'
614 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000615 else:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000616 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000617 self._Run(['diff', '--name-status', merge_base], options)
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000618 if file_list is not None:
619 files = self._Capture(['diff', '--name-only', merge_base]).split()
620 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000621
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000622 def GetUsableRev(self, rev, options):
623 """Finds a useful revision for this repository.
624
625 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
626 will be called on the source."""
627 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000628 if not os.path.isdir(self.checkout_path):
629 raise gclient_utils.Error(
630 ( 'We could not find a valid hash for safesync_url response "%s".\n'
631 'Safesync URLs with a git checkout currently require the repo to\n'
632 'be cloned without a safesync_url before adding the safesync_url.\n'
633 'For more info, see: '
634 'http://code.google.com/p/chromium/wiki/UsingNewGit'
635 '#Initial_checkout' ) % rev)
636 elif rev.isdigit() and len(rev) < 7:
637 # Handles an SVN rev. As an optimization, only verify an SVN revision as
638 # [0-9]{1,6} for now to avoid making a network request.
borenet@google.com6ff54482014-02-26 23:09:33 +0000639 if scm.GIT.IsGitSvn(self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000640 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
641 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000642 try:
643 logging.debug('Looking for git-svn configuration optimizations.')
644 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
645 cwd=self.checkout_path):
646 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
647 except subprocess2.CalledProcessError:
648 logging.debug('git config --get svn-remote.svn.fetch failed, '
649 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000650 if options.verbose:
651 print('Running git svn fetch. This might take a while.\n')
652 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000653 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000654 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
655 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000656 except gclient_utils.Error, e:
657 sha1 = e.message
658 print('\nWarning: Could not find a git revision with accurate\n'
659 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
660 'the closest sane git revision, which is:\n'
661 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000662 if not sha1:
663 raise gclient_utils.Error(
664 ( 'It appears that either your git-svn remote is incorrectly\n'
665 'configured or the revision in your safesync_url is\n'
666 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
667 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000668 else:
669 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
670 sha1 = rev
671 else:
672 # May exist in origin, but we don't have it yet, so fetch and look
673 # again.
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000674 scm.GIT.Capture(['fetch', self.remote], cwd=self.checkout_path)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000675 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
676 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000677
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000678 if not sha1:
679 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000680 ( 'We could not find a valid hash for safesync_url response "%s".\n'
681 'Safesync URLs with a git checkout currently require a git-svn\n'
682 'remote or a safesync_url that provides git sha1s. Please add a\n'
683 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000684 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000685 '#Initial_checkout' ) % rev)
686
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000687 return sha1
688
msb@chromium.orge6f78352010-01-13 17:05:33 +0000689 def FullUrlForRelativeUrl(self, url):
690 # Strip from last '/'
691 # Equivalent to unix basename
692 base_url = self.url
693 return base_url[:base_url.rfind('/')] + url
694
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000695 @staticmethod
696 def _NormalizeGitURL(url):
697 '''Takes a git url, strips the scheme, and ensures it ends with '.git'.'''
698 idx = url.find('://')
699 if idx != -1:
700 url = url[idx+3:]
701 if not url.endswith('.git'):
702 url += '.git'
703 return url
704
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000705 def _PossiblySwitchCache(self, url, options):
706 """Handles switching a repo from with-cache to direct, or vice versa.
707
708 When we go from direct to with-cache, the remote url changes from the
709 'real' url to the local file url (in cache_dir). Therefore, this function
710 assumes that |url| points to the correctly-switched-over local file url, if
711 we're in cache_mode.
712
713 When we go from with-cache to direct, assume that the normal url-switching
714 code already flipped the remote over, and we just need to repack and break
715 the dependency to the cache.
716 """
717
718 altfile = os.path.join(
719 self.checkout_path, '.git', 'objects', 'info', 'alternates')
720 if self.cache_dir:
721 if not os.path.exists(altfile):
722 try:
iannucci@chromium.org578e5e52013-07-18 20:55:16 +0000723 with open(altfile, 'w') as f:
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000724 f.write(os.path.join(url, 'objects'))
725 # pylint: disable=C0301
726 # This dance is necessary according to emperical evidence, also at:
727 # http://lists-archives.com/git/713652-retrospectively-add-alternates-to-a-repository.html
728 self._Run(['repack', '-ad'], options)
729 self._Run(['repack', '-adl'], options)
730 except Exception:
731 # If something goes wrong, try to remove the altfile so we'll go down
732 # this path again next time.
733 try:
734 os.remove(altfile)
iannucci@chromium.org578e5e52013-07-18 20:55:16 +0000735 except OSError as e:
736 print >> sys.stderr, "FAILED: os.remove('%s') -> %s" % (altfile, e)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000737 raise
738 else:
739 if os.path.exists(altfile):
740 self._Run(['repack', '-a'], options)
741 os.remove(altfile)
742
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000743 def _CreateOrUpdateCache(self, url, options):
744 """Make a new git mirror or update existing mirror for |url|, and return the
745 mirror URI to clone from.
746
747 If no cache-dir is specified, just return |url| unchanged.
748 """
749 if not self.cache_dir:
750 return url
751
752 # Replace - with -- to avoid ambiguity. / with - to flatten folder structure
753 folder = os.path.join(
754 self.cache_dir,
755 self._NormalizeGitURL(url).replace('-', '--').replace('/', '-'))
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000756 altfile = os.path.join(folder, 'objects', 'info', 'alternates')
757
758 # If we're bringing an old cache up to date or cloning a new cache, and the
759 # existing repo is currently a direct clone, use its objects to help out
760 # the fetch here.
761 checkout_objects = os.path.join(self.checkout_path, '.git', 'objects')
762 checkout_altfile = os.path.join(checkout_objects, 'info', 'alternates')
763 use_reference = (
764 os.path.exists(checkout_objects) and
765 not os.path.exists(checkout_altfile))
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000766
767 v = ['-v'] if options.verbose else []
768 filter_fn = lambda l: '[up to date]' not in l
769 with self.cache_locks[folder]:
770 gclient_utils.safe_makedirs(self.cache_dir)
771 if not os.path.exists(os.path.join(folder, 'config')):
772 gclient_utils.rmtree(folder)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000773 cmd = ['clone'] + v + ['-c', 'core.deltaBaseCacheLimit=2g',
hinoka@google.com78d78f32014-02-11 23:25:31 +0000774 '--progress', '--bare']
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000775
776 if use_reference:
777 cmd += ['--reference', os.path.abspath(self.checkout_path)]
778
779 self._Run(cmd + [url, folder],
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000780 options, filter_fn=filter_fn, cwd=self.cache_dir, retry=True)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000781 else:
782 # For now, assert that host/path/to/repo.git is identical. We may want
783 # to relax this restriction in the future to allow for smarter cache
784 # repo update schemes (such as pulling the same repo, but from a
785 # different host).
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000786 existing_url = self._Capture(['config', 'remote.%s.url' % self.remote],
787 cwd=folder)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000788 assert self._NormalizeGitURL(existing_url) == self._NormalizeGitURL(url)
789
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000790 if use_reference:
791 with open(altfile, 'w') as f:
792 f.write(os.path.abspath(checkout_objects))
793
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000794 # Would normally use `git remote update`, but it doesn't support
795 # --progress, so use fetch instead.
796 self._Run(['fetch'] + v + ['--multiple', '--progress', '--all'],
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000797 options, filter_fn=filter_fn, cwd=folder, retry=True)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000798
799 # If the clone has an object dependency on the existing repo, break it
800 # with repack and remove the linkage.
801 if os.path.exists(altfile):
802 self._Run(['repack', '-a'], options, cwd=folder)
803 os.remove(altfile)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000804 return folder
805
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000806 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000807 """Clone a git repository from the given URL.
808
msb@chromium.org786fb682010-06-02 15:16:23 +0000809 Once we've cloned the repo, we checkout a working branch if the specified
810 revision is a branch head. If it is a tag or a specific commit, then we
811 leave HEAD detached as it makes future updates simpler -- in this case the
812 user should first create a new branch or switch to an existing branch before
813 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000814 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000815 # git clone doesn't seem to insert a newline properly before printing
816 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000817 print('')
szager@chromium.orgecb75422013-07-12 21:57:33 +0000818 template_path = os.path.join(
819 os.path.dirname(THIS_FILE_PATH), 'git-templates')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000820 clone_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'clone', '--no-checkout',
821 '--progress', '--template=%s' % template_path]
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000822 if self.cache_dir:
823 clone_cmd.append('--shared')
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000824 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000825 clone_cmd.append('--verbose')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000826 clone_cmd.append(url)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000827 # If the parent directory does not exist, Git clone on Windows will not
828 # create it, so we need to do it manually.
829 parent_dir = os.path.dirname(self.checkout_path)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000830 gclient_utils.safe_makedirs(parent_dir)
831 tmp_dir = tempfile.mkdtemp(
832 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
833 dir=parent_dir)
834 try:
835 clone_cmd.append(tmp_dir)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000836 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000837 gclient_utils.safe_makedirs(self.checkout_path)
cyrille@nnamrak.orgef509e42013-09-20 13:19:08 +0000838 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
839 os.path.join(self.checkout_path, '.git'))
zty@chromium.org6279e8a2014-02-13 01:45:25 +0000840 except:
841 traceback.print_exc(file=sys.stderr)
842 raise
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000843 finally:
844 if os.listdir(tmp_dir):
845 print('\n_____ removing non-empty tmp dir %s' % tmp_dir)
846 gclient_utils.rmtree(tmp_dir)
847 if revision.startswith('refs/heads/'):
848 self._Run(
849 ['checkout', '--quiet', revision.replace('refs/heads/', '')], options)
850 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000851 # Squelch git's very verbose detached HEAD warning and use our own
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000852 self._Run(['checkout', '--quiet', revision], options)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000853 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000854 ('Checked out %s to a detached HEAD. Before making any commits\n'
855 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000856 'an existing branch or use \'git checkout %s -b <branch>\' to\n'
857 'create a new branch for your work.') % (revision, self.remote))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000858
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000859 @staticmethod
860 def _AskForData(prompt, options):
861 if options.jobs > 1:
862 raise gclient_utils.Error("Background task requires input. Rerun "
863 "gclient with --jobs=1 so that\n"
864 "interaction is possible.")
865 try:
866 return raw_input(prompt)
867 except KeyboardInterrupt:
868 # Hide the exception.
869 sys.exit(1)
870
871
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000872 def _AttemptRebase(self, upstream, files, options, newbase=None,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000873 branch=None, printed_path=False, merge=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000874 """Attempt to rebase onto either upstream or, if specified, newbase."""
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000875 if files is not None:
876 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000877 revision = upstream
878 if newbase:
879 revision = newbase
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000880 action = 'merge' if merge else 'rebase'
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000881 if not printed_path:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000882 print('\n_____ %s : Attempting %s onto %s...' % (
883 self.relpath, action, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000884 printed_path = True
885 else:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000886 print('Attempting %s onto %s...' % (action, revision))
887
888 if merge:
889 merge_output = self._Capture(['merge', revision])
890 if options.verbose:
891 print(merge_output)
892 return
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000893
894 # Build the rebase command here using the args
895 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
896 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000897 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000898 rebase_cmd.append('--verbose')
899 if newbase:
900 rebase_cmd.extend(['--onto', newbase])
901 rebase_cmd.append(upstream)
902 if branch:
903 rebase_cmd.append(branch)
904
905 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000906 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000907 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000908 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
909 re.match(r'cannot rebase: your index contains uncommitted changes',
910 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000911 while True:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000912 rebase_action = self._AskForData(
maruel@chromium.org90541732011-04-01 17:54:18 +0000913 'Cannot rebase because of unstaged changes.\n'
914 '\'git reset --hard HEAD\' ?\n'
915 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000916 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000917 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000918 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000919 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000920 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000921 break
922 elif re.match(r'quit|q', rebase_action, re.I):
923 raise gclient_utils.Error("Please merge or rebase manually\n"
924 "cd %s && git " % self.checkout_path
925 + "%s" % ' '.join(rebase_cmd))
926 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000927 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000928 continue
929 else:
930 gclient_utils.Error("Input not recognized")
931 continue
932 elif re.search(r'^CONFLICT', e.stdout, re.M):
933 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
934 "Fix the conflict and run gclient again.\n"
935 "See 'man git-rebase' for details.\n")
936 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000937 print(e.stdout.strip())
938 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000939 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
940 "manually.\ncd %s && git " %
941 self.checkout_path
942 + "%s" % ' '.join(rebase_cmd))
943
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000944 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000945 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000946 # Make the output a little prettier. It's nice to have some
947 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000948 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000949
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000950 @staticmethod
951 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000952 (ok, current_version) = scm.GIT.AssertVersion(min_version)
953 if not ok:
954 raise gclient_utils.Error('git version %s < minimum required %s' %
955 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000956
msb@chromium.org786fb682010-06-02 15:16:23 +0000957 def _IsRebasing(self):
958 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
959 # have a plumbing command to determine whether a rebase is in progress, so
960 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
961 g = os.path.join(self.checkout_path, '.git')
962 return (
963 os.path.isdir(os.path.join(g, "rebase-merge")) or
964 os.path.isdir(os.path.join(g, "rebase-apply")))
965
966 def _CheckClean(self, rev_str):
967 # Make sure the tree is clean; see git-rebase.sh for reference
968 try:
969 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000970 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000971 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000972 raise gclient_utils.Error('\n____ %s%s\n'
973 '\tYou have unstaged changes.\n'
974 '\tPlease commit, stash, or reset.\n'
975 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000976 try:
977 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000978 '--ignore-submodules', 'HEAD', '--'],
979 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000980 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000981 raise gclient_utils.Error('\n____ %s%s\n'
982 '\tYour index contains uncommitted changes\n'
983 '\tPlease commit, stash, or reset.\n'
984 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000985
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000986 def _CheckDetachedHead(self, rev_str, _options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000987 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
988 # reference by a commit). If not, error out -- most likely a rebase is
989 # in progress, try to detect so we can give a better error.
990 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000991 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
992 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000993 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000994 # Commit is not contained by any rev. See if the user is rebasing:
995 if self._IsRebasing():
996 # Punt to the user
997 raise gclient_utils.Error('\n____ %s%s\n'
998 '\tAlready in a conflict, i.e. (no branch).\n'
999 '\tFix the conflict and run gclient again.\n'
1000 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
1001 '\tSee man git-rebase for details.\n'
1002 % (self.relpath, rev_str))
1003 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001004 name = ('saved-by-gclient-' +
1005 self._Capture(['rev-parse', '--short', 'HEAD']))
mmoss@chromium.org77bd7362013-09-25 23:46:14 +00001006 self._Capture(['branch', '-f', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001007 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +00001008 name)
msb@chromium.org786fb682010-06-02 15:16:23 +00001009
msb@chromium.org5bde4852009-12-14 16:47:12 +00001010 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +00001011 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001012 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +00001013 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +00001014 return None
1015 return branch
1016
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001017 def _Capture(self, args, cwd=None):
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001018 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +00001019 ['git'] + args,
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +00001020 stderr=subprocess2.VOID,
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001021 cwd=cwd or self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001022
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001023 def _UpdateBranchHeads(self, options, fetch=False):
1024 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
1025 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +00001026 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +00001027 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1028 '^\\+refs/branch-heads/\\*:.*$']
1029 self._Run(config_cmd, options)
1030 if fetch:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +00001031 fetch_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'fetch', self.remote]
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +00001032 if options.verbose:
1033 fetch_cmd.append('--verbose')
1034 self._Run(fetch_cmd, options, retry=True)
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001035
agable@chromium.orgfd5b6382013-10-25 20:54:34 +00001036 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001037 kwargs.setdefault('cwd', self.checkout_path)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +00001038 git_filter = not options.verbose
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001039 if git_filter:
agable@chromium.org5a306a22014-02-24 22:13:59 +00001040 kwargs['filter_fn'] = gclient_utils.GitFilter(kwargs.get('filter_fn'))
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001041 kwargs.setdefault('print_stdout', False)
szager@chromium.org7f834ad2013-07-10 00:22:17 +00001042 # Don't prompt for passwords; just fail quickly and noisily.
szager@chromium.org3ce41842013-07-11 17:38:57 +00001043 # By default, git will use an interactive terminal prompt when a username/
1044 # password is needed. That shouldn't happen in the chromium workflow,
1045 # and if it does, then gclient may hide the prompt in the midst of a flood
1046 # of terminal spew. The only indication that something has gone wrong
1047 # will be when gclient hangs unresponsively. Instead, we disable the
1048 # password prompt and simply allow git to fail noisily. The error
1049 # message produced by git will be copied to gclient's output.
szager@chromium.org7f834ad2013-07-10 00:22:17 +00001050 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
1051 env.setdefault('GIT_ASKPASS', 'true')
1052 env.setdefault('SSH_ASKPASS', 'true')
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001053 else:
1054 kwargs.setdefault('print_stdout', True)
szager@google.com85d3e3a2011-10-07 17:12:00 +00001055 stdout = kwargs.get('stdout', sys.stdout)
1056 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
1057 ' '.join(args), kwargs['cwd']))
1058 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +00001059
1060
maruel@chromium.org55e724e2010-03-11 19:36:49 +00001061class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001062 """ Wrapper for SVN """
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001063 name = 'svn'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001064
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +00001065 @staticmethod
1066 def BinaryExists():
1067 """Returns true if the command exists."""
1068 try:
1069 result, version = scm.SVN.AssertVersion('1.4')
1070 if not result:
1071 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1072 return result
1073 except OSError:
1074 return False
1075
xusydoc@chromium.org885a9602013-05-31 09:54:40 +00001076 def GetCheckoutRoot(self):
1077 return scm.SVN.GetCheckoutRoot(self.checkout_path)
1078
floitsch@google.comeaab7842011-04-28 09:07:58 +00001079 def GetRevisionDate(self, revision):
1080 """Returns the given revision's date in ISO-8601 format (which contains the
1081 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001082 date = scm.SVN.Capture(
1083 ['propget', '--revprop', 'svn:date', '-r', revision],
1084 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +00001085 return date.strip()
1086
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001087 def cleanup(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001088 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001089 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001090
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001091 def diff(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001092 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001093 if not os.path.isdir(self.checkout_path):
1094 raise gclient_utils.Error('Directory %s is not present.' %
1095 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001096 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001097
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001098 def pack(self, _options, args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001099 """Generates a patch file which can be applied to the root of the
1100 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001101 if not os.path.isdir(self.checkout_path):
1102 raise gclient_utils.Error('Directory %s is not present.' %
1103 self.checkout_path)
1104 gclient_utils.CheckCallAndFilter(
1105 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1106 cwd=self.checkout_path,
1107 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +00001108 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001109
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001110 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +00001111 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001112
1113 All updated files will be appended to file_list.
1114
1115 Raises:
1116 Error: if can't get URL for relative path.
1117 """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001118 if args:
1119 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1120
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001121 # revision is the revision to match. It is None if no revision is specified,
1122 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001123 url, revision = gclient_utils.SplitUrlRevision(self.url)
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +00001124 # Keep the original unpinned url for reference in case the repo is switched.
1125 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001126 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001127 if options.revision:
1128 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001129 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001130 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001131 if revision != 'unmanaged':
1132 forced_revision = True
1133 # Reconstruct the url.
1134 url = '%s@%s' % (url, revision)
1135 rev_str = ' at %s' % revision
1136 else:
1137 managed = False
1138 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001139 else:
1140 forced_revision = False
1141 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001142
borenet@google.com6ff54482014-02-26 23:09:33 +00001143 if not managed:
1144 print ('________ unmanaged solution; skipping %s' % self.relpath)
1145 return self.Svnversion()
1146
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001147 # Get the existing scm url and the revision number of the current checkout.
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +00001148 exists = os.path.exists(self.checkout_path)
borenet@google.com6ff54482014-02-26 23:09:33 +00001149 needs_delete = False
1150 from_info = None
1151
1152 if exists:
1153 # If there's a git-svn checkout, verify that the svn-remote is correct.
1154 if scm.GIT.IsGitSvn(self.checkout_path):
1155 remote_url = scm.GIT.Capture(['config', '--local', '--get',
1156 'svn-remote.svn.url'],
1157 cwd=self.checkout_path).rstrip()
1158 if remote_url != base_url:
1159 needs_delete = True
1160 else:
1161 print('\n_____ %s looks like a git-svn checkout. Skipping.'
1162 % self.relpath)
1163 return # TODO(borenet): Get the svn revision number?
1164
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001165 try:
1166 from_info = scm.SVN.CaptureLocalInfo(
1167 [], os.path.join(self.checkout_path, '.'))
1168 except (gclient_utils.Error, subprocess2.CalledProcessError):
borenet@google.com6ff54482014-02-26 23:09:33 +00001169 if gclient_utils.enable_deletion_of_conflicting_checkouts():
1170 needs_delete = True
1171 else: # TODO(borenet): Remove this once we can get rid of the guard.
1172 if options.reset and options.delete_unversioned_trees:
1173 print 'Removing troublesome path %s' % self.checkout_path
1174 gclient_utils.rmtree(self.checkout_path)
1175 exists = False
1176 else:
1177 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1178 'present. Delete the directory and try again.')
1179 raise gclient_utils.Error(msg % self.checkout_path)
1180
1181 # Switch the checkout if necessary.
1182 if not needs_delete and from_info and from_info['URL'] != base_url:
1183 # The repository url changed, need to switch.
1184 try:
1185 to_info = scm.SVN.CaptureRemoteInfo(url)
1186 except (gclient_utils.Error, subprocess2.CalledProcessError):
1187 # The url is invalid or the server is not accessible, it's safer to bail
1188 # out right now.
1189 raise gclient_utils.Error('This url is unreachable: %s' % url)
1190 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1191 and (from_info['UUID'] == to_info['UUID']))
1192 if can_switch:
1193 print('\n_____ relocating %s to a new checkout' % self.relpath)
1194 # We have different roots, so check if we can switch --relocate.
1195 # Subversion only permits this if the repository UUIDs match.
1196 # Perform the switch --relocate, then rewrite the from_url
1197 # to reflect where we "are now." (This is the same way that
1198 # Subversion itself handles the metadata when switch --relocate
1199 # is used.) This makes the checks below for whether we
1200 # can update to a revision or have to switch to a different
1201 # branch work as expected.
1202 # TODO(maruel): TEST ME !
1203 command = ['switch', '--relocate',
1204 from_info['Repository Root'],
1205 to_info['Repository Root'],
1206 self.relpath]
1207 self._Run(command, options, cwd=self._root_dir)
1208 from_info['URL'] = from_info['URL'].replace(
1209 from_info['Repository Root'],
1210 to_info['Repository Root'])
1211 else:
1212 needs_delete = True
1213
1214 if (needs_delete and
1215 gclient_utils.enable_deletion_of_conflicting_checkouts()):
1216 if options.force:
1217 gclient_utils.rmtree(self.checkout_path)
1218 exists = False
1219 else:
1220 raise gclient_utils.Error('Conflicting directory found in %s. Please '
1221 'delete it or run with --force.'
1222 % self.checkout_path)
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001223
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001224 BASE_URLS = {
1225 '/chrome/trunk/src': 'gs://chromium-svn-checkout/chrome/',
1226 '/blink/trunk': 'gs://chromium-svn-checkout/blink/',
1227 }
hinoka@google.comca35be32014-01-17 01:48:18 +00001228 WHITELISTED_ROOTS = [
1229 'svn://svn.chromium.org',
1230 'svn://svn-mirror.golo.chromium.org',
1231 ]
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001232 if not exists:
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001233 try:
1234 # Split out the revision number since it's not useful for us.
1235 base_path = urlparse.urlparse(url).path.split('@')[0]
hinoka@google.comca35be32014-01-17 01:48:18 +00001236 # Check to see if we're on a whitelisted root. We do this because
1237 # only some svn servers have matching UUIDs.
1238 local_parsed = urlparse.urlparse(url)
1239 local_root = '%s://%s' % (local_parsed.scheme, local_parsed.netloc)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001240 if ('CHROME_HEADLESS' in os.environ
1241 and sys.platform == 'linux2' # TODO(hinoka): Enable for win/mac.
hinoka@google.comca35be32014-01-17 01:48:18 +00001242 and base_path in BASE_URLS
1243 and local_root in WHITELISTED_ROOTS):
1244
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001245 # Use a tarball for initial sync if we are on a bot.
1246 # Get an unauthenticated gsutil instance.
1247 gsutil = download_from_google_storage.Gsutil(
1248 GSUTIL_DEFAULT_PATH, boto_path=os.devnull)
1249
1250 gs_path = BASE_URLS[base_path]
1251 _, out, _ = gsutil.check_call('ls', gs_path)
1252 # So that we can get the most recent revision.
1253 sorted_items = sorted(out.splitlines())
1254 latest_checkout = sorted_items[-1]
1255
1256 tempdir = tempfile.mkdtemp()
1257 print 'Downloading %s...' % latest_checkout
1258 code, out, err = gsutil.check_call('cp', latest_checkout, tempdir)
1259 if code:
1260 print '%s\n%s' % (out, err)
1261 raise Exception()
1262 filename = latest_checkout.split('/')[-1]
1263 tarball = os.path.join(tempdir, filename)
1264 print 'Unpacking into %s...' % self.checkout_path
1265 gclient_utils.safe_makedirs(self.checkout_path)
1266 # TODO(hinoka): Use 7z for windows.
1267 cmd = ['tar', '--extract', '--ungzip',
1268 '--directory', self.checkout_path,
1269 '--file', tarball]
1270 gclient_utils.CheckCallAndFilter(
1271 cmd, stdout=sys.stdout, print_stdout=True)
1272
1273 print 'Deleting temp file'
1274 gclient_utils.rmtree(tempdir)
1275
1276 # Rewrite the repository root to match.
1277 tarball_url = scm.SVN.CaptureLocalInfo(
1278 ['.'], self.checkout_path)['Repository Root']
1279 tarball_parsed = urlparse.urlparse(tarball_url)
1280 tarball_root = '%s://%s' % (tarball_parsed.scheme,
1281 tarball_parsed.netloc)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001282
1283 if tarball_root != local_root:
1284 print 'Switching repository root to %s' % local_root
1285 self._Run(['switch', '--relocate', tarball_root,
1286 local_root, self.checkout_path],
1287 options)
1288 except Exception as e:
1289 print 'We tried to get a source tarball but failed.'
1290 print 'Resuming normal operations.'
1291 print str(e)
1292
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001293 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001294 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001295 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001296 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001297 self._RunAndGetFileList(command, options, file_list, self._root_dir)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001298 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001299
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001300 if 'URL' not in from_info:
1301 raise gclient_utils.Error(
1302 ('gclient is confused. Couldn\'t get the url for %s.\n'
1303 'Try using @unmanaged.\n%s') % (
1304 self.checkout_path, from_info))
1305
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001306 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001307 dir_info = scm.SVN.CaptureStatus(
1308 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001309 if any(d[0][2] == 'L' for d in dir_info):
1310 try:
1311 self._Run(['cleanup', self.checkout_path], options)
1312 except subprocess2.CalledProcessError, e:
1313 # Get the status again, svn cleanup may have cleaned up at least
1314 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001315 dir_info = scm.SVN.CaptureStatus(
1316 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001317
1318 # Try to fix the failures by removing troublesome files.
1319 for d in dir_info:
1320 if d[0][2] == 'L':
1321 if d[0][0] == '!' and options.force:
kustermann@google.com1580d952013-08-19 07:31:40 +00001322 # We don't pass any files/directories to CaptureStatus and set
1323 # cwd=self.checkout_path, so we should get relative paths here.
1324 assert not os.path.isabs(d[1])
1325 path_to_remove = os.path.normpath(
1326 os.path.join(self.checkout_path, d[1]))
1327 print 'Removing troublesome path %s' % path_to_remove
1328 gclient_utils.rmtree(path_to_remove)
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001329 else:
1330 print 'Not removing troublesome path %s automatically.' % d[1]
1331 if d[0][0] == '!':
1332 print 'You can pass --force to enable automatic removal.'
1333 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001334
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001335 # Retrieve the current HEAD version because svn is slow at null updates.
1336 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001337 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001338 revision = str(from_info_live['Revision'])
1339 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001340
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001341 # If the provided url has a revision number that matches the revision
1342 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001343 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001344 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001345 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001346 else:
1347 command = ['update', self.checkout_path]
1348 command = self._AddAdditionalUpdateFlags(command, options, revision)
1349 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001350
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001351 # If --reset and --delete_unversioned_trees are specified, remove any
1352 # untracked files and directories.
1353 if options.reset and options.delete_unversioned_trees:
1354 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1355 full_path = os.path.join(self.checkout_path, status[1])
1356 if (status[0][0] == '?'
1357 and os.path.isdir(full_path)
1358 and not os.path.islink(full_path)):
1359 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001360 gclient_utils.rmtree(full_path)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001361 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001362
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001363 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001364 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001365 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001366 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001367 # Create an empty checkout and then update the one file we want. Future
1368 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001369 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001370 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001371 if os.path.exists(os.path.join(self.checkout_path, filename)):
1372 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001373 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001374 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001375 # After the initial checkout, we can use update as if it were any other
1376 # dep.
1377 self.update(options, args, file_list)
1378 else:
1379 # If the installed version of SVN doesn't support --depth, fallback to
1380 # just exporting the file. This has the downside that revision
1381 # information is not stored next to the file, so we will have to
1382 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001383 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001384 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001385 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001386 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001387 command = self._AddAdditionalUpdateFlags(command, options,
1388 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001389 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001390
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001391 def revert(self, options, _args, file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001392 """Reverts local modifications. Subversion specific.
1393
1394 All reverted files will be appended to file_list, even if Subversion
1395 doesn't know about them.
1396 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001397 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001398 if os.path.exists(self.checkout_path):
1399 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001400 # svn revert won't work if the directory doesn't exist. It needs to
1401 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001402 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001403 # Don't reuse the args.
1404 return self.update(options, [], file_list)
1405
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001406 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +00001407 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1408 print('________ found .git directory; skipping %s' % self.relpath)
1409 return
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001410 if not options.force:
1411 raise gclient_utils.Error('Invalid checkout path, aborting')
1412 print(
1413 '\n_____ %s is not a valid svn checkout, synching instead' %
1414 self.relpath)
1415 gclient_utils.rmtree(self.checkout_path)
1416 # Don't reuse the args.
1417 return self.update(options, [], file_list)
1418
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001419 def printcb(file_status):
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001420 if file_list is not None:
1421 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001422 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001423 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001424 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001425 print(os.path.join(self.checkout_path, file_status[1]))
1426 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001427
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001428 # Revert() may delete the directory altogether.
1429 if not os.path.isdir(self.checkout_path):
1430 # Don't reuse the args.
1431 return self.update(options, [], file_list)
1432
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001433 try:
1434 # svn revert is so broken we don't even use it. Using
1435 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001436 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001437 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1438 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001439 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001440 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001441 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001442
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001443 def revinfo(self, _options, _args, _file_list):
msb@chromium.org0f282062009-11-06 20:14:02 +00001444 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001445 try:
1446 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001447 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001448 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001449
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001450 def runhooks(self, options, args, file_list):
1451 self.status(options, args, file_list)
1452
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001453 def status(self, options, args, file_list):
1454 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001455 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001456 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001457 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001458 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1459 'The directory does not exist.') %
1460 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001461 # There's no file list to retrieve.
1462 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001463 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001464
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001465 def GetUsableRev(self, rev, _options):
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001466 """Verifies the validity of the revision for this repository."""
1467 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1468 raise gclient_utils.Error(
1469 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1470 'correct.') % rev)
1471 return rev
1472
msb@chromium.orge6f78352010-01-13 17:05:33 +00001473 def FullUrlForRelativeUrl(self, url):
1474 # Find the forth '/' and strip from there. A bit hackish.
1475 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001476
maruel@chromium.org669600d2010-09-01 19:06:31 +00001477 def _Run(self, args, options, **kwargs):
1478 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001479 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001480 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001481 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001482
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001483 def Svnversion(self):
1484 """Runs the lowest checked out revision in the current project."""
1485 info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1486 return info['Revision']
1487
maruel@chromium.org669600d2010-09-01 19:06:31 +00001488 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1489 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001490 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001491 scm.SVN.RunAndGetFileList(
1492 options.verbose,
1493 args + ['--ignore-externals'],
1494 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001495 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001496
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001497 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001498 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001499 """Add additional flags to command depending on what options are set.
1500 command should be a list of strings that represents an svn command.
1501
1502 This method returns a new list to be used as a command."""
1503 new_command = command[:]
1504 if revision:
1505 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001506 # We don't want interaction when jobs are used.
1507 if options.jobs > 1:
1508 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001509 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001510 # --accept was added to 'svn update' in svn 1.6.
1511 if not scm.SVN.AssertVersion('1.5')[0]:
1512 return new_command
1513
1514 # It's annoying to have it block in the middle of a sync, just sensible
1515 # defaults.
1516 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001517 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001518 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1519 new_command.extend(('--accept', 'theirs-conflict'))
1520 elif options.manually_grab_svn_rev:
1521 new_command.append('--force')
1522 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1523 new_command.extend(('--accept', 'postpone'))
1524 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1525 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001526 return new_command