blob: f5a434b1edaada44cfcc93e64cf897f2d3ca5ae7 [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
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016
17import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000018import scm
19import subprocess2
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000020
21
szager@chromium.org71cbb502013-04-19 23:30:15 +000022THIS_FILE_PATH = os.path.abspath(__file__)
23
24
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000025class DiffFiltererWrapper(object):
26 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000027 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000028 working copy lines of the svn/git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000029 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000030 original_prefix = "--- "
31 working_prefix = "+++ "
32
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000033 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000034 # Note that we always use '/' as the path separator to be
35 # consistent with svn's cygwin-style output on Windows
36 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000037 self._current_file = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000038
maruel@chromium.org6e29d572010-06-04 17:32:20 +000039 def SetCurrentFile(self, current_file):
40 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000041
iannucci@chromium.org3830a672013-02-19 20:15:14 +000042 @property
43 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000044 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000045
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000046 def _Replace(self, line):
47 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000048
49 def Filter(self, line):
50 if (line.startswith(self.index_string)):
51 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000052 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000053 else:
54 if (line.startswith(self.original_prefix) or
55 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000056 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000057 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000058
59
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000060class SvnDiffFilterer(DiffFiltererWrapper):
61 index_string = "Index: "
62
63
64class GitDiffFilterer(DiffFiltererWrapper):
65 index_string = "diff --git "
66
67 def SetCurrentFile(self, current_file):
68 # Get filename by parsing "a/<filename> b/<filename>"
69 self._current_file = current_file[:(len(current_file)/2)][2:]
70
71 def _Replace(self, line):
72 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
73
74
bratell@opera.com18fa4542013-05-21 13:30:46 +000075def ask_for_data(prompt, options):
76 if options.jobs > 1:
77 raise gclient_utils.Error("Background task requires input. Rerun "
78 "gclient with --jobs=1 so that\n"
79 "interaction is possible.")
maruel@chromium.org90541732011-04-01 17:54:18 +000080 try:
81 return raw_input(prompt)
82 except KeyboardInterrupt:
83 # Hide the exception.
84 sys.exit(1)
85
86
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000087### SCM abstraction layer
88
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000089# Factory Method for SCM wrapper creation
90
maruel@chromium.org9eda4112010-06-11 18:56:10 +000091def GetScmName(url):
92 if url:
93 url, _ = gclient_utils.SplitUrlRevision(url)
94 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000095 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000096 url.endswith('.git')):
97 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000098 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000099 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000100 return 'svn'
101 return None
102
103
104def CreateSCM(url, root_dir=None, relpath=None):
105 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000106 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +0000107 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000108 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000109
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000110 scm_name = GetScmName(url)
111 if not scm_name in SCM_MAP:
112 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000113 scm_class = SCM_MAP[scm_name]
114 if not scm_class.BinaryExists():
115 raise gclient_utils.Error('%s command not found' % scm_name)
116 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000117
118
119# SCMWrapper base class
120
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000121class SCMWrapper(object):
122 """Add necessary glue between all the supported SCM.
123
msb@chromium.orgd6504212010-01-13 17:34:31 +0000124 This is the abstraction layer to bind to different SCM.
125 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000126 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000127 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000128 self._root_dir = root_dir
129 if self._root_dir:
130 self._root_dir = self._root_dir.replace('/', os.sep)
131 self.relpath = relpath
132 if self.relpath:
133 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000134 if self.relpath and self._root_dir:
135 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000136
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000137 def RunCommand(self, command, options, args, file_list=None):
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000138 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000139 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000140
141 if not command in commands:
142 raise gclient_utils.Error('Unknown command %s' % command)
143
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000144 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000145 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000146 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000147
148 return getattr(self, command)(options, args, file_list)
149
150
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000151class GitFilter(object):
152 """A filter_fn implementation for quieting down git output messages.
153
154 Allows a custom function to skip certain lines (predicate), and will throttle
155 the output of percentage completed lines to only output every X seconds.
156 """
157 PERCENT_RE = re.compile('.* ([0-9]{1,2})% .*')
158
159 def __init__(self, time_throttle=0, predicate=None):
160 """
161 Args:
162 time_throttle (int): GitFilter will throttle 'noisy' output (such as the
163 XX% complete messages) to only be printed at least |time_throttle|
164 seconds apart.
165 predicate (f(line)): An optional function which is invoked for every line.
166 The line will be skipped if predicate(line) returns False.
167 """
168 self.last_time = 0
169 self.time_throttle = time_throttle
170 self.predicate = predicate
171
172 def __call__(self, line):
173 # git uses an escape sequence to clear the line; elide it.
174 esc = line.find(unichr(033))
175 if esc > -1:
176 line = line[:esc]
177 if self.predicate and not self.predicate(line):
178 return
179 now = time.time()
180 match = self.PERCENT_RE.match(line)
181 if not match:
182 self.last_time = 0
183 if (now - self.last_time) >= self.time_throttle:
184 self.last_time = now
185 print line
186
187
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000188class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000189 """Wrapper for Git"""
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000190 name = 'git'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000191
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000192 cache_dir = None
193 # If a given cache is used in a solution more than once, prevent multiple
194 # threads from updating it simultaneously.
195 cache_locks = collections.defaultdict(threading.Lock)
196
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000197 def __init__(self, url=None, root_dir=None, relpath=None):
198 """Removes 'git+' fake prefix from git URL."""
199 if url.startswith('git+http://') or url.startswith('git+https://'):
200 url = url[4:]
201 SCMWrapper.__init__(self, url, root_dir, relpath)
202
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000203 @staticmethod
204 def BinaryExists():
205 """Returns true if the command exists."""
206 try:
207 # We assume git is newer than 1.7. See: crbug.com/114483
208 result, version = scm.GIT.AssertVersion('1.7')
209 if not result:
210 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
211 return result
212 except OSError:
213 return False
214
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000215 def GetCheckoutRoot(self):
216 return scm.GIT.GetCheckoutRoot(self.checkout_path)
217
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000218 def GetRevisionDate(self, _revision):
floitsch@google.comeaab7842011-04-28 09:07:58 +0000219 """Returns the given revision's date in ISO-8601 format (which contains the
220 time zone)."""
221 # TODO(floitsch): get the time-stamp of the given revision and not just the
222 # time-stamp of the currently checked out revision.
223 return self._Capture(['log', '-n', '1', '--format=%ai'])
224
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000225 @staticmethod
226 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000227 """'Cleanup' the repo.
228
229 There's no real git equivalent for the svn cleanup command, do a no-op.
230 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000231
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000232 def diff(self, options, _args, _file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000233 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000234 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000235
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000236 def pack(self, _options, _args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000237 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000238 repository.
239
240 The patch file is generated from a diff of the merge base of HEAD and
241 its upstream branch.
242 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000243 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000244 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000245 ['git', 'diff', merge_base],
246 cwd=self.checkout_path,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000247 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000248
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000249 def UpdateSubmoduleConfig(self):
250 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
251 'submodule.$name.ignore', '||',
252 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000253 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000254 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000255 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000256 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000257 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000258 kwargs = {'cwd': self.checkout_path,
259 'print_stdout': False,
260 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000261 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000262 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
263 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000264 except subprocess2.CalledProcessError:
265 # Not a fatal error, or even very interesting in a non-git-submodule
266 # world. So just keep it quiet.
267 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000268 try:
269 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
270 except subprocess2.CalledProcessError:
271 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000272
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000273 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
274
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000275 def _FetchAndReset(self, revision, file_list, options):
276 """Equivalent to git fetch; git reset."""
277 quiet = []
278 if not options.verbose:
279 quiet = ['--quiet']
280 self._UpdateBranchHeads(options, fetch=False)
iannucci@chromium.orgb8376882013-07-01 20:08:10 +0000281
282 fetch_cmd = [
283 '-c', 'core.deltaBaseCacheLimit=2g', 'fetch', 'origin', '--prune']
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +0000284 self._Run(fetch_cmd + quiet, options, retry=True)
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000285 self._Run(['reset', '--hard', revision] + quiet, options)
286 self.UpdateSubmoduleConfig()
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000287 if file_list is not None:
288 files = self._Capture(['ls-files']).splitlines()
289 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000290
msb@chromium.orge28e4982009-09-25 20:51:45 +0000291 def update(self, options, args, file_list):
292 """Runs git to update or transparently checkout the working copy.
293
294 All updated files will be appended to file_list.
295
296 Raises:
297 Error: if can't get URL for relative path.
298 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000299 if args:
300 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
301
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000302 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000303
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000304 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000305 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000306 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000307 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000308 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000309 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000310 # Override the revision number.
311 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000312 if revision == 'unmanaged':
313 revision = None
314 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000315 if not revision:
316 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000317
floitsch@google.comeaab7842011-04-28 09:07:58 +0000318 if gclient_utils.IsDateRevision(revision):
319 # Date-revisions only work on git-repositories if the reflog hasn't
320 # expired yet. Use rev-list to get the corresponding revision.
321 # git rev-list -n 1 --before='time-stamp' branchname
322 if options.transitive:
323 print('Warning: --transitive only works for SVN repositories.')
324 revision = default_rev
325
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000326 rev_str = ' at %s' % revision
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000327 files = [] if file_list is not None else None
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000328
329 printed_path = False
330 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000331 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000332 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000333 verbose = ['--verbose']
334 printed_path = True
335
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000336 url = self._CreateOrUpdateCache(url, options)
337
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000338 if revision.startswith('refs/'):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000339 rev_type = "branch"
340 elif revision.startswith('origin/'):
341 # For compatability with old naming, translate 'origin' to 'refs/heads'
342 revision = revision.replace('origin/', 'refs/heads/')
343 rev_type = "branch"
344 else:
345 # hash is also a tag, only make a distinction at checkout
346 rev_type = "hash"
347
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000348 if (not os.path.exists(self.checkout_path) or
349 (os.path.isdir(self.checkout_path) and
350 not os.path.exists(os.path.join(self.checkout_path, '.git')))):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000351 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000352 self.UpdateSubmoduleConfig()
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000353 if file_list is not None:
354 files = self._Capture(['ls-files']).splitlines()
355 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000356 if not verbose:
357 # Make the output a little prettier. It's nice to have some whitespace
358 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000359 print('')
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000360 return self._Capture(['rev-parse', '--verify', 'HEAD'])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000361
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000362 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000363 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000364 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000365 print ('________ unmanaged solution; skipping %s' % self.relpath)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000366 return self._Capture(['rev-parse', '--verify', 'HEAD'])
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000367
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000368 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
369 raise gclient_utils.Error('\n____ %s%s\n'
370 '\tPath is not a git repo. No .git dir.\n'
371 '\tTo resolve:\n'
372 '\t\trm -rf %s\n'
373 '\tAnd run gclient sync again\n'
374 % (self.relpath, rev_str, self.relpath))
375
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000376 # See if the url has changed (the unittests use git://foo for the url, let
377 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000378 current_url = self._Capture(['config', 'remote.origin.url'])
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000379 return_early = False
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000380 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
381 # unit test pass. (and update the comment above)
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +0000382 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
383 # This allows devs to use experimental repos which have a different url
384 # but whose branch(s) are the same as official repos.
385 if (current_url != url and
386 url != 'git://foo' and
387 subprocess2.capture(
388 ['git', 'config', 'remote.origin.gclient-auto-fix-url'],
389 cwd=self.checkout_path).strip() != 'False'):
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000390 print('_____ switching %s to a new upstream' % self.relpath)
391 # Make sure it's clean
392 self._CheckClean(rev_str)
393 # Switch over to the new upstream
394 self._Run(['remote', 'set-url', 'origin', url], options)
xusydoc@chromium.orgc3761712013-06-12 00:53:36 +0000395 self._FetchAndReset(revision, file_list, options)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000396 return_early = True
397
398 # Need to do this in the normal path as well as in the post-remote-switch
399 # path.
400 self._PossiblySwitchCache(url, options)
401
402 if return_early:
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000403 return self._Capture(['rev-parse', '--verify', 'HEAD'])
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000404
msb@chromium.org5bde4852009-12-14 16:47:12 +0000405 cur_branch = self._GetCurrentBranch()
406
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000407 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000408 # 0) HEAD is detached. Probably from our initial clone.
409 # - make sure HEAD is contained by a named ref, then update.
410 # Cases 1-4. HEAD is a branch.
411 # 1) current branch is not tracking a remote branch (could be git-svn)
412 # - try to rebase onto the new hash or branch
413 # 2) current branch is tracking a remote branch with local committed
414 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000415 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000416 # 3) current branch is tracking a remote branch w/or w/out changes,
417 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000418 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000419 # 4) current branch is tracking a remote branch, switches to a different
420 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000421 # - exit
422
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000423 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
424 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000425 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
426 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000427 if cur_branch is None:
428 upstream_branch = None
429 current_type = "detached"
430 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000431 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000432 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
433 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
434 current_type = "hash"
435 logging.debug("Current branch is not tracking an upstream (remote)"
436 " branch.")
437 elif upstream_branch.startswith('refs/remotes'):
438 current_type = "branch"
439 else:
440 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000441
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000442 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000443 # Update the remotes first so we have all the refs.
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000444 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000445 cwd=self.checkout_path)
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000446 if verbose:
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000447 print(remote_output)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000448
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000449 self._UpdateBranchHeads(options, fetch=True)
450
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000451 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000452 if options.force or options.reset:
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000453 target = 'HEAD'
454 if options.upstream and upstream_branch:
455 target = upstream_branch
456 self._Run(['reset', '--hard', target], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000457
msb@chromium.org786fb682010-06-02 15:16:23 +0000458 if current_type == 'detached':
459 # case 0
460 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000461 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000462 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000463 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000464 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000465 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000466 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000467 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000468 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000469 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470 newbase=revision, printed_path=printed_path)
471 printed_path = True
472 else:
473 # Can't find a merge-base since we don't know our upstream. That makes
474 # this command VERY likely to produce a rebase failure. For now we
475 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000476 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000477 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000478 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000479 self._AttemptRebase(upstream_branch, files, options,
480 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000481 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000482 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000483 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000484 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000485 newbase=revision, printed_path=printed_path)
486 printed_path = True
487 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
488 # case 4
489 new_base = revision.replace('heads', 'remotes/origin')
490 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000491 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000492 switch_error = ("Switching upstream branch from %s to %s\n"
493 % (upstream_branch, new_base) +
494 "Please merge or rebase manually:\n" +
495 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
496 "OR git checkout -b <some new branch> %s" % new_base)
497 raise gclient_utils.Error(switch_error)
498 else:
499 # case 3 - the default case
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000500 if files is not None:
501 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000502 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000503 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000504 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000505 merge_args = ['merge']
506 if not options.merge:
507 merge_args.append('--ff-only')
508 merge_args.append(upstream_branch)
509 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000510 except subprocess2.CalledProcessError as e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000511 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
512 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000513 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000514 printed_path = True
515 while True:
516 try:
maruel@chromium.org90541732011-04-01 17:54:18 +0000517 action = ask_for_data(
518 'Cannot fast-forward merge, attempt to rebase? '
bratell@opera.com18fa4542013-05-21 13:30:46 +0000519 '(y)es / (q)uit / (s)kip : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000520 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000521 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000522 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000523 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000524 printed_path=printed_path)
525 printed_path = True
526 break
527 elif re.match(r'quit|q', action, re.I):
528 raise gclient_utils.Error("Can't fast-forward, please merge or "
529 "rebase manually.\n"
530 "cd %s && git " % self.checkout_path
531 + "rebase %s" % upstream_branch)
532 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000533 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000534 return
535 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000536 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000537 elif re.match("error: Your local changes to '.*' would be "
538 "overwritten by merge. Aborting.\nPlease, commit your "
539 "changes or stash them before you can merge.\n",
540 e.stderr):
541 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000542 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000543 printed_path = True
544 raise gclient_utils.Error(e.stderr)
545 else:
546 # Some other problem happened with the merge
547 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000548 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000549 raise
550 else:
551 # Fast-forward merge was successful
552 if not re.match('Already up-to-date.', merge_output) or verbose:
553 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000554 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000555 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000556 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000557 if not verbose:
558 # Make the output a little prettier. It's nice to have some
559 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000560 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000561
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000562 self.UpdateSubmoduleConfig()
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000563 if file_list is not None:
564 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000565
566 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000567 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000568 raise gclient_utils.Error('\n____ %s%s\n'
569 '\nConflict while rebasing this branch.\n'
570 'Fix the conflict and run gclient again.\n'
571 'See man git-rebase for details.\n'
572 % (self.relpath, rev_str))
573
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000574 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000575 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000576
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000577 # If --reset and --delete_unversioned_trees are specified, remove any
578 # untracked directories.
579 if options.reset and options.delete_unversioned_trees:
580 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
581 # merge-base by default), so doesn't include untracked files. So we use
582 # 'git ls-files --directory --others --exclude-standard' here directly.
583 paths = scm.GIT.Capture(
584 ['ls-files', '--directory', '--others', '--exclude-standard'],
585 self.checkout_path)
586 for path in (p for p in paths.splitlines() if p.endswith('/')):
587 full_path = os.path.join(self.checkout_path, path)
588 if not os.path.islink(full_path):
589 print('\n_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000590 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000591
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000592 return self._Capture(['rev-parse', '--verify', 'HEAD'])
593
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000594
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000595 def revert(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000596 """Reverts local modifications.
597
598 All reverted files will be appended to file_list.
599 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000600 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000601 # revert won't work if the directory doesn't exist. It needs to
602 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000603 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000604 # Don't reuse the args.
605 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000606
607 default_rev = "refs/heads/master"
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000608 if options.upstream:
609 if self._GetCurrentBranch():
610 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
611 default_rev = upstream_branch or default_rev
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000612 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000613 if not deps_revision:
614 deps_revision = default_rev
615 if deps_revision.startswith('refs/heads/'):
616 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
617
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000618 if file_list is not None:
619 files = self._Capture(['diff', deps_revision, '--name-only']).split()
620
maruel@chromium.org37e89872010-09-07 16:11:33 +0000621 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000622 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000623
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000624 if file_list is not None:
625 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
626
627 def revinfo(self, _options, _args, _file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000628 """Returns revision"""
629 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000630
msb@chromium.orge28e4982009-09-25 20:51:45 +0000631 def runhooks(self, options, args, file_list):
632 self.status(options, args, file_list)
633
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000634 def status(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000635 """Display status information."""
636 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000637 print(('\n________ couldn\'t run status in %s:\n'
638 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000639 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000640 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000641 self._Run(['diff', '--name-status', merge_base], options)
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000642 if file_list is not None:
643 files = self._Capture(['diff', '--name-only', merge_base]).split()
644 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000645
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000646 def GetUsableRev(self, rev, options):
647 """Finds a useful revision for this repository.
648
649 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
650 will be called on the source."""
651 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000652 if not os.path.isdir(self.checkout_path):
653 raise gclient_utils.Error(
654 ( 'We could not find a valid hash for safesync_url response "%s".\n'
655 'Safesync URLs with a git checkout currently require the repo to\n'
656 'be cloned without a safesync_url before adding the safesync_url.\n'
657 'For more info, see: '
658 'http://code.google.com/p/chromium/wiki/UsingNewGit'
659 '#Initial_checkout' ) % rev)
660 elif rev.isdigit() and len(rev) < 7:
661 # Handles an SVN rev. As an optimization, only verify an SVN revision as
662 # [0-9]{1,6} for now to avoid making a network request.
663 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000664 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
665 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000666 try:
667 logging.debug('Looking for git-svn configuration optimizations.')
668 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
669 cwd=self.checkout_path):
670 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
671 except subprocess2.CalledProcessError:
672 logging.debug('git config --get svn-remote.svn.fetch failed, '
673 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000674 if options.verbose:
675 print('Running git svn fetch. This might take a while.\n')
676 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000677 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000678 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
679 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000680 except gclient_utils.Error, e:
681 sha1 = e.message
682 print('\nWarning: Could not find a git revision with accurate\n'
683 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
684 'the closest sane git revision, which is:\n'
685 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000686 if not sha1:
687 raise gclient_utils.Error(
688 ( 'It appears that either your git-svn remote is incorrectly\n'
689 'configured or the revision in your safesync_url is\n'
690 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
691 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000692 else:
693 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
694 sha1 = rev
695 else:
696 # May exist in origin, but we don't have it yet, so fetch and look
697 # again.
698 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
699 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
700 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000701
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000702 if not sha1:
703 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000704 ( 'We could not find a valid hash for safesync_url response "%s".\n'
705 'Safesync URLs with a git checkout currently require a git-svn\n'
706 'remote or a safesync_url that provides git sha1s. Please add a\n'
707 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000708 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000709 '#Initial_checkout' ) % rev)
710
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000711 return sha1
712
msb@chromium.orge6f78352010-01-13 17:05:33 +0000713 def FullUrlForRelativeUrl(self, url):
714 # Strip from last '/'
715 # Equivalent to unix basename
716 base_url = self.url
717 return base_url[:base_url.rfind('/')] + url
718
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000719 @staticmethod
720 def _NormalizeGitURL(url):
721 '''Takes a git url, strips the scheme, and ensures it ends with '.git'.'''
722 idx = url.find('://')
723 if idx != -1:
724 url = url[idx+3:]
725 if not url.endswith('.git'):
726 url += '.git'
727 return url
728
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000729 def _PossiblySwitchCache(self, url, options):
730 """Handles switching a repo from with-cache to direct, or vice versa.
731
732 When we go from direct to with-cache, the remote url changes from the
733 'real' url to the local file url (in cache_dir). Therefore, this function
734 assumes that |url| points to the correctly-switched-over local file url, if
735 we're in cache_mode.
736
737 When we go from with-cache to direct, assume that the normal url-switching
738 code already flipped the remote over, and we just need to repack and break
739 the dependency to the cache.
740 """
741
742 altfile = os.path.join(
743 self.checkout_path, '.git', 'objects', 'info', 'alternates')
744 if self.cache_dir:
745 if not os.path.exists(altfile):
746 try:
iannucci@chromium.org578e5e52013-07-18 20:55:16 +0000747 with open(altfile, 'w') as f:
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000748 f.write(os.path.join(url, 'objects'))
749 # pylint: disable=C0301
750 # This dance is necessary according to emperical evidence, also at:
751 # http://lists-archives.com/git/713652-retrospectively-add-alternates-to-a-repository.html
752 self._Run(['repack', '-ad'], options)
753 self._Run(['repack', '-adl'], options)
754 except Exception:
755 # If something goes wrong, try to remove the altfile so we'll go down
756 # this path again next time.
757 try:
758 os.remove(altfile)
iannucci@chromium.org578e5e52013-07-18 20:55:16 +0000759 except OSError as e:
760 print >> sys.stderr, "FAILED: os.remove('%s') -> %s" % (altfile, e)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000761 raise
762 else:
763 if os.path.exists(altfile):
764 self._Run(['repack', '-a'], options)
765 os.remove(altfile)
766
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000767 def _CreateOrUpdateCache(self, url, options):
768 """Make a new git mirror or update existing mirror for |url|, and return the
769 mirror URI to clone from.
770
771 If no cache-dir is specified, just return |url| unchanged.
772 """
773 if not self.cache_dir:
774 return url
775
776 # Replace - with -- to avoid ambiguity. / with - to flatten folder structure
777 folder = os.path.join(
778 self.cache_dir,
779 self._NormalizeGitURL(url).replace('-', '--').replace('/', '-'))
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000780 altfile = os.path.join(folder, 'objects', 'info', 'alternates')
781
782 # If we're bringing an old cache up to date or cloning a new cache, and the
783 # existing repo is currently a direct clone, use its objects to help out
784 # the fetch here.
785 checkout_objects = os.path.join(self.checkout_path, '.git', 'objects')
786 checkout_altfile = os.path.join(checkout_objects, 'info', 'alternates')
787 use_reference = (
788 os.path.exists(checkout_objects) and
789 not os.path.exists(checkout_altfile))
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000790
791 v = ['-v'] if options.verbose else []
792 filter_fn = lambda l: '[up to date]' not in l
793 with self.cache_locks[folder]:
794 gclient_utils.safe_makedirs(self.cache_dir)
795 if not os.path.exists(os.path.join(folder, 'config')):
796 gclient_utils.rmtree(folder)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000797 cmd = ['clone'] + v + ['-c', 'core.deltaBaseCacheLimit=2g',
798 '--progress', '--mirror']
799
800 if use_reference:
801 cmd += ['--reference', os.path.abspath(self.checkout_path)]
802
803 self._Run(cmd + [url, folder],
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000804 options, filter_fn=filter_fn, cwd=self.cache_dir, retry=True)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000805 else:
806 # For now, assert that host/path/to/repo.git is identical. We may want
807 # to relax this restriction in the future to allow for smarter cache
808 # repo update schemes (such as pulling the same repo, but from a
809 # different host).
810 existing_url = self._Capture(['config', 'remote.origin.url'],
811 cwd=folder)
812 assert self._NormalizeGitURL(existing_url) == self._NormalizeGitURL(url)
813
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000814 if use_reference:
815 with open(altfile, 'w') as f:
816 f.write(os.path.abspath(checkout_objects))
817
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000818 # Would normally use `git remote update`, but it doesn't support
819 # --progress, so use fetch instead.
820 self._Run(['fetch'] + v + ['--multiple', '--progress', '--all'],
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000821 options, filter_fn=filter_fn, cwd=folder, retry=True)
iannucci@chromium.org976a14d2013-07-17 21:56:49 +0000822
823 # If the clone has an object dependency on the existing repo, break it
824 # with repack and remove the linkage.
825 if os.path.exists(altfile):
826 self._Run(['repack', '-a'], options, cwd=folder)
827 os.remove(altfile)
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000828 return folder
829
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000830 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000831 """Clone a git repository from the given URL.
832
msb@chromium.org786fb682010-06-02 15:16:23 +0000833 Once we've cloned the repo, we checkout a working branch if the specified
834 revision is a branch head. If it is a tag or a specific commit, then we
835 leave HEAD detached as it makes future updates simpler -- in this case the
836 user should first create a new branch or switch to an existing branch before
837 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000838 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000839 # git clone doesn't seem to insert a newline properly before printing
840 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000841 print('')
szager@chromium.orgecb75422013-07-12 21:57:33 +0000842 template_path = os.path.join(
843 os.path.dirname(THIS_FILE_PATH), 'git-templates')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000844 clone_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'clone', '--no-checkout',
845 '--progress', '--template=%s' % template_path]
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000846 if self.cache_dir:
847 clone_cmd.append('--shared')
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000848 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000849 clone_cmd.append('--verbose')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000850 clone_cmd.append(url)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000851 # If the parent directory does not exist, Git clone on Windows will not
852 # create it, so we need to do it manually.
853 parent_dir = os.path.dirname(self.checkout_path)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000854 gclient_utils.safe_makedirs(parent_dir)
855 tmp_dir = tempfile.mkdtemp(
856 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
857 dir=parent_dir)
858 try:
859 clone_cmd.append(tmp_dir)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000860 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000861 gclient_utils.safe_makedirs(self.checkout_path)
cyrille@nnamrak.orgef509e42013-09-20 13:19:08 +0000862 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
863 os.path.join(self.checkout_path, '.git'))
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000864 finally:
865 if os.listdir(tmp_dir):
866 print('\n_____ removing non-empty tmp dir %s' % tmp_dir)
867 gclient_utils.rmtree(tmp_dir)
868 if revision.startswith('refs/heads/'):
869 self._Run(
870 ['checkout', '--quiet', revision.replace('refs/heads/', '')], options)
871 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000872 # Squelch git's very verbose detached HEAD warning and use our own
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000873 self._Run(['checkout', '--quiet', revision], options)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000874 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000875 ('Checked out %s to a detached HEAD. Before making any commits\n'
876 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
877 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
878 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000879
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000880 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000881 branch=None, printed_path=False):
882 """Attempt to rebase onto either upstream or, if specified, newbase."""
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000883 if files is not None:
884 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000885 revision = upstream
886 if newbase:
887 revision = newbase
888 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000889 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000890 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000891 printed_path = True
892 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000893 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000894
895 # Build the rebase command here using the args
896 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
897 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000898 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000899 rebase_cmd.append('--verbose')
900 if newbase:
901 rebase_cmd.extend(['--onto', newbase])
902 rebase_cmd.append(upstream)
903 if branch:
904 rebase_cmd.append(branch)
905
906 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000907 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000908 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000909 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
910 re.match(r'cannot rebase: your index contains uncommitted changes',
911 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000912 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000913 rebase_action = ask_for_data(
914 'Cannot rebase because of unstaged changes.\n'
915 '\'git reset --hard HEAD\' ?\n'
916 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000917 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000918 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000919 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000920 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000921 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000922 break
923 elif re.match(r'quit|q', rebase_action, re.I):
924 raise gclient_utils.Error("Please merge or rebase manually\n"
925 "cd %s && git " % self.checkout_path
926 + "%s" % ' '.join(rebase_cmd))
927 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000928 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000929 continue
930 else:
931 gclient_utils.Error("Input not recognized")
932 continue
933 elif re.search(r'^CONFLICT', e.stdout, re.M):
934 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
935 "Fix the conflict and run gclient again.\n"
936 "See 'man git-rebase' for details.\n")
937 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000938 print(e.stdout.strip())
939 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000940 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
941 "manually.\ncd %s && git " %
942 self.checkout_path
943 + "%s" % ' '.join(rebase_cmd))
944
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000945 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000946 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000947 # Make the output a little prettier. It's nice to have some
948 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000949 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000950
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000951 @staticmethod
952 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000953 (ok, current_version) = scm.GIT.AssertVersion(min_version)
954 if not ok:
955 raise gclient_utils.Error('git version %s < minimum required %s' %
956 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000957
msb@chromium.org786fb682010-06-02 15:16:23 +0000958 def _IsRebasing(self):
959 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
960 # have a plumbing command to determine whether a rebase is in progress, so
961 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
962 g = os.path.join(self.checkout_path, '.git')
963 return (
964 os.path.isdir(os.path.join(g, "rebase-merge")) or
965 os.path.isdir(os.path.join(g, "rebase-apply")))
966
967 def _CheckClean(self, rev_str):
968 # Make sure the tree is clean; see git-rebase.sh for reference
969 try:
970 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000971 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000972 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000973 raise gclient_utils.Error('\n____ %s%s\n'
974 '\tYou have unstaged changes.\n'
975 '\tPlease commit, stash, or reset.\n'
976 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000977 try:
978 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000979 '--ignore-submodules', 'HEAD', '--'],
980 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000981 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000982 raise gclient_utils.Error('\n____ %s%s\n'
983 '\tYour index contains uncommitted changes\n'
984 '\tPlease commit, stash, or reset.\n'
985 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000986
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000987 def _CheckDetachedHead(self, rev_str, _options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000988 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
989 # reference by a commit). If not, error out -- most likely a rebase is
990 # in progress, try to detect so we can give a better error.
991 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000992 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
993 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000994 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000995 # Commit is not contained by any rev. See if the user is rebasing:
996 if self._IsRebasing():
997 # Punt to the user
998 raise gclient_utils.Error('\n____ %s%s\n'
999 '\tAlready in a conflict, i.e. (no branch).\n'
1000 '\tFix the conflict and run gclient again.\n'
1001 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
1002 '\tSee man git-rebase for details.\n'
1003 % (self.relpath, rev_str))
1004 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001005 name = ('saved-by-gclient-' +
1006 self._Capture(['rev-parse', '--short', 'HEAD']))
mmoss@chromium.org77bd7362013-09-25 23:46:14 +00001007 self._Capture(['branch', '-f', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001008 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +00001009 name)
msb@chromium.org786fb682010-06-02 15:16:23 +00001010
msb@chromium.org5bde4852009-12-14 16:47:12 +00001011 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +00001012 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001013 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +00001014 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +00001015 return None
1016 return branch
1017
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001018 def _Capture(self, args, cwd=None):
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001019 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +00001020 ['git'] + args,
ilevy@chromium.orgf6f58402013-05-22 00:14:32 +00001021 stderr=subprocess2.VOID,
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001022 cwd=cwd or self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001023
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001024 def _UpdateBranchHeads(self, options, fetch=False):
1025 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
1026 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +00001027 config_cmd = ['config', 'remote.origin.fetch',
1028 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1029 '^\\+refs/branch-heads/\\*:.*$']
1030 self._Run(config_cmd, options)
1031 if fetch:
1032 fetch_cmd = ['-c', 'core.deltaBaseCacheLimit=2g', 'fetch', 'origin']
1033 if options.verbose:
1034 fetch_cmd.append('--verbose')
1035 self._Run(fetch_cmd, options, retry=True)
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001036
agable@chromium.orgfd5b6382013-10-25 20:54:34 +00001037 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001038 kwargs.setdefault('cwd', self.checkout_path)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +00001039 git_filter = not options.verbose
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001040 if git_filter:
scottmg@chromium.orgf547c802013-09-27 17:55:26 +00001041 kwargs['filter_fn'] = GitFilter(kwargs.get('filter_fn'))
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001042 kwargs.setdefault('print_stdout', False)
szager@chromium.org7f834ad2013-07-10 00:22:17 +00001043 # Don't prompt for passwords; just fail quickly and noisily.
szager@chromium.org3ce41842013-07-11 17:38:57 +00001044 # By default, git will use an interactive terminal prompt when a username/
1045 # password is needed. That shouldn't happen in the chromium workflow,
1046 # and if it does, then gclient may hide the prompt in the midst of a flood
1047 # of terminal spew. The only indication that something has gone wrong
1048 # will be when gclient hangs unresponsively. Instead, we disable the
1049 # password prompt and simply allow git to fail noisily. The error
1050 # message produced by git will be copied to gclient's output.
szager@chromium.org7f834ad2013-07-10 00:22:17 +00001051 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
1052 env.setdefault('GIT_ASKPASS', 'true')
1053 env.setdefault('SSH_ASKPASS', 'true')
iannucci@chromium.org53456aa2013-07-03 19:38:34 +00001054 else:
1055 kwargs.setdefault('print_stdout', True)
szager@google.com85d3e3a2011-10-07 17:12:00 +00001056 stdout = kwargs.get('stdout', sys.stdout)
1057 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
1058 ' '.join(args), kwargs['cwd']))
1059 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +00001060
1061
maruel@chromium.org55e724e2010-03-11 19:36:49 +00001062class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001063 """ Wrapper for SVN """
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001064 name = 'svn'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001065
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +00001066 @staticmethod
1067 def BinaryExists():
1068 """Returns true if the command exists."""
1069 try:
1070 result, version = scm.SVN.AssertVersion('1.4')
1071 if not result:
1072 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1073 return result
1074 except OSError:
1075 return False
1076
xusydoc@chromium.org885a9602013-05-31 09:54:40 +00001077 def GetCheckoutRoot(self):
1078 return scm.SVN.GetCheckoutRoot(self.checkout_path)
1079
floitsch@google.comeaab7842011-04-28 09:07:58 +00001080 def GetRevisionDate(self, revision):
1081 """Returns the given revision's date in ISO-8601 format (which contains the
1082 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001083 date = scm.SVN.Capture(
1084 ['propget', '--revprop', 'svn:date', '-r', revision],
1085 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +00001086 return date.strip()
1087
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001088 def cleanup(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001089 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001090 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001091
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001092 def diff(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001093 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001094 if not os.path.isdir(self.checkout_path):
1095 raise gclient_utils.Error('Directory %s is not present.' %
1096 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001097 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001098
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001099 def pack(self, _options, args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001100 """Generates a patch file which can be applied to the root of the
1101 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001102 if not os.path.isdir(self.checkout_path):
1103 raise gclient_utils.Error('Directory %s is not present.' %
1104 self.checkout_path)
1105 gclient_utils.CheckCallAndFilter(
1106 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1107 cwd=self.checkout_path,
1108 print_stdout=False,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +00001109 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001110
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001111 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +00001112 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001113
1114 All updated files will be appended to file_list.
1115
1116 Raises:
1117 Error: if can't get URL for relative path.
1118 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +00001119 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001120 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001121 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001122 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001123 return
1124
morrita@chromium.org21dca0e2010-10-05 00:55:12 +00001125 hg_path = os.path.join(self.checkout_path, '.hg')
1126 if os.path.exists(hg_path):
1127 print('________ found .hg directory; skipping %s' % self.relpath)
1128 return
1129
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001130 if args:
1131 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1132
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001133 # revision is the revision to match. It is None if no revision is specified,
1134 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001135 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001136 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001137 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001138 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001139 if options.revision:
1140 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001141 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001142 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001143 if revision != 'unmanaged':
1144 forced_revision = True
1145 # Reconstruct the url.
1146 url = '%s@%s' % (url, revision)
1147 rev_str = ' at %s' % revision
1148 else:
1149 managed = False
1150 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001151 else:
1152 forced_revision = False
1153 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001154
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001155 # Get the existing scm url and the revision number of the current checkout.
1156 exists = os.path.exists(self.checkout_path)
1157 if exists and managed:
1158 try:
1159 from_info = scm.SVN.CaptureLocalInfo(
1160 [], os.path.join(self.checkout_path, '.'))
1161 except (gclient_utils.Error, subprocess2.CalledProcessError):
1162 if options.reset and options.delete_unversioned_trees:
1163 print 'Removing troublesome path %s' % self.checkout_path
1164 gclient_utils.rmtree(self.checkout_path)
1165 exists = False
1166 else:
1167 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1168 'present. Delete the directory and try again.')
1169 raise gclient_utils.Error(msg % self.checkout_path)
1170
1171 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001172 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001173 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001174 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001175 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001176 self._RunAndGetFileList(command, options, file_list, self._root_dir)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001177 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001178
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001179 if not managed:
1180 print ('________ unmanaged solution; skipping %s' % self.relpath)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001181 return self.Svnversion()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001182
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001183 if 'URL' not in from_info:
1184 raise gclient_utils.Error(
1185 ('gclient is confused. Couldn\'t get the url for %s.\n'
1186 'Try using @unmanaged.\n%s') % (
1187 self.checkout_path, from_info))
1188
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001189 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001190 dir_info = scm.SVN.CaptureStatus(
1191 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001192 if any(d[0][2] == 'L' for d in dir_info):
1193 try:
1194 self._Run(['cleanup', self.checkout_path], options)
1195 except subprocess2.CalledProcessError, e:
1196 # Get the status again, svn cleanup may have cleaned up at least
1197 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001198 dir_info = scm.SVN.CaptureStatus(
1199 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001200
1201 # Try to fix the failures by removing troublesome files.
1202 for d in dir_info:
1203 if d[0][2] == 'L':
1204 if d[0][0] == '!' and options.force:
kustermann@google.com1580d952013-08-19 07:31:40 +00001205 # We don't pass any files/directories to CaptureStatus and set
1206 # cwd=self.checkout_path, so we should get relative paths here.
1207 assert not os.path.isabs(d[1])
1208 path_to_remove = os.path.normpath(
1209 os.path.join(self.checkout_path, d[1]))
1210 print 'Removing troublesome path %s' % path_to_remove
1211 gclient_utils.rmtree(path_to_remove)
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001212 else:
1213 print 'Not removing troublesome path %s automatically.' % d[1]
1214 if d[0][0] == '!':
1215 print 'You can pass --force to enable automatic removal.'
1216 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001217
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001218 # Retrieve the current HEAD version because svn is slow at null updates.
1219 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001220 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001221 revision = str(from_info_live['Revision'])
1222 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001223
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001224 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001225 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001226 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001227 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001228 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001229 # The url is invalid or the server is not accessible, it's safer to bail
1230 # out right now.
1231 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001232 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1233 and (from_info['UUID'] == to_info['UUID']))
1234 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001235 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001236 # We have different roots, so check if we can switch --relocate.
1237 # Subversion only permits this if the repository UUIDs match.
1238 # Perform the switch --relocate, then rewrite the from_url
1239 # to reflect where we "are now." (This is the same way that
1240 # Subversion itself handles the metadata when switch --relocate
1241 # is used.) This makes the checks below for whether we
1242 # can update to a revision or have to switch to a different
1243 # branch work as expected.
1244 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001245 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001246 from_info['Repository Root'],
1247 to_info['Repository Root'],
1248 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001249 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001250 from_info['URL'] = from_info['URL'].replace(
1251 from_info['Repository Root'],
1252 to_info['Repository Root'])
1253 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001254 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001255 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001256 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001257 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001258 raise gclient_utils.Error(
1259 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1260 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001261 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001262 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001263 print('\n_____ switching %s to a new checkout' % self.relpath)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001264 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001265 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001266 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001267 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001268 self._RunAndGetFileList(command, options, file_list, self._root_dir)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001269 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001270
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001271 # If the provided url has a revision number that matches the revision
1272 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001273 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001274 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001275 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001276 else:
1277 command = ['update', self.checkout_path]
1278 command = self._AddAdditionalUpdateFlags(command, options, revision)
1279 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001280
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001281 # If --reset and --delete_unversioned_trees are specified, remove any
1282 # untracked files and directories.
1283 if options.reset and options.delete_unversioned_trees:
1284 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1285 full_path = os.path.join(self.checkout_path, status[1])
1286 if (status[0][0] == '?'
1287 and os.path.isdir(full_path)
1288 and not os.path.islink(full_path)):
1289 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001290 gclient_utils.rmtree(full_path)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001291 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001292
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001293 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001294 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001295 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001296 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001297 # Create an empty checkout and then update the one file we want. Future
1298 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001299 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001300 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001301 if os.path.exists(os.path.join(self.checkout_path, filename)):
1302 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001303 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001304 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001305 # After the initial checkout, we can use update as if it were any other
1306 # dep.
1307 self.update(options, args, file_list)
1308 else:
1309 # If the installed version of SVN doesn't support --depth, fallback to
1310 # just exporting the file. This has the downside that revision
1311 # information is not stored next to the file, so we will have to
1312 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001313 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001314 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001315 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001316 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001317 command = self._AddAdditionalUpdateFlags(command, options,
1318 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001319 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001320
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001321 def revert(self, options, _args, file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001322 """Reverts local modifications. Subversion specific.
1323
1324 All reverted files will be appended to file_list, even if Subversion
1325 doesn't know about them.
1326 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001327 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001328 if os.path.exists(self.checkout_path):
1329 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001330 # svn revert won't work if the directory doesn't exist. It needs to
1331 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001332 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001333 # Don't reuse the args.
1334 return self.update(options, [], file_list)
1335
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001336 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1337 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1338 print('________ found .git directory; skipping %s' % self.relpath)
1339 return
1340 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1341 print('________ found .hg directory; skipping %s' % self.relpath)
1342 return
1343 if not options.force:
1344 raise gclient_utils.Error('Invalid checkout path, aborting')
1345 print(
1346 '\n_____ %s is not a valid svn checkout, synching instead' %
1347 self.relpath)
1348 gclient_utils.rmtree(self.checkout_path)
1349 # Don't reuse the args.
1350 return self.update(options, [], file_list)
1351
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001352 def printcb(file_status):
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001353 if file_list is not None:
1354 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001355 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001356 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001357 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001358 print(os.path.join(self.checkout_path, file_status[1]))
1359 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001360
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001361 # Revert() may delete the directory altogether.
1362 if not os.path.isdir(self.checkout_path):
1363 # Don't reuse the args.
1364 return self.update(options, [], file_list)
1365
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001366 try:
1367 # svn revert is so broken we don't even use it. Using
1368 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001369 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001370 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1371 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001372 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001373 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001374 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001375
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001376 def revinfo(self, _options, _args, _file_list):
msb@chromium.org0f282062009-11-06 20:14:02 +00001377 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001378 try:
1379 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001380 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001381 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001382
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001383 def runhooks(self, options, args, file_list):
1384 self.status(options, args, file_list)
1385
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001386 def status(self, options, args, file_list):
1387 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001388 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001389 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001390 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001391 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1392 'The directory does not exist.') %
1393 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001394 # There's no file list to retrieve.
1395 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001396 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001397
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001398 def GetUsableRev(self, rev, _options):
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001399 """Verifies the validity of the revision for this repository."""
1400 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1401 raise gclient_utils.Error(
1402 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1403 'correct.') % rev)
1404 return rev
1405
msb@chromium.orge6f78352010-01-13 17:05:33 +00001406 def FullUrlForRelativeUrl(self, url):
1407 # Find the forth '/' and strip from there. A bit hackish.
1408 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001409
maruel@chromium.org669600d2010-09-01 19:06:31 +00001410 def _Run(self, args, options, **kwargs):
1411 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001412 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001413 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001414 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001415
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001416 def Svnversion(self):
1417 """Runs the lowest checked out revision in the current project."""
1418 info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1419 return info['Revision']
1420
maruel@chromium.org669600d2010-09-01 19:06:31 +00001421 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1422 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001423 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001424 scm.SVN.RunAndGetFileList(
1425 options.verbose,
1426 args + ['--ignore-externals'],
1427 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001428 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001429
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001430 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001431 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001432 """Add additional flags to command depending on what options are set.
1433 command should be a list of strings that represents an svn command.
1434
1435 This method returns a new list to be used as a command."""
1436 new_command = command[:]
1437 if revision:
1438 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001439 # We don't want interaction when jobs are used.
1440 if options.jobs > 1:
1441 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001442 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001443 # --accept was added to 'svn update' in svn 1.6.
1444 if not scm.SVN.AssertVersion('1.5')[0]:
1445 return new_command
1446
1447 # It's annoying to have it block in the middle of a sync, just sensible
1448 # defaults.
1449 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001450 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001451 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1452 new_command.extend(('--accept', 'theirs-conflict'))
1453 elif options.manually_grab_svn_rev:
1454 new_command.append('--force')
1455 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1456 new_command.extend(('--accept', 'postpone'))
1457 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1458 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001459 return new_command