blob: cf19e350d9627c98f20f03c875509ce8c1e65c0c [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
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00007from __future__ import print_function
8
borenet@google.comb2256212014-05-07 20:57:28 +00009import errno
maruel@chromium.org754960e2009-09-21 12:31:05 +000010import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000011import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000012import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013import re
maruel@chromium.org90541732011-04-01 17:54:18 +000014import sys
ilevy@chromium.org3534aa52013-07-20 01:58:08 +000015import tempfile
zty@chromium.org6279e8a2014-02-13 01:45:25 +000016import traceback
hinoka@google.com2f2ca142014-01-07 03:59:18 +000017import urlparse
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000018
hinoka@google.com2f2ca142014-01-07 03:59:18 +000019import download_from_google_storage
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000020import gclient_utils
szager@chromium.org848fd492014-04-09 19:06:44 +000021import git_cache
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000022import scm
borenet@google.comb2256212014-05-07 20:57:28 +000023import shutil
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000024import subprocess2
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000025
26
szager@chromium.org71cbb502013-04-19 23:30:15 +000027THIS_FILE_PATH = os.path.abspath(__file__)
28
hinoka@google.com2f2ca142014-01-07 03:59:18 +000029GSUTIL_DEFAULT_PATH = os.path.join(
hinoka@chromium.orgb091aa52014-12-20 01:47:31 +000030 os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
hinoka@google.com2f2ca142014-01-07 03:59:18 +000031
maruel@chromium.org79d62372015-06-01 18:50:55 +000032
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000033class DiffFiltererWrapper(object):
34 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000035 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000036 working copy lines of the svn/git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000037 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000038 original_prefix = "--- "
39 working_prefix = "+++ "
40
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000041 def __init__(self, relpath, print_func):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000042 # Note that we always use '/' as the path separator to be
43 # consistent with svn's cygwin-style output on Windows
44 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000045 self._current_file = None
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000046 self._print_func = print_func
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000047
maruel@chromium.org6e29d572010-06-04 17:32:20 +000048 def SetCurrentFile(self, current_file):
49 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000050
iannucci@chromium.org3830a672013-02-19 20:15:14 +000051 @property
52 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000053 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000054
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000055 def _Replace(self, line):
56 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000057
58 def Filter(self, line):
59 if (line.startswith(self.index_string)):
60 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000061 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000062 else:
63 if (line.startswith(self.original_prefix) or
64 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000065 line = self._Replace(line)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000066 self._print_func(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000067
68
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000069class SvnDiffFilterer(DiffFiltererWrapper):
70 index_string = "Index: "
71
72
73class GitDiffFilterer(DiffFiltererWrapper):
74 index_string = "diff --git "
75
76 def SetCurrentFile(self, current_file):
77 # Get filename by parsing "a/<filename> b/<filename>"
78 self._current_file = current_file[:(len(current_file)/2)][2:]
79
80 def _Replace(self, line):
81 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
82
83
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000084### SCM abstraction layer
85
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000086# Factory Method for SCM wrapper creation
87
maruel@chromium.org9eda4112010-06-11 18:56:10 +000088def GetScmName(url):
89 if url:
90 url, _ = gclient_utils.SplitUrlRevision(url)
91 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000092 url.startswith('git+http://') or url.startswith('git+https://') or
borenet@google.coma2aec972014-04-22 21:35:15 +000093 url.endswith('.git') or url.startswith('sso://') or
94 'googlesource' in url):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000095 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000096 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000097 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000098 return 'svn'
agable@chromium.org44ae4fb2014-10-23 08:28:30 +000099 elif url.startswith('file://'):
100 if url.endswith('.git'):
101 return 'git'
102 return 'svn'
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000103 return None
104
105
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000106def CreateSCM(url, root_dir=None, relpath=None, out_fh=None, out_cb=None):
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000107 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000108 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +0000109 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000110 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000111
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000112 scm_name = GetScmName(url)
113 if not scm_name in SCM_MAP:
114 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000115 scm_class = SCM_MAP[scm_name]
116 if not scm_class.BinaryExists():
117 raise gclient_utils.Error('%s command not found' % scm_name)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000118 return scm_class(url, root_dir, relpath, out_fh, out_cb)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000119
120
121# SCMWrapper base class
122
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000123class SCMWrapper(object):
124 """Add necessary glue between all the supported SCM.
125
msb@chromium.orgd6504212010-01-13 17:34:31 +0000126 This is the abstraction layer to bind to different SCM.
127 """
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000128
129 def __init__(self, url=None, root_dir=None, relpath=None, out_fh=None,
130 out_cb=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000131 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000132 self._root_dir = root_dir
133 if self._root_dir:
134 self._root_dir = self._root_dir.replace('/', os.sep)
135 self.relpath = relpath
136 if self.relpath:
137 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000138 if self.relpath and self._root_dir:
139 self.checkout_path = os.path.join(self._root_dir, self.relpath)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000140 if out_fh is None:
141 out_fh = sys.stdout
142 self.out_fh = out_fh
143 self.out_cb = out_cb
144
145 def Print(self, *args, **kwargs):
146 kwargs.setdefault('file', self.out_fh)
147 if kwargs.pop('timestamp', True):
148 self.out_fh.write('[%s] ' % gclient_utils.Elapsed())
149 print(*args, **kwargs)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000150
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000151 def RunCommand(self, command, options, args, file_list=None):
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000152 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000153 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000154
155 if not command in commands:
156 raise gclient_utils.Error('Unknown command %s' % command)
157
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000158 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000159 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000160 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000161
162 return getattr(self, command)(options, args, file_list)
163
hinoka@chromium.orgfa2b9b42014-08-22 18:08:53 +0000164 @staticmethod
165 def _get_first_remote_url(checkout_path):
166 log = scm.GIT.Capture(
167 ['config', '--local', '--get-regexp', r'remote.*.url'],
168 cwd=checkout_path)
169 # Get the second token of the first line of the log.
170 return log.splitlines()[0].split(' ', 1)[1]
171
smut@google.comd33eab32014-07-07 19:35:18 +0000172 def GetActualRemoteURL(self, options):
borenet@google.com88d10082014-03-21 17:24:48 +0000173 """Attempt to determine the remote URL for this SCMWrapper."""
smut@google.comd33eab32014-07-07 19:35:18 +0000174 # Git
borenet@google.combda475e2014-03-24 19:04:45 +0000175 if os.path.exists(os.path.join(self.checkout_path, '.git')):
hinoka@chromium.orgfa2b9b42014-08-22 18:08:53 +0000176 actual_remote_url = self._get_first_remote_url(self.checkout_path)
borenet@google.com4e9be262014-04-08 19:40:30 +0000177
178 # If a cache_dir is used, obtain the actual remote URL from the cache.
179 if getattr(self, 'cache_dir', None):
borenet@google.com46d09f62014-04-10 18:50:23 +0000180 url, _ = gclient_utils.SplitUrlRevision(self.url)
181 mirror = git_cache.Mirror(url)
szager@chromium.org848fd492014-04-09 19:06:44 +0000182 if (mirror.exists() and mirror.mirror_path.replace('\\', '/') ==
borenet@google.com4e9be262014-04-08 19:40:30 +0000183 actual_remote_url.replace('\\', '/')):
hinoka@chromium.orgfa2b9b42014-08-22 18:08:53 +0000184 actual_remote_url = self._get_first_remote_url(mirror.mirror_path)
borenet@google.com4e9be262014-04-08 19:40:30 +0000185 return actual_remote_url
186
187 # Svn
borenet@google.combda475e2014-03-24 19:04:45 +0000188 if os.path.exists(os.path.join(self.checkout_path, '.svn')):
borenet@google.com88d10082014-03-21 17:24:48 +0000189 return scm.SVN.CaptureLocalInfo([], self.checkout_path)['URL']
borenet@google.com88d10082014-03-21 17:24:48 +0000190 return None
191
borenet@google.com4e9be262014-04-08 19:40:30 +0000192 def DoesRemoteURLMatch(self, options):
borenet@google.com88d10082014-03-21 17:24:48 +0000193 """Determine whether the remote URL of this checkout is the expected URL."""
194 if not os.path.exists(self.checkout_path):
195 # A checkout which doesn't exist can't be broken.
196 return True
197
smut@google.comd33eab32014-07-07 19:35:18 +0000198 actual_remote_url = self.GetActualRemoteURL(options)
borenet@google.com88d10082014-03-21 17:24:48 +0000199 if actual_remote_url:
borenet@google.com8156c9f2014-04-01 16:41:36 +0000200 return (gclient_utils.SplitUrlRevision(actual_remote_url)[0].rstrip('/')
201 == gclient_utils.SplitUrlRevision(self.url)[0].rstrip('/'))
borenet@google.com88d10082014-03-21 17:24:48 +0000202 else:
203 # This may occur if the self.checkout_path exists but does not contain a
204 # valid git or svn checkout.
205 return False
206
borenet@google.comb09097a2014-04-09 19:09:08 +0000207 def _DeleteOrMove(self, force):
208 """Delete the checkout directory or move it out of the way.
209
210 Args:
211 force: bool; if True, delete the directory. Otherwise, just move it.
212 """
borenet@google.comb2256212014-05-07 20:57:28 +0000213 if force and os.environ.get('CHROME_HEADLESS') == '1':
214 self.Print('_____ Conflicting directory found in %s. Removing.'
215 % self.checkout_path)
216 gclient_utils.AddWarning('Conflicting directory %s deleted.'
217 % self.checkout_path)
218 gclient_utils.rmtree(self.checkout_path)
219 else:
220 bad_scm_dir = os.path.join(self._root_dir, '_bad_scm',
221 os.path.dirname(self.relpath))
222
223 try:
224 os.makedirs(bad_scm_dir)
225 except OSError as e:
226 if e.errno != errno.EEXIST:
227 raise
228
229 dest_path = tempfile.mkdtemp(
230 prefix=os.path.basename(self.relpath),
231 dir=bad_scm_dir)
232 self.Print('_____ Conflicting directory found in %s. Moving to %s.'
233 % (self.checkout_path, dest_path))
234 gclient_utils.AddWarning('Conflicting directory %s moved to %s.'
235 % (self.checkout_path, dest_path))
236 shutil.move(self.checkout_path, dest_path)
borenet@google.comb09097a2014-04-09 19:09:08 +0000237
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000238
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000239class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000240 """Wrapper for Git"""
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000241 name = 'git'
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000242 remote = 'origin'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000243
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000244 cache_dir = None
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000245
szager@chromium.org848fd492014-04-09 19:06:44 +0000246 def __init__(self, url=None, *args):
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000247 """Removes 'git+' fake prefix from git URL."""
248 if url.startswith('git+http://') or url.startswith('git+https://'):
249 url = url[4:]
szager@chromium.org848fd492014-04-09 19:06:44 +0000250 SCMWrapper.__init__(self, url, *args)
251 filter_kwargs = { 'time_throttle': 1, 'out_fh': self.out_fh }
252 if self.out_cb:
253 filter_kwargs['predicate'] = self.out_cb
254 self.filter = gclient_utils.GitFilter(**filter_kwargs)
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000255
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000256 @staticmethod
257 def BinaryExists():
258 """Returns true if the command exists."""
259 try:
260 # We assume git is newer than 1.7. See: crbug.com/114483
261 result, version = scm.GIT.AssertVersion('1.7')
262 if not result:
263 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
264 return result
265 except OSError:
266 return False
267
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000268 def GetCheckoutRoot(self):
269 return scm.GIT.GetCheckoutRoot(self.checkout_path)
270
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000271 def GetRevisionDate(self, _revision):
floitsch@google.comeaab7842011-04-28 09:07:58 +0000272 """Returns the given revision's date in ISO-8601 format (which contains the
273 time zone)."""
274 # TODO(floitsch): get the time-stamp of the given revision and not just the
275 # time-stamp of the currently checked out revision.
276 return self._Capture(['log', '-n', '1', '--format=%ai'])
277
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000278 @staticmethod
279 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000280 """'Cleanup' the repo.
281
282 There's no real git equivalent for the svn cleanup command, do a no-op.
283 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000284
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000285 def diff(self, options, _args, _file_list):
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000286 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000287 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000288
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000289 def pack(self, _options, _args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000290 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000291 repository.
292
293 The patch file is generated from a diff of the merge base of HEAD and
294 its upstream branch.
295 """
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000296 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000297 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000298 ['git', 'diff', merge_base],
299 cwd=self.checkout_path,
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000300 filter_fn=GitDiffFilterer(self.relpath, print_func=self.Print).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000301
smut@google.comd33eab32014-07-07 19:35:18 +0000302 def _FetchAndReset(self, revision, file_list, options):
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000303 """Equivalent to git fetch; git reset."""
304 quiet = []
305 if not options.verbose:
306 quiet = ['--quiet']
307 self._UpdateBranchHeads(options, fetch=False)
308
dnj@chromium.org680f2172014-06-25 00:39:32 +0000309 self._Fetch(options, prune=True, quiet=options.verbose)
smut@google.comd33eab32014-07-07 19:35:18 +0000310 self._Run(['reset', '--hard', revision] + quiet, options)
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000311 if file_list is not None:
312 files = self._Capture(['ls-files']).splitlines()
313 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
314
szager@chromium.org8a139702014-06-20 15:55:01 +0000315 def _DisableHooks(self):
316 hook_dir = os.path.join(self.checkout_path, '.git', 'hooks')
317 if not os.path.isdir(hook_dir):
318 return
319 for f in os.listdir(hook_dir):
320 if not f.endswith('.sample') and not f.endswith('.disabled'):
primiano@chromium.org41265562015-04-08 09:14:46 +0000321 disabled_hook_path = os.path.join(hook_dir, f + '.disabled')
322 if os.path.exists(disabled_hook_path):
323 os.remove(disabled_hook_path)
324 os.rename(os.path.join(hook_dir, f), disabled_hook_path)
szager@chromium.org8a139702014-06-20 15:55:01 +0000325
msb@chromium.orge28e4982009-09-25 20:51:45 +0000326 def update(self, options, args, file_list):
327 """Runs git to update or transparently checkout the working copy.
328
329 All updated files will be appended to file_list.
330
331 Raises:
332 Error: if can't get URL for relative path.
333 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000334 if args:
335 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
336
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000337 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000338
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000339 # If a dependency is not pinned, track the default remote branch.
smut@google.comd33eab32014-07-07 19:35:18 +0000340 default_rev = 'refs/remotes/%s/master' % self.remote
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000341 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000342 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000343 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000344 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000345 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000346 # Override the revision number.
347 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000348 if revision == 'unmanaged':
romain.pokrzywka@gmail.com483a0ba2014-05-30 00:06:07 +0000349 # Check again for a revision in case an initial ref was specified
350 # in the url, for example bla.git@refs/heads/custombranch
351 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000352 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000353 if not revision:
354 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000355
szager@chromium.org8a139702014-06-20 15:55:01 +0000356 if managed:
357 self._DisableHooks()
358
floitsch@google.comeaab7842011-04-28 09:07:58 +0000359 if gclient_utils.IsDateRevision(revision):
360 # Date-revisions only work on git-repositories if the reflog hasn't
361 # expired yet. Use rev-list to get the corresponding revision.
362 # git rev-list -n 1 --before='time-stamp' branchname
363 if options.transitive:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000364 self.Print('Warning: --transitive only works for SVN repositories.')
floitsch@google.comeaab7842011-04-28 09:07:58 +0000365 revision = default_rev
366
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000367 rev_str = ' at %s' % revision
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000368 files = [] if file_list is not None else None
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000369
370 printed_path = False
371 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000372 if options.verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000373 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000374 verbose = ['--verbose']
375 printed_path = True
376
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000377 remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
378 if remote_ref:
smut@google.comd33eab32014-07-07 19:35:18 +0000379 # Rewrite remote refs to their local equivalents.
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000380 revision = ''.join(remote_ref)
381 rev_type = "branch"
382 elif revision.startswith('refs/'):
383 # Local branch? We probably don't want to support, since DEPS should
384 # always specify branches as they are in the upstream repo.
smut@google.comd33eab32014-07-07 19:35:18 +0000385 rev_type = "branch"
386 else:
387 # hash is also a tag, only make a distinction at checkout
388 rev_type = "hash"
389
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000390 mirror = self._GetMirror(url, options)
391 if mirror:
392 url = mirror.mirror_path
393
primiano@chromium.org1c127382015-02-17 11:15:40 +0000394 # If we are going to introduce a new project, there is a possibility that
395 # we are syncing back to a state where the project was originally a
396 # sub-project rolled by DEPS (realistic case: crossing the Blink merge point
397 # syncing backwards, when Blink was a DEPS entry and not part of src.git).
398 # In such case, we might have a backup of the former .git folder, which can
399 # be used to avoid re-fetching the entire repo again (useful for bisects).
400 backup_dir = self.GetGitBackupDirPath()
401 target_dir = os.path.join(self.checkout_path, '.git')
402 if os.path.exists(backup_dir) and not os.path.exists(target_dir):
403 gclient_utils.safe_makedirs(self.checkout_path)
404 os.rename(backup_dir, target_dir)
405 # Reset to a clean state
406 self._Run(['reset', '--hard', 'HEAD'], options)
407
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000408 if (not os.path.exists(self.checkout_path) or
409 (os.path.isdir(self.checkout_path) and
410 not os.path.exists(os.path.join(self.checkout_path, '.git')))):
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000411 if mirror:
412 self._UpdateMirror(mirror, options)
borenet@google.com90fe58b2014-05-01 18:22:00 +0000413 try:
smut@google.comd33eab32014-07-07 19:35:18 +0000414 self._Clone(revision, url, options)
borenet@google.com90fe58b2014-05-01 18:22:00 +0000415 except subprocess2.CalledProcessError:
416 self._DeleteOrMove(options.force)
smut@google.comd33eab32014-07-07 19:35:18 +0000417 self._Clone(revision, url, options)
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000418 if file_list is not None:
419 files = self._Capture(['ls-files']).splitlines()
420 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000421 if not verbose:
422 # Make the output a little prettier. It's nice to have some whitespace
423 # between projects when cloning.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000424 self.Print('')
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000425 return self._Capture(['rev-parse', '--verify', 'HEAD'])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000426
szager@chromium.org3dc5cb72014-06-17 15:06:05 +0000427 if not managed:
428 self._UpdateBranchHeads(options, fetch=False)
429 self.Print('________ unmanaged solution; skipping %s' % self.relpath)
430 return self._Capture(['rev-parse', '--verify', 'HEAD'])
431
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000432 if mirror:
433 self._UpdateMirror(mirror, options)
434
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000435 # See if the url has changed (the unittests use git://foo for the url, let
436 # that through).
437 current_url = self._Capture(['config', 'remote.%s.url' % self.remote])
438 return_early = False
439 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
440 # unit test pass. (and update the comment above)
441 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
442 # This allows devs to use experimental repos which have a different url
443 # but whose branch(s) are the same as official repos.
borenet@google.comb09097a2014-04-09 19:09:08 +0000444 if (current_url.rstrip('/') != url.rstrip('/') and
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000445 url != 'git://foo' and
446 subprocess2.capture(
447 ['git', 'config', 'remote.%s.gclient-auto-fix-url' % self.remote],
448 cwd=self.checkout_path).strip() != 'False'):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000449 self.Print('_____ switching %s to a new upstream' % self.relpath)
iannucci@chromium.org78514212014-08-20 23:08:00 +0000450 if not (options.force or options.reset):
451 # Make sure it's clean
452 self._CheckClean(rev_str)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000453 # Switch over to the new upstream
454 self._Run(['remote', 'set-url', self.remote, url], options)
smut@google.comd33eab32014-07-07 19:35:18 +0000455 self._FetchAndReset(revision, file_list, options)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000456 return_early = True
457
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000458 if return_early:
459 return self._Capture(['rev-parse', '--verify', 'HEAD'])
460
msb@chromium.org5bde4852009-12-14 16:47:12 +0000461 cur_branch = self._GetCurrentBranch()
462
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000463 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000464 # 0) HEAD is detached. Probably from our initial clone.
465 # - make sure HEAD is contained by a named ref, then update.
466 # Cases 1-4. HEAD is a branch.
467 # 1) current branch is not tracking a remote branch (could be git-svn)
468 # - try to rebase onto the new hash or branch
469 # 2) current branch is tracking a remote branch with local committed
470 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000471 # - rebase those changes on top of the hash
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000472 # 3) current branch is tracking a remote branch w/or w/out changes, and
473 # no DEPS switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000474 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000475 # 4) current branch is tracking a remote branch, but DEPS switches to a
476 # different remote branch, and
477 # a) current branch has no local changes, and --force:
478 # - checkout new branch
479 # b) current branch has local changes, and --force and --reset:
480 # - checkout new branch
481 # c) otherwise exit
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000482
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000483 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
484 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000485 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
486 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000487 if cur_branch is None:
488 upstream_branch = None
489 current_type = "detached"
490 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000491 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000492 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
493 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
494 current_type = "hash"
495 logging.debug("Current branch is not tracking an upstream (remote)"
496 " branch.")
497 elif upstream_branch.startswith('refs/remotes'):
498 current_type = "branch"
499 else:
500 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000501
smut@google.comd33eab32014-07-07 19:35:18 +0000502 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000503 # Update the remotes first so we have all the refs.
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000504 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000505 cwd=self.checkout_path)
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000506 if verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000507 self.Print(remote_output)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000508
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000509 self._UpdateBranchHeads(options, fetch=True)
510
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000511 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000512 if options.force or options.reset:
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000513 target = 'HEAD'
514 if options.upstream and upstream_branch:
515 target = upstream_branch
516 self._Run(['reset', '--hard', target], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000517
msb@chromium.org786fb682010-06-02 15:16:23 +0000518 if current_type == 'detached':
519 # case 0
520 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000521 self._CheckDetachedHead(rev_str, options)
smut@google.comd33eab32014-07-07 19:35:18 +0000522 if self._Capture(['rev-list', '-n', '1', 'HEAD']) == revision:
szager@chromium.org848fd492014-04-09 19:06:44 +0000523 self.Print('Up-to-date; skipping checkout.')
524 else:
vadimsh@chromium.org2b7d3ed2014-06-20 18:15:37 +0000525 # 'git checkout' may need to overwrite existing untracked files. Allow
526 # it only when nuclear options are enabled.
dnj@chromium.orgbb424c02014-06-23 22:42:51 +0000527 self._Checkout(
528 options,
529 revision,
530 force=(options.force and options.delete_unversioned_trees),
531 quiet=True,
532 )
msb@chromium.org786fb682010-06-02 15:16:23 +0000533 if not printed_path:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000534 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
msb@chromium.org786fb682010-06-02 15:16:23 +0000535 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000536 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000537 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000538 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000539 self._AttemptRebase(upstream_branch, files, options,
smut@google.comd33eab32014-07-07 19:35:18 +0000540 newbase=revision, printed_path=printed_path,
541 merge=options.merge)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000542 printed_path = True
543 else:
544 # Can't find a merge-base since we don't know our upstream. That makes
545 # this command VERY likely to produce a rebase failure. For now we
546 # assume origin is our upstream since that's what the old behavior was.
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000547 upstream_branch = self.remote
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000548 if options.revision or deps_revision:
smut@google.comd33eab32014-07-07 19:35:18 +0000549 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000550 self._AttemptRebase(upstream_branch, files, options,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000551 printed_path=printed_path, merge=options.merge)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000552 printed_path = True
smut@google.comd33eab32014-07-07 19:35:18 +0000553 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000554 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000555 self._AttemptRebase(upstream_branch, files, options,
smut@google.comd33eab32014-07-07 19:35:18 +0000556 newbase=revision, printed_path=printed_path,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000557 merge=options.merge)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000558 printed_path = True
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000559 elif remote_ref and ''.join(remote_ref) != upstream_branch:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000560 # case 4
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000561 new_base = ''.join(remote_ref)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000562 if not printed_path:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000563 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000564 switch_error = ("Could not switch upstream branch from %s to %s\n"
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000565 % (upstream_branch, new_base) +
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000566 "Please use --force or merge or rebase manually:\n" +
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000567 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
568 "OR git checkout -b <some new branch> %s" % new_base)
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000569 force_switch = False
570 if options.force:
571 try:
572 self._CheckClean(rev_str)
573 # case 4a
574 force_switch = True
575 except gclient_utils.Error as e:
576 if options.reset:
577 # case 4b
578 force_switch = True
579 else:
580 switch_error = '%s\n%s' % (e.message, switch_error)
581 if force_switch:
582 self.Print("Switching upstream branch from %s to %s" %
583 (upstream_branch, new_base))
584 switch_branch = 'gclient_' + remote_ref[1]
585 self._Capture(['branch', '-f', switch_branch, new_base])
586 self._Checkout(options, switch_branch, force=True, quiet=True)
587 else:
588 # case 4c
589 raise gclient_utils.Error(switch_error)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000590 else:
591 # case 3 - the default case
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000592 if files is not None:
593 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000594 if verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000595 self.Print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000596 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000597 merge_args = ['merge']
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000598 if options.merge:
599 merge_args.append('--ff')
600 else:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000601 merge_args.append('--ff-only')
602 merge_args.append(upstream_branch)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000603 merge_output = self._Capture(merge_args)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000604 except subprocess2.CalledProcessError as e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000605 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000606 files = []
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000607 if not printed_path:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000608 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000609 printed_path = True
610 while True:
dnj@chromium.org5b23e872015-02-20 21:25:57 +0000611 if not options.auto_rebase:
612 try:
613 action = self._AskForData(
614 'Cannot %s, attempt to rebase? '
615 '(y)es / (q)uit / (s)kip : ' %
616 ('merge' if options.merge else 'fast-forward merge'),
617 options)
618 except ValueError:
619 raise gclient_utils.Error('Invalid Character')
620 if options.auto_rebase or re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000621 self._AttemptRebase(upstream_branch, files, options,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000622 printed_path=printed_path, merge=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000623 printed_path = True
624 break
625 elif re.match(r'quit|q', action, re.I):
626 raise gclient_utils.Error("Can't fast-forward, please merge or "
627 "rebase manually.\n"
628 "cd %s && git " % self.checkout_path
629 + "rebase %s" % upstream_branch)
630 elif re.match(r'skip|s', action, re.I):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000631 self.Print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000632 return
633 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000634 self.Print('Input not recognized')
smut@google.com27c9c8a2014-09-11 19:57:55 +0000635 elif re.match("error: Your local changes to '.*' would be "
636 "overwritten by merge. Aborting.\nPlease, commit your "
637 "changes or stash them before you can merge.\n",
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000638 e.stderr):
639 if not printed_path:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000640 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000641 printed_path = True
642 raise gclient_utils.Error(e.stderr)
643 else:
644 # Some other problem happened with the merge
645 logging.error("Error during fast-forward merge in %s!" % self.relpath)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000646 self.Print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000647 raise
648 else:
649 # Fast-forward merge was successful
650 if not re.match('Already up-to-date.', merge_output) or verbose:
651 if not printed_path:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000652 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000653 printed_path = True
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000654 self.Print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000655 if not verbose:
656 # Make the output a little prettier. It's nice to have some
657 # whitespace between projects when syncing.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000658 self.Print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000659
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000660 if file_list is not None:
661 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000662
663 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000664 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000665 raise gclient_utils.Error('\n____ %s%s\n'
666 '\nConflict while rebasing this branch.\n'
667 'Fix the conflict and run gclient again.\n'
668 'See man git-rebase for details.\n'
669 % (self.relpath, rev_str))
670
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000671 if verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000672 self.Print('Checked out revision %s' % self.revinfo(options, (), None),
673 timestamp=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000674
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000675 # If --reset and --delete_unversioned_trees are specified, remove any
676 # untracked directories.
677 if options.reset and options.delete_unversioned_trees:
678 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
679 # merge-base by default), so doesn't include untracked files. So we use
680 # 'git ls-files --directory --others --exclude-standard' here directly.
681 paths = scm.GIT.Capture(
682 ['ls-files', '--directory', '--others', '--exclude-standard'],
683 self.checkout_path)
684 for path in (p for p in paths.splitlines() if p.endswith('/')):
685 full_path = os.path.join(self.checkout_path, path)
686 if not os.path.islink(full_path):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000687 self.Print('_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000688 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000689
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000690 return self._Capture(['rev-parse', '--verify', 'HEAD'])
691
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000692
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000693 def revert(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000694 """Reverts local modifications.
695
696 All reverted files will be appended to file_list.
697 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000698 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000699 # revert won't work if the directory doesn't exist. It needs to
700 # checkout instead.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000701 self.Print('_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000702 # Don't reuse the args.
703 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000704
705 default_rev = "refs/heads/master"
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000706 if options.upstream:
707 if self._GetCurrentBranch():
708 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
709 default_rev = upstream_branch or default_rev
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000710 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000711 if not deps_revision:
712 deps_revision = default_rev
smut@google.comd33eab32014-07-07 19:35:18 +0000713 if deps_revision.startswith('refs/heads/'):
714 deps_revision = deps_revision.replace('refs/heads/', self.remote + '/')
715 deps_revision = self.GetUsableRev(deps_revision, options)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000716
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000717 if file_list is not None:
718 files = self._Capture(['diff', deps_revision, '--name-only']).split()
719
maruel@chromium.org37e89872010-09-07 16:11:33 +0000720 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000721 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000722
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000723 if file_list is not None:
724 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
725
726 def revinfo(self, _options, _args, _file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000727 """Returns revision"""
728 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000729
msb@chromium.orge28e4982009-09-25 20:51:45 +0000730 def runhooks(self, options, args, file_list):
731 self.status(options, args, file_list)
732
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000733 def status(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000734 """Display status information."""
735 if not os.path.isdir(self.checkout_path):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000736 self.Print('________ couldn\'t run status in %s:\n'
737 'The directory does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000738 else:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000739 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000740 self._Run(['diff', '--name-status', merge_base], options,
741 stdout=self.out_fh)
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000742 if file_list is not None:
743 files = self._Capture(['diff', '--name-only', merge_base]).split()
744 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000745
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000746 def GetUsableRev(self, rev, options):
747 """Finds a useful revision for this repository.
748
749 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
750 will be called on the source."""
751 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000752 if not os.path.isdir(self.checkout_path):
753 raise gclient_utils.Error(
754 ( 'We could not find a valid hash for safesync_url response "%s".\n'
755 'Safesync URLs with a git checkout currently require the repo to\n'
756 'be cloned without a safesync_url before adding the safesync_url.\n'
757 'For more info, see: '
758 'http://code.google.com/p/chromium/wiki/UsingNewGit'
759 '#Initial_checkout' ) % rev)
760 elif rev.isdigit() and len(rev) < 7:
761 # Handles an SVN rev. As an optimization, only verify an SVN revision as
762 # [0-9]{1,6} for now to avoid making a network request.
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000763 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000764 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
765 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000766 try:
767 logging.debug('Looking for git-svn configuration optimizations.')
768 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
769 cwd=self.checkout_path):
dnj@chromium.org680f2172014-06-25 00:39:32 +0000770 self._Fetch(options)
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000771 except subprocess2.CalledProcessError:
772 logging.debug('git config --get svn-remote.svn.fetch failed, '
773 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000774 if options.verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000775 self.Print('Running git svn fetch. This might take a while.\n')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000776 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000777 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000778 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
779 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000780 except gclient_utils.Error, e:
781 sha1 = e.message
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000782 self.Print('Warning: Could not find a git revision with accurate\n'
szager@google.com312a6a42012-10-11 21:19:42 +0000783 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
784 'the closest sane git revision, which is:\n'
785 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000786 if not sha1:
787 raise gclient_utils.Error(
788 ( 'It appears that either your git-svn remote is incorrectly\n'
789 'configured or the revision in your safesync_url is\n'
790 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
791 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000792 else:
793 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
794 sha1 = rev
795 else:
796 # May exist in origin, but we don't have it yet, so fetch and look
797 # again.
dnj@chromium.org680f2172014-06-25 00:39:32 +0000798 self._Fetch(options)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000799 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
800 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000801
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000802 if not sha1:
803 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000804 ( 'We could not find a valid hash for safesync_url response "%s".\n'
805 'Safesync URLs with a git checkout currently require a git-svn\n'
806 'remote or a safesync_url that provides git sha1s. Please add a\n'
807 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000808 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000809 '#Initial_checkout' ) % rev)
810
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000811 return sha1
812
msb@chromium.orge6f78352010-01-13 17:05:33 +0000813 def FullUrlForRelativeUrl(self, url):
814 # Strip from last '/'
815 # Equivalent to unix basename
816 base_url = self.url
817 return base_url[:base_url.rfind('/')] + url
818
primiano@chromium.org1c127382015-02-17 11:15:40 +0000819 def GetGitBackupDirPath(self):
820 """Returns the path where the .git folder for the current project can be
821 staged/restored. Use case: subproject moved from DEPS <-> outer project."""
822 return os.path.join(self._root_dir,
823 'old_' + self.relpath.replace(os.sep, '_')) + '.git'
824
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000825 def _GetMirror(self, url, options):
826 """Get a git_cache.Mirror object for the argument url."""
827 if not git_cache.Mirror.GetCachePath():
828 return None
hinoka@google.comb1b54572014-04-16 22:29:23 +0000829 mirror_kwargs = {
830 'print_func': self.filter,
831 'refs': []
832 }
hinoka@google.comb1b54572014-04-16 22:29:23 +0000833 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
834 mirror_kwargs['refs'].append('refs/branch-heads/*')
szager@chromium.org8d3348f2014-08-19 22:49:16 +0000835 if hasattr(options, 'with_tags') and options.with_tags:
836 mirror_kwargs['refs'].append('refs/tags/*')
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000837 return git_cache.Mirror(url, **mirror_kwargs)
838
839 @staticmethod
840 def _UpdateMirror(mirror, options):
841 """Update a git mirror by fetching the latest commits from the remote."""
szager@chromium.org3ec84f62014-08-22 21:00:22 +0000842 if getattr(options, 'shallow', False):
hinoka@chromium.org46b87412014-05-15 00:42:05 +0000843 # HACK(hinoka): These repositories should be super shallow.
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000844 if 'flash' in mirror.url:
hinoka@chromium.org46b87412014-05-15 00:42:05 +0000845 depth = 10
846 else:
847 depth = 10000
848 else:
849 depth = None
e.hakkinen@samsung.come8bc1aa2015-04-08 08:00:37 +0000850 mirror.populate(verbose=options.verbose,
851 bootstrap=not getattr(options, 'no_bootstrap', False),
852 depth=depth,
vadimsh@chromium.org3fd325b2014-08-22 23:56:49 +0000853 ignore_lock=getattr(options, 'ignore_locks', False))
szager@chromium.org848fd492014-04-09 19:06:44 +0000854 mirror.unlock()
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000855
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000856 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000857 """Clone a git repository from the given URL.
858
msb@chromium.org786fb682010-06-02 15:16:23 +0000859 Once we've cloned the repo, we checkout a working branch if the specified
860 revision is a branch head. If it is a tag or a specific commit, then we
861 leave HEAD detached as it makes future updates simpler -- in this case the
862 user should first create a new branch or switch to an existing branch before
863 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000864 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000865 # git clone doesn't seem to insert a newline properly before printing
866 # to stdout
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000867 self.Print('')
szager@chromium.orgf1d73eb2014-04-21 17:07:04 +0000868 cfg = gclient_utils.DefaultIndexPackConfig(url)
szager@chromium.org8a139702014-06-20 15:55:01 +0000869 clone_cmd = cfg + ['clone', '--no-checkout', '--progress']
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000870 if self.cache_dir:
871 clone_cmd.append('--shared')
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000872 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000873 clone_cmd.append('--verbose')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000874 clone_cmd.append(url)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000875 # If the parent directory does not exist, Git clone on Windows will not
876 # create it, so we need to do it manually.
877 parent_dir = os.path.dirname(self.checkout_path)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000878 gclient_utils.safe_makedirs(parent_dir)
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000879
880 template_dir = None
881 if hasattr(options, 'no_history') and options.no_history:
882 if gclient_utils.IsGitSha(revision):
883 # In the case of a subproject, the pinned sha is not necessarily the
884 # head of the remote branch (so we can't just use --depth=N). Instead,
885 # we tell git to fetch all the remote objects from SHA..HEAD by means of
886 # a template git dir which has a 'shallow' file pointing to the sha.
887 template_dir = tempfile.mkdtemp(
888 prefix='_gclient_gittmp_%s' % os.path.basename(self.checkout_path),
889 dir=parent_dir)
890 self._Run(['init', '--bare', template_dir], options, cwd=self._root_dir)
891 with open(os.path.join(template_dir, 'shallow'), 'w') as template_file:
892 template_file.write(revision)
893 clone_cmd.append('--template=' + template_dir)
894 else:
895 # Otherwise, we're just interested in the HEAD. Just use --depth.
896 clone_cmd.append('--depth=1')
897
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000898 tmp_dir = tempfile.mkdtemp(
899 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
900 dir=parent_dir)
901 try:
902 clone_cmd.append(tmp_dir)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000903 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000904 gclient_utils.safe_makedirs(self.checkout_path)
cyrille@nnamrak.orgef509e42013-09-20 13:19:08 +0000905 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
906 os.path.join(self.checkout_path, '.git'))
zty@chromium.org6279e8a2014-02-13 01:45:25 +0000907 except:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000908 traceback.print_exc(file=self.out_fh)
zty@chromium.org6279e8a2014-02-13 01:45:25 +0000909 raise
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000910 finally:
911 if os.listdir(tmp_dir):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000912 self.Print('_____ removing non-empty tmp dir %s' % tmp_dir)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000913 gclient_utils.rmtree(tmp_dir)
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000914 if template_dir:
915 gclient_utils.rmtree(template_dir)
mmoss@chromium.org1a6bec02014-06-02 21:53:29 +0000916 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000917 remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
918 self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
romain.pokrzywka@gmail.com483a0ba2014-05-30 00:06:07 +0000919 if self._GetCurrentBranch() is None:
msb@chromium.org786fb682010-06-02 15:16:23 +0000920 # Squelch git's very verbose detached HEAD warning and use our own
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000921 self.Print(
smut@google.comd33eab32014-07-07 19:35:18 +0000922 ('Checked out %s to a detached HEAD. Before making any commits\n'
923 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
924 'an existing branch or use \'git checkout %s -b <branch>\' to\n'
925 'create a new branch for your work.') % (revision, self.remote))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000926
szager@chromium.org6cd41b62014-04-21 23:55:22 +0000927 def _AskForData(self, prompt, options):
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000928 if options.jobs > 1:
szager@chromium.org6cd41b62014-04-21 23:55:22 +0000929 self.Print(prompt)
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000930 raise gclient_utils.Error("Background task requires input. Rerun "
931 "gclient with --jobs=1 so that\n"
932 "interaction is possible.")
933 try:
934 return raw_input(prompt)
935 except KeyboardInterrupt:
936 # Hide the exception.
937 sys.exit(1)
938
939
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000940 def _AttemptRebase(self, upstream, files, options, newbase=None,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000941 branch=None, printed_path=False, merge=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000942 """Attempt to rebase onto either upstream or, if specified, newbase."""
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000943 if files is not None:
944 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000945 revision = upstream
946 if newbase:
947 revision = newbase
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000948 action = 'merge' if merge else 'rebase'
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000949 if not printed_path:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000950 self.Print('_____ %s : Attempting %s onto %s...' % (
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000951 self.relpath, action, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000952 printed_path = True
953 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000954 self.Print('Attempting %s onto %s...' % (action, revision))
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000955
956 if merge:
957 merge_output = self._Capture(['merge', revision])
958 if options.verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000959 self.Print(merge_output)
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000960 return
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000961
962 # Build the rebase command here using the args
963 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
964 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000965 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000966 rebase_cmd.append('--verbose')
967 if newbase:
968 rebase_cmd.extend(['--onto', newbase])
969 rebase_cmd.append(upstream)
970 if branch:
971 rebase_cmd.append(branch)
972
973 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000974 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000975 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000976 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
977 re.match(r'cannot rebase: your index contains uncommitted changes',
978 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000979 while True:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000980 rebase_action = self._AskForData(
maruel@chromium.org90541732011-04-01 17:54:18 +0000981 'Cannot rebase because of unstaged changes.\n'
982 '\'git reset --hard HEAD\' ?\n'
983 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000984 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000985 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000986 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000987 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000988 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000989 break
990 elif re.match(r'quit|q', rebase_action, re.I):
991 raise gclient_utils.Error("Please merge or rebase manually\n"
992 "cd %s && git " % self.checkout_path
993 + "%s" % ' '.join(rebase_cmd))
994 elif re.match(r'show|s', rebase_action, re.I):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000995 self.Print('%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000996 continue
997 else:
998 gclient_utils.Error("Input not recognized")
999 continue
1000 elif re.search(r'^CONFLICT', e.stdout, re.M):
1001 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
1002 "Fix the conflict and run gclient again.\n"
1003 "See 'man git-rebase' for details.\n")
1004 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001005 self.Print(e.stdout.strip())
1006 self.Print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +00001007 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
1008 "manually.\ncd %s && git " %
1009 self.checkout_path
1010 + "%s" % ' '.join(rebase_cmd))
1011
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001012 self.Print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +00001013 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +00001014 # Make the output a little prettier. It's nice to have some
1015 # whitespace between projects when syncing.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001016 self.Print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +00001017
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001018 @staticmethod
1019 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +00001020 (ok, current_version) = scm.GIT.AssertVersion(min_version)
1021 if not ok:
1022 raise gclient_utils.Error('git version %s < minimum required %s' %
1023 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +00001024
msb@chromium.org786fb682010-06-02 15:16:23 +00001025 def _IsRebasing(self):
1026 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
1027 # have a plumbing command to determine whether a rebase is in progress, so
1028 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
1029 g = os.path.join(self.checkout_path, '.git')
1030 return (
1031 os.path.isdir(os.path.join(g, "rebase-merge")) or
1032 os.path.isdir(os.path.join(g, "rebase-apply")))
1033
1034 def _CheckClean(self, rev_str):
1035 # Make sure the tree is clean; see git-rebase.sh for reference
1036 try:
1037 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +00001038 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001039 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001040 raise gclient_utils.Error('\n____ %s%s\n'
1041 '\tYou have unstaged changes.\n'
1042 '\tPlease commit, stash, or reset.\n'
1043 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +00001044 try:
1045 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
smut@google.com27c9c8a2014-09-11 19:57:55 +00001046 '--ignore-submodules', 'HEAD', '--'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +00001047 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001048 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001049 raise gclient_utils.Error('\n____ %s%s\n'
1050 '\tYour index contains uncommitted changes\n'
1051 '\tPlease commit, stash, or reset.\n'
1052 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +00001053
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001054 def _CheckDetachedHead(self, rev_str, _options):
msb@chromium.org786fb682010-06-02 15:16:23 +00001055 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
1056 # reference by a commit). If not, error out -- most likely a rebase is
1057 # in progress, try to detect so we can give a better error.
1058 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +00001059 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
1060 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001061 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +00001062 # Commit is not contained by any rev. See if the user is rebasing:
1063 if self._IsRebasing():
1064 # Punt to the user
1065 raise gclient_utils.Error('\n____ %s%s\n'
1066 '\tAlready in a conflict, i.e. (no branch).\n'
1067 '\tFix the conflict and run gclient again.\n'
1068 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
1069 '\tSee man git-rebase for details.\n'
1070 % (self.relpath, rev_str))
1071 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001072 name = ('saved-by-gclient-' +
1073 self._Capture(['rev-parse', '--short', 'HEAD']))
mmoss@chromium.org77bd7362013-09-25 23:46:14 +00001074 self._Capture(['branch', '-f', name])
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001075 self.Print('_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +00001076 name)
msb@chromium.org786fb682010-06-02 15:16:23 +00001077
msb@chromium.org5bde4852009-12-14 16:47:12 +00001078 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +00001079 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001080 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +00001081 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +00001082 return None
1083 return branch
1084
borenet@google.comc3e09d22014-04-10 13:58:18 +00001085 def _Capture(self, args, **kwargs):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001086 kwargs.setdefault('cwd', self.checkout_path)
1087 kwargs.setdefault('stderr', subprocess2.PIPE)
szager@chromium.org6d8115d2014-04-23 20:59:23 +00001088 env = scm.GIT.ApplyEnvVars(kwargs)
1089 return subprocess2.check_output(['git'] + args, env=env, **kwargs).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001090
dnj@chromium.orgbb424c02014-06-23 22:42:51 +00001091 def _Checkout(self, options, ref, force=False, quiet=None):
1092 """Performs a 'git-checkout' operation.
1093
1094 Args:
1095 options: The configured option set
1096 ref: (str) The branch/commit to checkout
1097 quiet: (bool/None) Whether or not the checkout shoud pass '--quiet'; if
1098 'None', the behavior is inferred from 'options.verbose'.
1099 Returns: (str) The output of the checkout operation
1100 """
1101 if quiet is None:
1102 quiet = (not options.verbose)
1103 checkout_args = ['checkout']
1104 if force:
1105 checkout_args.append('--force')
1106 if quiet:
1107 checkout_args.append('--quiet')
1108 checkout_args.append(ref)
1109 return self._Capture(checkout_args)
1110
dnj@chromium.org680f2172014-06-25 00:39:32 +00001111 def _Fetch(self, options, remote=None, prune=False, quiet=False):
1112 cfg = gclient_utils.DefaultIndexPackConfig(self.url)
1113 fetch_cmd = cfg + [
1114 'fetch',
1115 remote or self.remote,
1116 ]
1117
1118 if prune:
1119 fetch_cmd.append('--prune')
1120 if options.verbose:
1121 fetch_cmd.append('--verbose')
1122 elif quiet:
1123 fetch_cmd.append('--quiet')
1124 self._Run(fetch_cmd, options, show_header=options.verbose, retry=True)
1125
1126 # Return the revision that was fetched; this will be stored in 'FETCH_HEAD'
1127 return self._Capture(['rev-parse', '--verify', 'FETCH_HEAD'])
1128
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001129 def _UpdateBranchHeads(self, options, fetch=False):
szager@chromium.org8d3348f2014-08-19 22:49:16 +00001130 """Adds, and optionally fetches, "branch-heads" and "tags" refspecs
1131 if requested."""
1132 need_fetch = fetch
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001133 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +00001134 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +00001135 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1136 '^\\+refs/branch-heads/\\*:.*$']
1137 self._Run(config_cmd, options)
szager@chromium.org8d3348f2014-08-19 22:49:16 +00001138 need_fetch = True
1139 if hasattr(options, 'with_tags') and options.with_tags:
1140 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
1141 '+refs/tags/*:refs/tags/*',
1142 '^\\+refs/tags/\\*:.*$']
1143 self._Run(config_cmd, options)
1144 need_fetch = True
1145 if fetch and need_fetch:
1146 self._Fetch(options)
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001147
dnj@chromium.org680f2172014-06-25 00:39:32 +00001148 def _Run(self, args, options, show_header=True, **kwargs):
1149 # Disable 'unused options' warning | pylint: disable=W0613
sbc@chromium.org2cd0b8e2014-09-22 21:17:59 +00001150 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001151 kwargs.setdefault('stdout', self.out_fh)
szager@chromium.org848fd492014-04-09 19:06:44 +00001152 kwargs['filter_fn'] = self.filter
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001153 kwargs.setdefault('print_stdout', False)
szager@chromium.org6d8115d2014-04-23 20:59:23 +00001154 env = scm.GIT.ApplyEnvVars(kwargs)
agable@chromium.org772efaf2014-04-01 02:35:44 +00001155 cmd = ['git'] + args
dnj@chromium.org680f2172014-06-25 00:39:32 +00001156 if show_header:
sbc@chromium.org2cd0b8e2014-09-22 21:17:59 +00001157 gclient_utils.CheckCallAndFilterAndHeader(cmd, env=env, **kwargs)
1158 else:
1159 gclient_utils.CheckCallAndFilter(cmd, env=env, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +00001160
1161
maruel@chromium.org55e724e2010-03-11 19:36:49 +00001162class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001163 """ Wrapper for SVN """
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001164 name = 'svn'
maruel@chromium.org79d62372015-06-01 18:50:55 +00001165 _PRINTED_DEPRECATION = False
1166
1167 _MESSAGE = (
1168 'Oh hai! You are using subversion. Chrome infra is eager to get rid of',
1169 'svn support so please switch to git.',
1170 'Tracking bug: http://crbug.com/475320',
1171 'Request a new git repository at: ',
sergiyb@chromium.orgecc37952015-06-02 09:36:43 +00001172 ' https://code.google.com/p/chromium/issues/entry?template=Infra-Git')
maruel@chromium.org79d62372015-06-01 18:50:55 +00001173
1174 def __init__(self, *args, **kwargs):
1175 super(SVNWrapper, self).__init__(*args, **kwargs)
sergiyb@chromium.orgecc37952015-06-02 09:36:43 +00001176 suppress_deprecated_notice = os.environ.get(
1177 'SUPPRESS_DEPRECATED_SVN_NOTICE', False)
1178 if not SVNWrapper._PRINTED_DEPRECATION and not suppress_deprecated_notice:
maruel@chromium.org79d62372015-06-01 18:50:55 +00001179 SVNWrapper._PRINTED_DEPRECATION = True
1180 sys.stderr.write('\n'.join(self._MESSAGE) + '\n')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001181
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +00001182 @staticmethod
1183 def BinaryExists():
1184 """Returns true if the command exists."""
1185 try:
1186 result, version = scm.SVN.AssertVersion('1.4')
1187 if not result:
1188 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1189 return result
1190 except OSError:
1191 return False
1192
xusydoc@chromium.org885a9602013-05-31 09:54:40 +00001193 def GetCheckoutRoot(self):
1194 return scm.SVN.GetCheckoutRoot(self.checkout_path)
1195
floitsch@google.comeaab7842011-04-28 09:07:58 +00001196 def GetRevisionDate(self, revision):
1197 """Returns the given revision's date in ISO-8601 format (which contains the
1198 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001199 date = scm.SVN.Capture(
1200 ['propget', '--revprop', 'svn:date', '-r', revision],
1201 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +00001202 return date.strip()
1203
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001204 def cleanup(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001205 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001206 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001207
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001208 def diff(self, options, args, _file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001209 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001210 if not os.path.isdir(self.checkout_path):
1211 raise gclient_utils.Error('Directory %s is not present.' %
1212 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001213 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001214
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001215 def pack(self, _options, args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001216 """Generates a patch file which can be applied to the root of the
1217 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001218 if not os.path.isdir(self.checkout_path):
1219 raise gclient_utils.Error('Directory %s is not present.' %
1220 self.checkout_path)
1221 gclient_utils.CheckCallAndFilter(
1222 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1223 cwd=self.checkout_path,
1224 print_stdout=False,
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001225 filter_fn=SvnDiffFilterer(self.relpath, print_func=self.Print).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00001226
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001227 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +00001228 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001229
1230 All updated files will be appended to file_list.
1231
1232 Raises:
1233 Error: if can't get URL for relative path.
1234 """
borenet@google.comb09097a2014-04-09 19:09:08 +00001235 # Only update if hg is not controlling the directory.
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001236 hg_path = os.path.join(self.checkout_path, '.hg')
1237 if os.path.exists(hg_path):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001238 self.Print('________ found .hg directory; skipping %s' % self.relpath)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001239 return
1240
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001241 if args:
1242 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1243
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001244 # revision is the revision to match. It is None if no revision is specified,
1245 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001246 url, revision = gclient_utils.SplitUrlRevision(self.url)
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +00001247 # Keep the original unpinned url for reference in case the repo is switched.
1248 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001249 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001250 if options.revision:
1251 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001252 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001253 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001254 if revision != 'unmanaged':
1255 forced_revision = True
1256 # Reconstruct the url.
1257 url = '%s@%s' % (url, revision)
1258 rev_str = ' at %s' % revision
1259 else:
1260 managed = False
1261 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001262 else:
1263 forced_revision = False
1264 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001265
thakis@chromium.orgd0b0a5b2014-03-10 19:30:21 +00001266 exists = os.path.exists(self.checkout_path)
borenet@google.com7ff04292014-03-10 12:57:25 +00001267 if exists and managed:
borenet@google.comb09097a2014-04-09 19:09:08 +00001268 # Git is only okay if it's a git-svn checkout of the right repo.
1269 if scm.GIT.IsGitSvn(self.checkout_path):
1270 remote_url = scm.GIT.Capture(['config', '--local', '--get',
1271 'svn-remote.svn.url'],
1272 cwd=self.checkout_path).rstrip()
1273 if remote_url.rstrip('/') == base_url.rstrip('/'):
borenet@google.comb2256212014-05-07 20:57:28 +00001274 self.Print('\n_____ %s looks like a git-svn checkout. Skipping.'
1275 % self.relpath)
borenet@google.comb09097a2014-04-09 19:09:08 +00001276 return # TODO(borenet): Get the svn revision number?
1277
1278 # Get the existing scm url and the revision number of the current checkout.
1279 if exists and managed:
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001280 try:
1281 from_info = scm.SVN.CaptureLocalInfo(
1282 [], os.path.join(self.checkout_path, '.'))
1283 except (gclient_utils.Error, subprocess2.CalledProcessError):
borenet@google.comb09097a2014-04-09 19:09:08 +00001284 self._DeleteOrMove(options.force)
1285 exists = False
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001286
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001287 BASE_URLS = {
1288 '/chrome/trunk/src': 'gs://chromium-svn-checkout/chrome/',
1289 '/blink/trunk': 'gs://chromium-svn-checkout/blink/',
1290 }
hinoka@google.comca35be32014-01-17 01:48:18 +00001291 WHITELISTED_ROOTS = [
1292 'svn://svn.chromium.org',
1293 'svn://svn-mirror.golo.chromium.org',
1294 ]
davidjames@chromium.org13349e22012-11-15 17:11:28 +00001295 if not exists:
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001296 try:
1297 # Split out the revision number since it's not useful for us.
1298 base_path = urlparse.urlparse(url).path.split('@')[0]
hinoka@google.comca35be32014-01-17 01:48:18 +00001299 # Check to see if we're on a whitelisted root. We do this because
1300 # only some svn servers have matching UUIDs.
1301 local_parsed = urlparse.urlparse(url)
1302 local_root = '%s://%s' % (local_parsed.scheme, local_parsed.netloc)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001303 if ('CHROME_HEADLESS' in os.environ
1304 and sys.platform == 'linux2' # TODO(hinoka): Enable for win/mac.
hinoka@google.comca35be32014-01-17 01:48:18 +00001305 and base_path in BASE_URLS
1306 and local_root in WHITELISTED_ROOTS):
1307
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001308 # Use a tarball for initial sync if we are on a bot.
1309 # Get an unauthenticated gsutil instance.
1310 gsutil = download_from_google_storage.Gsutil(
1311 GSUTIL_DEFAULT_PATH, boto_path=os.devnull)
1312
1313 gs_path = BASE_URLS[base_path]
1314 _, out, _ = gsutil.check_call('ls', gs_path)
1315 # So that we can get the most recent revision.
1316 sorted_items = sorted(out.splitlines())
1317 latest_checkout = sorted_items[-1]
1318
1319 tempdir = tempfile.mkdtemp()
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001320 self.Print('Downloading %s...' % latest_checkout)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001321 code, out, err = gsutil.check_call('cp', latest_checkout, tempdir)
1322 if code:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001323 self.Print('%s\n%s' % (out, err))
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001324 raise Exception()
1325 filename = latest_checkout.split('/')[-1]
1326 tarball = os.path.join(tempdir, filename)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001327 self.Print('Unpacking into %s...' % self.checkout_path)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001328 gclient_utils.safe_makedirs(self.checkout_path)
1329 # TODO(hinoka): Use 7z for windows.
1330 cmd = ['tar', '--extract', '--ungzip',
1331 '--directory', self.checkout_path,
1332 '--file', tarball]
1333 gclient_utils.CheckCallAndFilter(
1334 cmd, stdout=sys.stdout, print_stdout=True)
1335
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001336 self.Print('Deleting temp file')
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001337 gclient_utils.rmtree(tempdir)
1338
1339 # Rewrite the repository root to match.
1340 tarball_url = scm.SVN.CaptureLocalInfo(
1341 ['.'], self.checkout_path)['Repository Root']
1342 tarball_parsed = urlparse.urlparse(tarball_url)
1343 tarball_root = '%s://%s' % (tarball_parsed.scheme,
1344 tarball_parsed.netloc)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001345
1346 if tarball_root != local_root:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001347 self.Print('Switching repository root to %s' % local_root)
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001348 self._Run(['switch', '--relocate', tarball_root,
1349 local_root, self.checkout_path],
1350 options)
1351 except Exception as e:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001352 self.Print('We tried to get a source tarball but failed.')
1353 self.Print('Resuming normal operations.')
1354 self.Print(str(e))
hinoka@google.com2f2ca142014-01-07 03:59:18 +00001355
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001356 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001357 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001358 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001359 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001360 self._RunAndGetFileList(command, options, file_list, self._root_dir)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001361 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001362
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001363 if not managed:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001364 self.Print(('________ unmanaged solution; skipping %s' % self.relpath))
borenet@google.comb09097a2014-04-09 19:09:08 +00001365 if os.path.exists(os.path.join(self.checkout_path, '.svn')):
1366 return self.Svnversion()
1367 return
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001368
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001369 if 'URL' not in from_info:
1370 raise gclient_utils.Error(
1371 ('gclient is confused. Couldn\'t get the url for %s.\n'
1372 'Try using @unmanaged.\n%s') % (
1373 self.checkout_path, from_info))
1374
stip@chromium.org3031d732014-04-21 22:18:02 +00001375 # Look for locked directories.
1376 dir_info = scm.SVN.CaptureStatus(
1377 None, os.path.join(self.checkout_path, '.'))
1378 if any(d[0][2] == 'L' for d in dir_info):
1379 try:
1380 self._Run(['cleanup', self.checkout_path], options)
1381 except subprocess2.CalledProcessError, e:
1382 # Get the status again, svn cleanup may have cleaned up at least
1383 # something.
1384 dir_info = scm.SVN.CaptureStatus(
1385 None, os.path.join(self.checkout_path, '.'))
1386
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001387 # Try to fix the failures by removing troublesome files.
1388 for d in dir_info:
1389 if d[0][2] == 'L':
1390 if d[0][0] == '!' and options.force:
kustermann@google.com1580d952013-08-19 07:31:40 +00001391 # We don't pass any files/directories to CaptureStatus and set
1392 # cwd=self.checkout_path, so we should get relative paths here.
1393 assert not os.path.isabs(d[1])
1394 path_to_remove = os.path.normpath(
1395 os.path.join(self.checkout_path, d[1]))
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001396 self.Print('Removing troublesome path %s' % path_to_remove)
kustermann@google.com1580d952013-08-19 07:31:40 +00001397 gclient_utils.rmtree(path_to_remove)
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001398 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001399 self.Print(
1400 'Not removing troublesome path %s automatically.' % d[1])
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001401 if d[0][0] == '!':
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001402 self.Print('You can pass --force to enable automatic removal.')
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001403 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001404
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001405 # Retrieve the current HEAD version because svn is slow at null updates.
1406 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001407 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001408 revision = str(from_info_live['Revision'])
1409 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001410
borenet@google.comb09097a2014-04-09 19:09:08 +00001411 if from_info['URL'].rstrip('/') != base_url.rstrip('/'):
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001412 # The repository url changed, need to switch.
1413 try:
1414 to_info = scm.SVN.CaptureRemoteInfo(url)
1415 except (gclient_utils.Error, subprocess2.CalledProcessError):
1416 # The url is invalid or the server is not accessible, it's safer to bail
1417 # out right now.
1418 raise gclient_utils.Error('This url is unreachable: %s' % url)
1419 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1420 and (from_info['UUID'] == to_info['UUID']))
1421 if can_switch:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001422 self.Print('_____ relocating %s to a new checkout' % self.relpath)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001423 # We have different roots, so check if we can switch --relocate.
1424 # Subversion only permits this if the repository UUIDs match.
1425 # Perform the switch --relocate, then rewrite the from_url
1426 # to reflect where we "are now." (This is the same way that
1427 # Subversion itself handles the metadata when switch --relocate
1428 # is used.) This makes the checks below for whether we
1429 # can update to a revision or have to switch to a different
1430 # branch work as expected.
1431 # TODO(maruel): TEST ME !
1432 command = ['switch', '--relocate',
1433 from_info['Repository Root'],
1434 to_info['Repository Root'],
1435 self.relpath]
1436 self._Run(command, options, cwd=self._root_dir)
1437 from_info['URL'] = from_info['URL'].replace(
1438 from_info['Repository Root'],
1439 to_info['Repository Root'])
1440 else:
1441 if not options.force and not options.reset:
1442 # Look for local modifications but ignore unversioned files.
1443 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1444 if status[0][0] != '?':
1445 raise gclient_utils.Error(
1446 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1447 'there is local changes in %s. Delete the directory and '
1448 'try again.') % (url, self.checkout_path))
1449 # Ok delete it.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001450 self.Print('_____ switching %s to a new checkout' % self.relpath)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001451 gclient_utils.rmtree(self.checkout_path)
1452 # We need to checkout.
1453 command = ['checkout', url, self.checkout_path]
1454 command = self._AddAdditionalUpdateFlags(command, options, revision)
1455 self._RunAndGetFileList(command, options, file_list, self._root_dir)
1456 return self.Svnversion()
1457
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001458 # If the provided url has a revision number that matches the revision
1459 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001460 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001461 if options.verbose or not forced_revision:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001462 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001463 else:
1464 command = ['update', self.checkout_path]
1465 command = self._AddAdditionalUpdateFlags(command, options, revision)
1466 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001467
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001468 # If --reset and --delete_unversioned_trees are specified, remove any
1469 # untracked files and directories.
1470 if options.reset and options.delete_unversioned_trees:
1471 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1472 full_path = os.path.join(self.checkout_path, status[1])
1473 if (status[0][0] == '?'
1474 and os.path.isdir(full_path)
1475 and not os.path.islink(full_path)):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001476 self.Print('_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001477 gclient_utils.rmtree(full_path)
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001478 return self.Svnversion()
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001479
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001480 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001481 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001482 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001483 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001484 # Create an empty checkout and then update the one file we want. Future
1485 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001486 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001487 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001488 if os.path.exists(os.path.join(self.checkout_path, filename)):
1489 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001490 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001491 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001492 # After the initial checkout, we can use update as if it were any other
1493 # dep.
1494 self.update(options, args, file_list)
1495 else:
1496 # If the installed version of SVN doesn't support --depth, fallback to
1497 # just exporting the file. This has the downside that revision
1498 # information is not stored next to the file, so we will have to
1499 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001500 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001501 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001502 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001503 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001504 command = self._AddAdditionalUpdateFlags(command, options,
1505 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001506 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001507
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001508 def revert(self, options, _args, file_list):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001509 """Reverts local modifications. Subversion specific.
1510
1511 All reverted files will be appended to file_list, even if Subversion
1512 doesn't know about them.
1513 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001514 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001515 if os.path.exists(self.checkout_path):
1516 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001517 # svn revert won't work if the directory doesn't exist. It needs to
1518 # checkout instead.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001519 self.Print('_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001520 # Don't reuse the args.
1521 return self.update(options, [], file_list)
1522
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001523 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +00001524 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001525 self.Print('________ found .git directory; skipping %s' % self.relpath)
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +00001526 return
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001527 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001528 self.Print('________ found .hg directory; skipping %s' % self.relpath)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +00001529 return
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001530 if not options.force:
1531 raise gclient_utils.Error('Invalid checkout path, aborting')
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001532 self.Print(
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001533 '\n_____ %s is not a valid svn checkout, synching instead' %
1534 self.relpath)
1535 gclient_utils.rmtree(self.checkout_path)
1536 # Don't reuse the args.
1537 return self.update(options, [], file_list)
1538
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001539 def printcb(file_status):
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001540 if file_list is not None:
1541 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001542 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001543 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001544 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001545 self.Print(os.path.join(self.checkout_path, file_status[1]))
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001546 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001547
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001548 # Revert() may delete the directory altogether.
1549 if not os.path.isdir(self.checkout_path):
1550 # Don't reuse the args.
1551 return self.update(options, [], file_list)
1552
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001553 try:
1554 # svn revert is so broken we don't even use it. Using
1555 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001556 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001557 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1558 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001559 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001560 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001561 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001562
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001563 def revinfo(self, _options, _args, _file_list):
msb@chromium.org0f282062009-11-06 20:14:02 +00001564 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001565 try:
1566 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001567 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001568 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001569
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001570 def runhooks(self, options, args, file_list):
1571 self.status(options, args, file_list)
1572
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001573 def status(self, options, args, file_list):
1574 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001575 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001576 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001577 # svn status won't work if the directory doesn't exist.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001578 self.Print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001579 'The directory does not exist.') %
1580 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001581 # There's no file list to retrieve.
1582 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001583 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001584
iannucci@chromium.org396e1a62013-07-03 19:41:04 +00001585 def GetUsableRev(self, rev, _options):
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001586 """Verifies the validity of the revision for this repository."""
1587 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1588 raise gclient_utils.Error(
1589 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1590 'correct.') % rev)
1591 return rev
1592
msb@chromium.orge6f78352010-01-13 17:05:33 +00001593 def FullUrlForRelativeUrl(self, url):
1594 # Find the forth '/' and strip from there. A bit hackish.
1595 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001596
maruel@chromium.org669600d2010-09-01 19:06:31 +00001597 def _Run(self, args, options, **kwargs):
1598 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001599 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001600 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001601 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001602
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +00001603 def Svnversion(self):
1604 """Runs the lowest checked out revision in the current project."""
1605 info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1606 return info['Revision']
1607
maruel@chromium.org669600d2010-09-01 19:06:31 +00001608 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1609 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001610 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001611 scm.SVN.RunAndGetFileList(
1612 options.verbose,
1613 args + ['--ignore-externals'],
1614 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001615 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001616
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001617 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001618 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001619 """Add additional flags to command depending on what options are set.
1620 command should be a list of strings that represents an svn command.
1621
1622 This method returns a new list to be used as a command."""
1623 new_command = command[:]
1624 if revision:
1625 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001626 # We don't want interaction when jobs are used.
1627 if options.jobs > 1:
1628 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001629 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001630 # --accept was added to 'svn update' in svn 1.6.
1631 if not scm.SVN.AssertVersion('1.5')[0]:
1632 return new_command
1633
1634 # It's annoying to have it block in the middle of a sync, just sensible
1635 # defaults.
1636 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001637 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001638 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1639 new_command.extend(('--accept', 'theirs-conflict'))
1640 elif options.manually_grab_svn_rev:
1641 new_command.append('--force')
1642 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1643 new_command.extend(('--accept', 'postpone'))
1644 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1645 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001646 return new_command