blob: c6d7699ce639db9a7a340c3bd74a2ae29eea1953 [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
smutae7ea312016-07-18 11:59:41 -070033class NoUsableRevError(gclient_utils.Error):
34 """Raised if requested revision isn't found in checkout."""
35
36
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000037class DiffFiltererWrapper(object):
38 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000039 replaces instances of its file name in the original and
agable41e3a6c2016-10-20 11:36:56 -070040 working copy lines of the git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000041 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000042 original_prefix = "--- "
43 working_prefix = "+++ "
44
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000045 def __init__(self, relpath, print_func):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000046 # Note that we always use '/' as the path separator to be
agable41e3a6c2016-10-20 11:36:56 -070047 # consistent with cygwin-style output on Windows
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000048 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000049 self._current_file = None
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000050 self._print_func = print_func
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000051
maruel@chromium.org6e29d572010-06-04 17:32:20 +000052 def SetCurrentFile(self, current_file):
53 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000054
iannucci@chromium.org3830a672013-02-19 20:15:14 +000055 @property
56 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000057 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000058
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000059 def _Replace(self, line):
60 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000061
62 def Filter(self, line):
63 if (line.startswith(self.index_string)):
64 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000065 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000066 else:
67 if (line.startswith(self.original_prefix) or
68 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000069 line = self._Replace(line)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000070 self._print_func(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000071
72
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000073class 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):
agable41e3a6c2016-10-20 11:36:56 -070089 if not url:
90 return None
91 url, _ = gclient_utils.SplitUrlRevision(url)
92 if url.endswith('.git'):
93 return 'git'
94 protocol = url.split('://')[0]
95 if protocol in (
96 'file', 'git', 'git+http', 'git+https', 'http', 'https', 'ssh', 'sso'):
97 return 'git'
maruel@chromium.org9eda4112010-06-11 18:56:10 +000098 return None
99
100
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000101def CreateSCM(url, root_dir=None, relpath=None, out_fh=None, out_cb=None):
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000102 SCM_MAP = {
msb@chromium.orge28e4982009-09-25 20:51:45 +0000103 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000104 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000105
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000106 scm_name = GetScmName(url)
107 if not scm_name in SCM_MAP:
108 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000109 scm_class = SCM_MAP[scm_name]
110 if not scm_class.BinaryExists():
111 raise gclient_utils.Error('%s command not found' % scm_name)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000112 return scm_class(url, root_dir, relpath, out_fh, out_cb)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000113
114
115# SCMWrapper base class
116
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000117class SCMWrapper(object):
118 """Add necessary glue between all the supported SCM.
119
msb@chromium.orgd6504212010-01-13 17:34:31 +0000120 This is the abstraction layer to bind to different SCM.
121 """
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000122
123 def __init__(self, url=None, root_dir=None, relpath=None, out_fh=None,
124 out_cb=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000125 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000126 self._root_dir = root_dir
127 if self._root_dir:
128 self._root_dir = self._root_dir.replace('/', os.sep)
129 self.relpath = relpath
130 if self.relpath:
131 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000132 if self.relpath and self._root_dir:
133 self.checkout_path = os.path.join(self._root_dir, self.relpath)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000134 if out_fh is None:
135 out_fh = sys.stdout
136 self.out_fh = out_fh
137 self.out_cb = out_cb
138
139 def Print(self, *args, **kwargs):
140 kwargs.setdefault('file', self.out_fh)
141 if kwargs.pop('timestamp', True):
142 self.out_fh.write('[%s] ' % gclient_utils.Elapsed())
143 print(*args, **kwargs)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000144
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000145 def RunCommand(self, command, options, args, file_list=None):
agabledebf6c82016-12-21 12:50:12 -0800146 commands = ['update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000147 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000148
149 if not command in commands:
150 raise gclient_utils.Error('Unknown command %s' % command)
151
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000152 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000153 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000154 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000155
156 return getattr(self, command)(options, args, file_list)
157
hinoka@chromium.orgfa2b9b42014-08-22 18:08:53 +0000158 @staticmethod
159 def _get_first_remote_url(checkout_path):
160 log = scm.GIT.Capture(
161 ['config', '--local', '--get-regexp', r'remote.*.url'],
162 cwd=checkout_path)
163 # Get the second token of the first line of the log.
164 return log.splitlines()[0].split(' ', 1)[1]
165
levarum@chromium.org27a6f9a2016-05-28 00:21:49 +0000166 def GetCacheMirror(self):
167 if (getattr(self, 'cache_dir', None)):
168 url, _ = gclient_utils.SplitUrlRevision(self.url)
169 return git_cache.Mirror(url)
170 return None
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
levarum@chromium.org27a6f9a2016-05-28 00:21:49 +0000178 mirror = self.GetCacheMirror()
179 # If the cache is used, obtain the actual remote URL from there.
180 if (mirror and mirror.exists() and
181 mirror.mirror_path.replace('\\', '/') ==
182 actual_remote_url.replace('\\', '/')):
183 actual_remote_url = self._get_first_remote_url(mirror.mirror_path)
borenet@google.com4e9be262014-04-08 19:40:30 +0000184 return actual_remote_url
borenet@google.com88d10082014-03-21 17:24:48 +0000185 return None
186
borenet@google.com4e9be262014-04-08 19:40:30 +0000187 def DoesRemoteURLMatch(self, options):
borenet@google.com88d10082014-03-21 17:24:48 +0000188 """Determine whether the remote URL of this checkout is the expected URL."""
189 if not os.path.exists(self.checkout_path):
190 # A checkout which doesn't exist can't be broken.
191 return True
192
smut@google.comd33eab32014-07-07 19:35:18 +0000193 actual_remote_url = self.GetActualRemoteURL(options)
borenet@google.com88d10082014-03-21 17:24:48 +0000194 if actual_remote_url:
borenet@google.com8156c9f2014-04-01 16:41:36 +0000195 return (gclient_utils.SplitUrlRevision(actual_remote_url)[0].rstrip('/')
196 == gclient_utils.SplitUrlRevision(self.url)[0].rstrip('/'))
borenet@google.com88d10082014-03-21 17:24:48 +0000197 else:
198 # This may occur if the self.checkout_path exists but does not contain a
agable41e3a6c2016-10-20 11:36:56 -0700199 # valid git checkout.
borenet@google.com88d10082014-03-21 17:24:48 +0000200 return False
201
borenet@google.comb09097a2014-04-09 19:09:08 +0000202 def _DeleteOrMove(self, force):
203 """Delete the checkout directory or move it out of the way.
204
205 Args:
206 force: bool; if True, delete the directory. Otherwise, just move it.
207 """
borenet@google.comb2256212014-05-07 20:57:28 +0000208 if force and os.environ.get('CHROME_HEADLESS') == '1':
209 self.Print('_____ Conflicting directory found in %s. Removing.'
210 % self.checkout_path)
211 gclient_utils.AddWarning('Conflicting directory %s deleted.'
212 % self.checkout_path)
213 gclient_utils.rmtree(self.checkout_path)
214 else:
215 bad_scm_dir = os.path.join(self._root_dir, '_bad_scm',
216 os.path.dirname(self.relpath))
217
218 try:
219 os.makedirs(bad_scm_dir)
220 except OSError as e:
221 if e.errno != errno.EEXIST:
222 raise
223
224 dest_path = tempfile.mkdtemp(
225 prefix=os.path.basename(self.relpath),
226 dir=bad_scm_dir)
227 self.Print('_____ Conflicting directory found in %s. Moving to %s.'
228 % (self.checkout_path, dest_path))
229 gclient_utils.AddWarning('Conflicting directory %s moved to %s.'
230 % (self.checkout_path, dest_path))
231 shutil.move(self.checkout_path, dest_path)
borenet@google.comb09097a2014-04-09 19:09:08 +0000232
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000233
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000234class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000235 """Wrapper for Git"""
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000236 name = 'git'
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000237 remote = 'origin'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000238
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000239 cache_dir = None
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000240
szager@chromium.org848fd492014-04-09 19:06:44 +0000241 def __init__(self, url=None, *args):
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000242 """Removes 'git+' fake prefix from git URL."""
243 if url.startswith('git+http://') or url.startswith('git+https://'):
244 url = url[4:]
szager@chromium.org848fd492014-04-09 19:06:44 +0000245 SCMWrapper.__init__(self, url, *args)
246 filter_kwargs = { 'time_throttle': 1, 'out_fh': self.out_fh }
247 if self.out_cb:
248 filter_kwargs['predicate'] = self.out_cb
249 self.filter = gclient_utils.GitFilter(**filter_kwargs)
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000250
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000251 @staticmethod
252 def BinaryExists():
253 """Returns true if the command exists."""
254 try:
255 # We assume git is newer than 1.7. See: crbug.com/114483
256 result, version = scm.GIT.AssertVersion('1.7')
257 if not result:
258 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
259 return result
260 except OSError:
261 return False
262
xusydoc@chromium.org885a9602013-05-31 09:54:40 +0000263 def GetCheckoutRoot(self):
264 return scm.GIT.GetCheckoutRoot(self.checkout_path)
265
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000266 def GetRevisionDate(self, _revision):
floitsch@google.comeaab7842011-04-28 09:07:58 +0000267 """Returns the given revision's date in ISO-8601 format (which contains the
268 time zone)."""
269 # TODO(floitsch): get the time-stamp of the given revision and not just the
270 # time-stamp of the currently checked out revision.
271 return self._Capture(['log', '-n', '1', '--format=%ai'])
272
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000273 def diff(self, options, _args, _file_list):
raphael.kubo.da.costa05c83592016-08-04 08:32:41 -0700274 try:
275 merge_base = [self._Capture(['merge-base', 'HEAD', self.remote])]
276 except subprocess2.CalledProcessError:
277 merge_base = []
278 self._Run(['diff'] + merge_base, options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000279
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000280 def pack(self, _options, _args, _file_list):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000281 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000282 repository.
283
284 The patch file is generated from a diff of the merge base of HEAD and
285 its upstream branch.
286 """
raphael.kubo.da.costa05c83592016-08-04 08:32:41 -0700287 try:
288 merge_base = [self._Capture(['merge-base', 'HEAD', self.remote])]
289 except subprocess2.CalledProcessError:
290 merge_base = []
maruel@chromium.org17d01792010-09-01 18:07:10 +0000291 gclient_utils.CheckCallAndFilter(
raphael.kubo.da.costa05c83592016-08-04 08:32:41 -0700292 ['git', 'diff'] + merge_base,
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000293 cwd=self.checkout_path,
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000294 filter_fn=GitDiffFilterer(self.relpath, print_func=self.Print).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000295
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800296 def _Scrub(self, target, options):
297 """Scrubs out all changes in the local repo, back to the state of target."""
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000298 quiet = []
299 if not options.verbose:
300 quiet = ['--quiet']
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800301 self._Run(['reset', '--hard', target] + quiet, options)
302 if options.force and options.delete_unversioned_trees:
303 # where `target` is a commit that contains both upper and lower case
304 # versions of the same file on a case insensitive filesystem, we are
305 # actually in a broken state here. The index will have both 'a' and 'A',
306 # but only one of them will exist on the disk. To progress, we delete
307 # everything that status thinks is modified.
308 for line in self._Capture(['status', '--porcelain']).splitlines():
309 # --porcelain (v1) looks like:
310 # XY filename
311 try:
312 filename = line[3:]
313 self.Print('_____ Deleting residual after reset: %r.' % filename)
314 gclient_utils.rm_file_or_tree(
315 os.path.join(self.checkout_path, line[3:]))
316 except OSError:
317 pass
318
319 def _FetchAndReset(self, revision, file_list, options):
320 """Equivalent to git fetch; git reset."""
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000321 self._UpdateBranchHeads(options, fetch=False)
322
dnj@chromium.org680f2172014-06-25 00:39:32 +0000323 self._Fetch(options, prune=True, quiet=options.verbose)
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800324 self._Scrub(revision, options)
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000325 if file_list is not None:
326 files = self._Capture(['ls-files']).splitlines()
327 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
328
szager@chromium.org8a139702014-06-20 15:55:01 +0000329 def _DisableHooks(self):
330 hook_dir = os.path.join(self.checkout_path, '.git', 'hooks')
331 if not os.path.isdir(hook_dir):
332 return
333 for f in os.listdir(hook_dir):
334 if not f.endswith('.sample') and not f.endswith('.disabled'):
primiano@chromium.org41265562015-04-08 09:14:46 +0000335 disabled_hook_path = os.path.join(hook_dir, f + '.disabled')
336 if os.path.exists(disabled_hook_path):
337 os.remove(disabled_hook_path)
338 os.rename(os.path.join(hook_dir, f), disabled_hook_path)
szager@chromium.org8a139702014-06-20 15:55:01 +0000339
iannucci@chromium.org30a07982016-04-07 21:35:19 +0000340 def _maybe_break_locks(self, options):
341 """This removes all .lock files from this repo's .git directory, if the
342 user passed the --break_repo_locks command line flag.
343
344 In particular, this will cleanup index.lock files, as well as ref lock
345 files.
346 """
347 if options.break_repo_locks:
348 git_dir = os.path.join(self.checkout_path, '.git')
349 for path, _, filenames in os.walk(git_dir):
350 for filename in filenames:
351 if filename.endswith('.lock'):
352 to_break = os.path.join(path, filename)
353 self.Print('breaking lock: %s' % (to_break,))
354 try:
355 os.remove(to_break)
356 except OSError as ex:
357 self.Print('FAILED to break lock: %s: %s' % (to_break, ex))
358 raise
359
360
msb@chromium.orge28e4982009-09-25 20:51:45 +0000361 def update(self, options, args, file_list):
362 """Runs git to update or transparently checkout the working copy.
363
364 All updated files will be appended to file_list.
365
366 Raises:
367 Error: if can't get URL for relative path.
368 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000369 if args:
370 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
371
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000372 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000373
maruel@chromium.org1a60dca2013-11-26 14:06:26 +0000374 # If a dependency is not pinned, track the default remote branch.
smut@google.comd33eab32014-07-07 19:35:18 +0000375 default_rev = 'refs/remotes/%s/master' % self.remote
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000376 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000377 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000378 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000379 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000380 # Override the revision number.
381 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000382 if revision == 'unmanaged':
romain.pokrzywka@gmail.com483a0ba2014-05-30 00:06:07 +0000383 # Check again for a revision in case an initial ref was specified
384 # in the url, for example bla.git@refs/heads/custombranch
385 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000386 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000387 if not revision:
388 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000389
szager@chromium.org8a139702014-06-20 15:55:01 +0000390 if managed:
391 self._DisableHooks()
392
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000393 printed_path = False
394 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000395 if options.verbose:
agable83faed02016-10-24 14:37:10 -0700396 self.Print('_____ %s at %s' % (self.relpath, revision), timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000397 verbose = ['--verbose']
398 printed_path = True
399
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000400 remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
401 if remote_ref:
smut@google.comd33eab32014-07-07 19:35:18 +0000402 # Rewrite remote refs to their local equivalents.
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000403 revision = ''.join(remote_ref)
404 rev_type = "branch"
405 elif revision.startswith('refs/'):
406 # Local branch? We probably don't want to support, since DEPS should
407 # always specify branches as they are in the upstream repo.
smut@google.comd33eab32014-07-07 19:35:18 +0000408 rev_type = "branch"
409 else:
410 # hash is also a tag, only make a distinction at checkout
411 rev_type = "hash"
412
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000413 mirror = self._GetMirror(url, options)
414 if mirror:
415 url = mirror.mirror_path
416
primiano@chromium.org1c127382015-02-17 11:15:40 +0000417 # If we are going to introduce a new project, there is a possibility that
418 # we are syncing back to a state where the project was originally a
419 # sub-project rolled by DEPS (realistic case: crossing the Blink merge point
420 # syncing backwards, when Blink was a DEPS entry and not part of src.git).
421 # In such case, we might have a backup of the former .git folder, which can
422 # be used to avoid re-fetching the entire repo again (useful for bisects).
423 backup_dir = self.GetGitBackupDirPath()
424 target_dir = os.path.join(self.checkout_path, '.git')
425 if os.path.exists(backup_dir) and not os.path.exists(target_dir):
426 gclient_utils.safe_makedirs(self.checkout_path)
427 os.rename(backup_dir, target_dir)
428 # Reset to a clean state
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800429 self._Scrub('HEAD', options)
primiano@chromium.org1c127382015-02-17 11:15:40 +0000430
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000431 if (not os.path.exists(self.checkout_path) or
432 (os.path.isdir(self.checkout_path) and
433 not os.path.exists(os.path.join(self.checkout_path, '.git')))):
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000434 if mirror:
435 self._UpdateMirror(mirror, options)
borenet@google.com90fe58b2014-05-01 18:22:00 +0000436 try:
smut@google.comd33eab32014-07-07 19:35:18 +0000437 self._Clone(revision, url, options)
borenet@google.com90fe58b2014-05-01 18:22:00 +0000438 except subprocess2.CalledProcessError:
439 self._DeleteOrMove(options.force)
smut@google.comd33eab32014-07-07 19:35:18 +0000440 self._Clone(revision, url, options)
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000441 if file_list is not None:
442 files = self._Capture(['ls-files']).splitlines()
443 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000444 if not verbose:
445 # Make the output a little prettier. It's nice to have some whitespace
446 # between projects when cloning.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000447 self.Print('')
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000448 return self._Capture(['rev-parse', '--verify', 'HEAD'])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000449
szager@chromium.org3dc5cb72014-06-17 15:06:05 +0000450 if not managed:
451 self._UpdateBranchHeads(options, fetch=False)
452 self.Print('________ unmanaged solution; skipping %s' % self.relpath)
453 return self._Capture(['rev-parse', '--verify', 'HEAD'])
454
iannucci@chromium.org30a07982016-04-07 21:35:19 +0000455 self._maybe_break_locks(options)
456
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000457 if mirror:
458 self._UpdateMirror(mirror, options)
459
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000460 # See if the url has changed (the unittests use git://foo for the url, let
461 # that through).
462 current_url = self._Capture(['config', 'remote.%s.url' % self.remote])
463 return_early = False
464 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
465 # unit test pass. (and update the comment above)
466 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
467 # This allows devs to use experimental repos which have a different url
468 # but whose branch(s) are the same as official repos.
borenet@google.comb09097a2014-04-09 19:09:08 +0000469 if (current_url.rstrip('/') != url.rstrip('/') and
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000470 url != 'git://foo' and
471 subprocess2.capture(
472 ['git', 'config', 'remote.%s.gclient-auto-fix-url' % self.remote],
473 cwd=self.checkout_path).strip() != 'False'):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000474 self.Print('_____ switching %s to a new upstream' % self.relpath)
iannucci@chromium.org78514212014-08-20 23:08:00 +0000475 if not (options.force or options.reset):
476 # Make sure it's clean
agable83faed02016-10-24 14:37:10 -0700477 self._CheckClean(revision)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000478 # Switch over to the new upstream
479 self._Run(['remote', 'set-url', self.remote, url], options)
szager@chromium.org8dd35462015-06-08 22:56:05 +0000480 if mirror:
481 with open(os.path.join(
482 self.checkout_path, '.git', 'objects', 'info', 'alternates'),
483 'w') as fh:
484 fh.write(os.path.join(url, 'objects'))
tandrii@chromium.orgc438c142015-08-24 22:55:55 +0000485 self._EnsureValidHeadObjectOrCheckout(revision, options, url)
smut@google.comd33eab32014-07-07 19:35:18 +0000486 self._FetchAndReset(revision, file_list, options)
tandrii@chromium.orgc438c142015-08-24 22:55:55 +0000487
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000488 return_early = True
tandrii@chromium.orgc438c142015-08-24 22:55:55 +0000489 else:
490 self._EnsureValidHeadObjectOrCheckout(revision, options, url)
szager@chromium.org6c2b49d2014-02-26 23:57:38 +0000491
mmoss@chromium.org50fd47f2014-02-13 01:03:19 +0000492 if return_early:
493 return self._Capture(['rev-parse', '--verify', 'HEAD'])
494
msb@chromium.org5bde4852009-12-14 16:47:12 +0000495 cur_branch = self._GetCurrentBranch()
496
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000497 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000498 # 0) HEAD is detached. Probably from our initial clone.
499 # - make sure HEAD is contained by a named ref, then update.
500 # Cases 1-4. HEAD is a branch.
agable41e3a6c2016-10-20 11:36:56 -0700501 # 1) current branch is not tracking a remote branch
msb@chromium.org786fb682010-06-02 15:16:23 +0000502 # - try to rebase onto the new hash or branch
503 # 2) current branch is tracking a remote branch with local committed
504 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000505 # - rebase those changes on top of the hash
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000506 # 3) current branch is tracking a remote branch w/or w/out changes, and
507 # no DEPS switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000508 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000509 # 4) current branch is tracking a remote branch, but DEPS switches to a
510 # different remote branch, and
511 # a) current branch has no local changes, and --force:
512 # - checkout new branch
513 # b) current branch has local changes, and --force and --reset:
514 # - checkout new branch
515 # c) otherwise exit
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000516
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000517 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
518 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000519 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
520 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000521 if cur_branch is None:
522 upstream_branch = None
523 current_type = "detached"
524 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000525 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000526 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
527 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
528 current_type = "hash"
529 logging.debug("Current branch is not tracking an upstream (remote)"
530 " branch.")
531 elif upstream_branch.startswith('refs/remotes'):
532 current_type = "branch"
533 else:
534 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000535
smut@google.comd33eab32014-07-07 19:35:18 +0000536 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000537 # Update the remotes first so we have all the refs.
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000538 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000539 cwd=self.checkout_path)
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000540 if verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000541 self.Print(remote_output)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000542
mmoss@chromium.org37ac0e32015-08-18 18:14:38 +0000543 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000544
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000545 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000546 if options.force or options.reset:
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000547 target = 'HEAD'
548 if options.upstream and upstream_branch:
549 target = upstream_branch
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800550 self._Scrub(target, options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000551
msb@chromium.org786fb682010-06-02 15:16:23 +0000552 if current_type == 'detached':
553 # case 0
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800554 # We just did a Scrub, this is as clean as it's going to get. In
555 # particular if HEAD is a commit that contains two versions of the same
556 # file on a case-insensitive filesystem (e.g. 'a' and 'A'), there's no way
557 # to actually "Clean" the checkout; that commit is uncheckoutable on this
558 # system. The best we can do is carry forward to the checkout step.
559 if not (options.force or options.reset):
560 self._CheckClean(revision)
agable83faed02016-10-24 14:37:10 -0700561 self._CheckDetachedHead(revision, options)
smut@google.comd33eab32014-07-07 19:35:18 +0000562 if self._Capture(['rev-list', '-n', '1', 'HEAD']) == revision:
szager@chromium.org848fd492014-04-09 19:06:44 +0000563 self.Print('Up-to-date; skipping checkout.')
564 else:
vadimsh@chromium.org2b7d3ed2014-06-20 18:15:37 +0000565 # 'git checkout' may need to overwrite existing untracked files. Allow
566 # it only when nuclear options are enabled.
dnj@chromium.orgbb424c02014-06-23 22:42:51 +0000567 self._Checkout(
568 options,
569 revision,
smut@google.com34b4e982016-05-16 19:06:07 +0000570 force=(options.force and options.delete_unversioned_trees),
dnj@chromium.orgbb424c02014-06-23 22:42:51 +0000571 quiet=True,
572 )
msb@chromium.org786fb682010-06-02 15:16:23 +0000573 if not printed_path:
agable83faed02016-10-24 14:37:10 -0700574 self.Print('_____ %s at %s' % (self.relpath, revision), timestamp=False)
msb@chromium.org786fb682010-06-02 15:16:23 +0000575 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000576 # case 1
agable41e3a6c2016-10-20 11:36:56 -0700577 # Can't find a merge-base since we don't know our upstream. That makes
578 # this command VERY likely to produce a rebase failure. For now we
579 # assume origin is our upstream since that's what the old behavior was.
580 upstream_branch = self.remote
581 if options.revision or deps_revision:
582 upstream_branch = revision
agable1a8439a2016-10-24 16:36:14 -0700583 self._AttemptRebase(upstream_branch, file_list, options,
agable41e3a6c2016-10-20 11:36:56 -0700584 printed_path=printed_path, merge=options.merge)
585 printed_path = True
smut@google.comd33eab32014-07-07 19:35:18 +0000586 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000587 # case 2
agable1a8439a2016-10-24 16:36:14 -0700588 self._AttemptRebase(upstream_branch, file_list, options,
smut@google.comd33eab32014-07-07 19:35:18 +0000589 newbase=revision, printed_path=printed_path,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000590 merge=options.merge)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000591 printed_path = True
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000592 elif remote_ref and ''.join(remote_ref) != upstream_branch:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000593 # case 4
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000594 new_base = ''.join(remote_ref)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000595 if not printed_path:
agable83faed02016-10-24 14:37:10 -0700596 self.Print('_____ %s at %s' % (self.relpath, revision), timestamp=False)
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000597 switch_error = ("Could not switch upstream branch from %s to %s\n"
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000598 % (upstream_branch, new_base) +
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000599 "Please use --force or merge or rebase manually:\n" +
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000600 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
601 "OR git checkout -b <some new branch> %s" % new_base)
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000602 force_switch = False
603 if options.force:
604 try:
agable83faed02016-10-24 14:37:10 -0700605 self._CheckClean(revision)
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000606 # case 4a
607 force_switch = True
608 except gclient_utils.Error as e:
609 if options.reset:
610 # case 4b
611 force_switch = True
612 else:
613 switch_error = '%s\n%s' % (e.message, switch_error)
614 if force_switch:
615 self.Print("Switching upstream branch from %s to %s" %
616 (upstream_branch, new_base))
617 switch_branch = 'gclient_' + remote_ref[1]
618 self._Capture(['branch', '-f', switch_branch, new_base])
619 self._Checkout(options, switch_branch, force=True, quiet=True)
620 else:
621 # case 4c
622 raise gclient_utils.Error(switch_error)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000623 else:
624 # case 3 - the default case
agable1a8439a2016-10-24 16:36:14 -0700625 rebase_files = self._Capture(
626 ['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000627 if verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000628 self.Print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000629 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000630 merge_args = ['merge']
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000631 if options.merge:
632 merge_args.append('--ff')
633 else:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000634 merge_args.append('--ff-only')
635 merge_args.append(upstream_branch)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000636 merge_output = self._Capture(merge_args)
bratell@opera.com18fa4542013-05-21 13:30:46 +0000637 except subprocess2.CalledProcessError as e:
agable1a8439a2016-10-24 16:36:14 -0700638 rebase_files = []
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000639 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
640 if not printed_path:
agable83faed02016-10-24 14:37:10 -0700641 self.Print('_____ %s at %s' % (self.relpath, revision),
642 timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000643 printed_path = True
644 while True:
dnj@chromium.org5b23e872015-02-20 21:25:57 +0000645 if not options.auto_rebase:
646 try:
647 action = self._AskForData(
648 'Cannot %s, attempt to rebase? '
649 '(y)es / (q)uit / (s)kip : ' %
650 ('merge' if options.merge else 'fast-forward merge'),
651 options)
652 except ValueError:
653 raise gclient_utils.Error('Invalid Character')
654 if options.auto_rebase or re.match(r'yes|y', action, re.I):
agable1a8439a2016-10-24 16:36:14 -0700655 self._AttemptRebase(upstream_branch, rebase_files, options,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000656 printed_path=printed_path, merge=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000657 printed_path = True
658 break
659 elif re.match(r'quit|q', action, re.I):
660 raise gclient_utils.Error("Can't fast-forward, please merge or "
661 "rebase manually.\n"
662 "cd %s && git " % self.checkout_path
663 + "rebase %s" % upstream_branch)
664 elif re.match(r'skip|s', action, re.I):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000665 self.Print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000666 return
667 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000668 self.Print('Input not recognized')
smut@google.com27c9c8a2014-09-11 19:57:55 +0000669 elif re.match("error: Your local changes to '.*' would be "
670 "overwritten by merge. Aborting.\nPlease, commit your "
671 "changes or stash them before you can merge.\n",
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000672 e.stderr):
673 if not printed_path:
agable83faed02016-10-24 14:37:10 -0700674 self.Print('_____ %s at %s' % (self.relpath, revision),
675 timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000676 printed_path = True
677 raise gclient_utils.Error(e.stderr)
678 else:
679 # Some other problem happened with the merge
680 logging.error("Error during fast-forward merge in %s!" % self.relpath)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000681 self.Print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000682 raise
683 else:
684 # Fast-forward merge was successful
685 if not re.match('Already up-to-date.', merge_output) or verbose:
686 if not printed_path:
agable83faed02016-10-24 14:37:10 -0700687 self.Print('_____ %s at %s' % (self.relpath, revision),
688 timestamp=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000689 printed_path = True
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000690 self.Print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000691 if not verbose:
692 # Make the output a little prettier. It's nice to have some
693 # whitespace between projects when syncing.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000694 self.Print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000695
agablec3937b92016-10-25 10:13:03 -0700696 if file_list is not None:
697 file_list.extend(
698 [os.path.join(self.checkout_path, f) for f in rebase_files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000699
700 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000701 if self._IsRebasing():
agable83faed02016-10-24 14:37:10 -0700702 raise gclient_utils.Error('\n____ %s at %s\n'
msb@chromium.org5bde4852009-12-14 16:47:12 +0000703 '\nConflict while rebasing this branch.\n'
704 'Fix the conflict and run gclient again.\n'
705 'See man git-rebase for details.\n'
agable83faed02016-10-24 14:37:10 -0700706 % (self.relpath, revision))
msb@chromium.org5bde4852009-12-14 16:47:12 +0000707
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000708 if verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000709 self.Print('Checked out revision %s' % self.revinfo(options, (), None),
710 timestamp=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000711
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000712 # If --reset and --delete_unversioned_trees are specified, remove any
713 # untracked directories.
714 if options.reset and options.delete_unversioned_trees:
715 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
716 # merge-base by default), so doesn't include untracked files. So we use
717 # 'git ls-files --directory --others --exclude-standard' here directly.
718 paths = scm.GIT.Capture(
719 ['ls-files', '--directory', '--others', '--exclude-standard'],
720 self.checkout_path)
721 for path in (p for p in paths.splitlines() if p.endswith('/')):
722 full_path = os.path.join(self.checkout_path, path)
723 if not os.path.islink(full_path):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000724 self.Print('_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000725 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000726
iannucci@chromium.org2702bcd2013-09-24 19:10:07 +0000727 return self._Capture(['rev-parse', '--verify', 'HEAD'])
728
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000729
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000730 def revert(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000731 """Reverts local modifications.
732
733 All reverted files will be appended to file_list.
734 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000735 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000736 # revert won't work if the directory doesn't exist. It needs to
737 # checkout instead.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000738 self.Print('_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000739 # Don't reuse the args.
740 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000741
742 default_rev = "refs/heads/master"
iannucci@chromium.orgd4fffee2013-06-28 00:35:26 +0000743 if options.upstream:
744 if self._GetCurrentBranch():
745 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
746 default_rev = upstream_branch or default_rev
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000747 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000748 if not deps_revision:
749 deps_revision = default_rev
smut@google.comd33eab32014-07-07 19:35:18 +0000750 if deps_revision.startswith('refs/heads/'):
751 deps_revision = deps_revision.replace('refs/heads/', self.remote + '/')
smutae7ea312016-07-18 11:59:41 -0700752 try:
753 deps_revision = self.GetUsableRev(deps_revision, options)
754 except NoUsableRevError as e:
755 # If the DEPS entry's url and hash changed, try to update the origin.
756 # See also http://crbug.com/520067.
757 logging.warn(
758 'Couldn\'t find usable revision, will retrying to update instead: %s',
759 e.message)
760 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000761
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000762 if file_list is not None:
763 files = self._Capture(['diff', deps_revision, '--name-only']).split()
764
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800765 self._Scrub(deps_revision, options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000766 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000767
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000768 if file_list is not None:
769 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
770
771 def revinfo(self, _options, _args, _file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000772 """Returns revision"""
773 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000774
msb@chromium.orge28e4982009-09-25 20:51:45 +0000775 def runhooks(self, options, args, file_list):
776 self.status(options, args, file_list)
777
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000778 def status(self, options, _args, file_list):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000779 """Display status information."""
780 if not os.path.isdir(self.checkout_path):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000781 self.Print('________ couldn\'t run status in %s:\n'
782 'The directory does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000783 else:
raphael.kubo.da.costa05c83592016-08-04 08:32:41 -0700784 try:
785 merge_base = [self._Capture(['merge-base', 'HEAD', self.remote])]
786 except subprocess2.CalledProcessError:
787 merge_base = []
788 self._Run(['diff', '--name-status'] + merge_base, options,
agable41e3a6c2016-10-20 11:36:56 -0700789 stdout=self.out_fh, always=options.verbose)
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000790 if file_list is not None:
raphael.kubo.da.costa05c83592016-08-04 08:32:41 -0700791 files = self._Capture(['diff', '--name-only'] + merge_base).split()
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000792 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orge28e4982009-09-25 20:51:45 +0000793
smutae7ea312016-07-18 11:59:41 -0700794 def GetUsableRev(self, rev, options):
agable41e3a6c2016-10-20 11:36:56 -0700795 """Finds a useful revision for this repository."""
smutae7ea312016-07-18 11:59:41 -0700796 sha1 = None
797 if not os.path.isdir(self.checkout_path):
798 raise NoUsableRevError(
agablea98a6cd2016-11-15 14:30:10 -0800799 'This is not a git repo, so we cannot get a usable rev.')
agable41e3a6c2016-10-20 11:36:56 -0700800
801 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
802 sha1 = rev
smutae7ea312016-07-18 11:59:41 -0700803 else:
agable41e3a6c2016-10-20 11:36:56 -0700804 # May exist in origin, but we don't have it yet, so fetch and look
805 # again.
806 self._Fetch(options)
smutae7ea312016-07-18 11:59:41 -0700807 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
808 sha1 = rev
smutae7ea312016-07-18 11:59:41 -0700809
810 if not sha1:
811 raise NoUsableRevError(
agablea98a6cd2016-11-15 14:30:10 -0800812 'Hash %s does not appear to be a valid hash in this repo.' % rev)
smutae7ea312016-07-18 11:59:41 -0700813
814 return sha1
815
msb@chromium.orge6f78352010-01-13 17:05:33 +0000816 def FullUrlForRelativeUrl(self, url):
817 # Strip from last '/'
818 # Equivalent to unix basename
819 base_url = self.url
820 return base_url[:base_url.rfind('/')] + url
821
primiano@chromium.org1c127382015-02-17 11:15:40 +0000822 def GetGitBackupDirPath(self):
823 """Returns the path where the .git folder for the current project can be
824 staged/restored. Use case: subproject moved from DEPS <-> outer project."""
825 return os.path.join(self._root_dir,
826 'old_' + self.relpath.replace(os.sep, '_')) + '.git'
827
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000828 def _GetMirror(self, url, options):
829 """Get a git_cache.Mirror object for the argument url."""
830 if not git_cache.Mirror.GetCachePath():
831 return None
hinoka@google.comb1b54572014-04-16 22:29:23 +0000832 mirror_kwargs = {
833 'print_func': self.filter,
834 'refs': []
835 }
hinoka@google.comb1b54572014-04-16 22:29:23 +0000836 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
837 mirror_kwargs['refs'].append('refs/branch-heads/*')
szager@chromium.org8d3348f2014-08-19 22:49:16 +0000838 if hasattr(options, 'with_tags') and options.with_tags:
839 mirror_kwargs['refs'].append('refs/tags/*')
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000840 return git_cache.Mirror(url, **mirror_kwargs)
841
842 @staticmethod
843 def _UpdateMirror(mirror, options):
844 """Update a git mirror by fetching the latest commits from the remote."""
szager@chromium.org3ec84f62014-08-22 21:00:22 +0000845 if getattr(options, 'shallow', False):
hinoka@chromium.org46b87412014-05-15 00:42:05 +0000846 # HACK(hinoka): These repositories should be super shallow.
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000847 if 'flash' in mirror.url:
hinoka@chromium.org46b87412014-05-15 00:42:05 +0000848 depth = 10
849 else:
850 depth = 10000
851 else:
852 depth = None
e.hakkinen@samsung.come8bc1aa2015-04-08 08:00:37 +0000853 mirror.populate(verbose=options.verbose,
854 bootstrap=not getattr(options, 'no_bootstrap', False),
855 depth=depth,
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000856 ignore_lock=getattr(options, 'ignore_locks', False),
857 lock_timeout=getattr(options, 'lock_timeout', 0))
szager@chromium.org848fd492014-04-09 19:06:44 +0000858 mirror.unlock()
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000859
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000860 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000861 """Clone a git repository from the given URL.
862
msb@chromium.org786fb682010-06-02 15:16:23 +0000863 Once we've cloned the repo, we checkout a working branch if the specified
864 revision is a branch head. If it is a tag or a specific commit, then we
865 leave HEAD detached as it makes future updates simpler -- in this case the
866 user should first create a new branch or switch to an existing branch before
867 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000868 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000869 # git clone doesn't seem to insert a newline properly before printing
870 # to stdout
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000871 self.Print('')
szager@chromium.orgf1d73eb2014-04-21 17:07:04 +0000872 cfg = gclient_utils.DefaultIndexPackConfig(url)
szager@chromium.org8a139702014-06-20 15:55:01 +0000873 clone_cmd = cfg + ['clone', '--no-checkout', '--progress']
iannucci@chromium.org53456aa2013-07-03 19:38:34 +0000874 if self.cache_dir:
875 clone_cmd.append('--shared')
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000876 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000877 clone_cmd.append('--verbose')
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000878 clone_cmd.append(url)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000879 # If the parent directory does not exist, Git clone on Windows will not
880 # create it, so we need to do it manually.
881 parent_dir = os.path.dirname(self.checkout_path)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000882 gclient_utils.safe_makedirs(parent_dir)
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000883
884 template_dir = None
885 if hasattr(options, 'no_history') and options.no_history:
886 if gclient_utils.IsGitSha(revision):
887 # In the case of a subproject, the pinned sha is not necessarily the
888 # head of the remote branch (so we can't just use --depth=N). Instead,
889 # we tell git to fetch all the remote objects from SHA..HEAD by means of
890 # a template git dir which has a 'shallow' file pointing to the sha.
891 template_dir = tempfile.mkdtemp(
892 prefix='_gclient_gittmp_%s' % os.path.basename(self.checkout_path),
893 dir=parent_dir)
894 self._Run(['init', '--bare', template_dir], options, cwd=self._root_dir)
895 with open(os.path.join(template_dir, 'shallow'), 'w') as template_file:
896 template_file.write(revision)
897 clone_cmd.append('--template=' + template_dir)
898 else:
899 # Otherwise, we're just interested in the HEAD. Just use --depth.
900 clone_cmd.append('--depth=1')
901
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000902 tmp_dir = tempfile.mkdtemp(
903 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
904 dir=parent_dir)
905 try:
906 clone_cmd.append(tmp_dir)
agable@chromium.orgfd5b6382013-10-25 20:54:34 +0000907 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000908 gclient_utils.safe_makedirs(self.checkout_path)
cyrille@nnamrak.orgef509e42013-09-20 13:19:08 +0000909 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
910 os.path.join(self.checkout_path, '.git'))
zty@chromium.org6279e8a2014-02-13 01:45:25 +0000911 except:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000912 traceback.print_exc(file=self.out_fh)
zty@chromium.org6279e8a2014-02-13 01:45:25 +0000913 raise
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000914 finally:
915 if os.listdir(tmp_dir):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000916 self.Print('_____ removing non-empty tmp dir %s' % tmp_dir)
ilevy@chromium.org3534aa52013-07-20 01:58:08 +0000917 gclient_utils.rmtree(tmp_dir)
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000918 if template_dir:
919 gclient_utils.rmtree(template_dir)
mmoss@chromium.org1a6bec02014-06-02 21:53:29 +0000920 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000921 remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
922 self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
romain.pokrzywka@gmail.com483a0ba2014-05-30 00:06:07 +0000923 if self._GetCurrentBranch() is None:
msb@chromium.org786fb682010-06-02 15:16:23 +0000924 # Squelch git's very verbose detached HEAD warning and use our own
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000925 self.Print(
smut@google.comd33eab32014-07-07 19:35:18 +0000926 ('Checked out %s to a detached HEAD. Before making any commits\n'
927 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
928 'an existing branch or use \'git checkout %s -b <branch>\' to\n'
929 'create a new branch for your work.') % (revision, self.remote))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000930
szager@chromium.org6cd41b62014-04-21 23:55:22 +0000931 def _AskForData(self, prompt, options):
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000932 if options.jobs > 1:
szager@chromium.org6cd41b62014-04-21 23:55:22 +0000933 self.Print(prompt)
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000934 raise gclient_utils.Error("Background task requires input. Rerun "
935 "gclient with --jobs=1 so that\n"
936 "interaction is possible.")
937 try:
938 return raw_input(prompt)
939 except KeyboardInterrupt:
940 # Hide the exception.
941 sys.exit(1)
942
943
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000944 def _AttemptRebase(self, upstream, files, options, newbase=None,
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000945 branch=None, printed_path=False, merge=False):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000946 """Attempt to rebase onto either upstream or, if specified, newbase."""
iannucci@chromium.org396e1a62013-07-03 19:41:04 +0000947 if files is not None:
948 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000949 revision = upstream
950 if newbase:
951 revision = newbase
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000952 action = 'merge' if merge else 'rebase'
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000953 if not printed_path:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000954 self.Print('_____ %s : Attempting %s onto %s...' % (
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000955 self.relpath, action, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000956 printed_path = True
957 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000958 self.Print('Attempting %s onto %s...' % (action, revision))
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000959
960 if merge:
961 merge_output = self._Capture(['merge', revision])
962 if options.verbose:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000963 self.Print(merge_output)
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000964 return
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000965
966 # Build the rebase command here using the args
967 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
968 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000969 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000970 rebase_cmd.append('--verbose')
971 if newbase:
972 rebase_cmd.extend(['--onto', newbase])
973 rebase_cmd.append(upstream)
974 if branch:
975 rebase_cmd.append(branch)
976
977 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000978 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000979 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000980 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
981 re.match(r'cannot rebase: your index contains uncommitted changes',
982 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000983 while True:
bauerb@chromium.org30c46d62014-01-23 12:11:56 +0000984 rebase_action = self._AskForData(
maruel@chromium.org90541732011-04-01 17:54:18 +0000985 'Cannot rebase because of unstaged changes.\n'
986 '\'git reset --hard HEAD\' ?\n'
987 'WARNING: destroys any uncommitted work in your current branch!'
bratell@opera.com18fa4542013-05-21 13:30:46 +0000988 ' (y)es / (q)uit / (s)how : ', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000989 if re.match(r'yes|y', rebase_action, re.I):
Robert Iannuccic41d8b92017-02-16 17:07:37 -0800990 self._Scrub('HEAD', options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000991 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000992 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000993 break
994 elif re.match(r'quit|q', rebase_action, re.I):
995 raise gclient_utils.Error("Please merge or rebase manually\n"
996 "cd %s && git " % self.checkout_path
997 + "%s" % ' '.join(rebase_cmd))
998 elif re.match(r'show|s', rebase_action, re.I):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +0000999 self.Print('%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +00001000 continue
1001 else:
1002 gclient_utils.Error("Input not recognized")
1003 continue
1004 elif re.search(r'^CONFLICT', e.stdout, re.M):
1005 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
1006 "Fix the conflict and run gclient again.\n"
1007 "See 'man git-rebase' for details.\n")
1008 else:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001009 self.Print(e.stdout.strip())
1010 self.Print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +00001011 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
1012 "manually.\ncd %s && git " %
1013 self.checkout_path
1014 + "%s" % ' '.join(rebase_cmd))
1015
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001016 self.Print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +00001017 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +00001018 # Make the output a little prettier. It's nice to have some
1019 # whitespace between projects when syncing.
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001020 self.Print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +00001021
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001022 @staticmethod
1023 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +00001024 (ok, current_version) = scm.GIT.AssertVersion(min_version)
1025 if not ok:
1026 raise gclient_utils.Error('git version %s < minimum required %s' %
1027 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +00001028
tandrii@chromium.orgc438c142015-08-24 22:55:55 +00001029 def _EnsureValidHeadObjectOrCheckout(self, revision, options, url):
1030 # Special case handling if all 3 conditions are met:
1031 # * the mirros have recently changed, but deps destination remains same,
1032 # * the git histories of mirrors are conflicting.
1033 # * git cache is used
1034 # This manifests itself in current checkout having invalid HEAD commit on
1035 # most git operations. Since git cache is used, just deleted the .git
1036 # folder, and re-create it by cloning.
1037 try:
1038 self._Capture(['rev-list', '-n', '1', 'HEAD'])
1039 except subprocess2.CalledProcessError as e:
1040 if ('fatal: bad object HEAD' in e.stderr
1041 and self.cache_dir and self.cache_dir in url):
1042 self.Print((
1043 'Likely due to DEPS change with git cache_dir, '
1044 'the current commit points to no longer existing object.\n'
1045 '%s' % e)
1046 )
1047 self._DeleteOrMove(options.force)
1048 self._Clone(revision, url, options)
1049 else:
1050 raise
1051
msb@chromium.org786fb682010-06-02 15:16:23 +00001052 def _IsRebasing(self):
1053 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
1054 # have a plumbing command to determine whether a rebase is in progress, so
1055 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
1056 g = os.path.join(self.checkout_path, '.git')
1057 return (
1058 os.path.isdir(os.path.join(g, "rebase-merge")) or
1059 os.path.isdir(os.path.join(g, "rebase-apply")))
1060
Robert Iannuccic41d8b92017-02-16 17:07:37 -08001061 def _CheckClean(self, revision, fixup=False):
iannucci@chromium.orgd9b318c2015-12-04 20:03:08 +00001062 lockfile = os.path.join(self.checkout_path, ".git", "index.lock")
1063 if os.path.exists(lockfile):
1064 raise gclient_utils.Error(
agable83faed02016-10-24 14:37:10 -07001065 '\n____ %s at %s\n'
iannucci@chromium.orgd9b318c2015-12-04 20:03:08 +00001066 '\tYour repo is locked, possibly due to a concurrent git process.\n'
1067 '\tIf no git executable is running, then clean up %r and try again.\n'
agable83faed02016-10-24 14:37:10 -07001068 % (self.relpath, revision, lockfile))
iannucci@chromium.orgd9b318c2015-12-04 20:03:08 +00001069
msb@chromium.org786fb682010-06-02 15:16:23 +00001070 # Make sure the tree is clean; see git-rebase.sh for reference
1071 try:
1072 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +00001073 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001074 except subprocess2.CalledProcessError:
agable83faed02016-10-24 14:37:10 -07001075 raise gclient_utils.Error('\n____ %s at %s\n'
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001076 '\tYou have unstaged changes.\n'
1077 '\tPlease commit, stash, or reset.\n'
agable83faed02016-10-24 14:37:10 -07001078 % (self.relpath, revision))
msb@chromium.org786fb682010-06-02 15:16:23 +00001079 try:
1080 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
smut@google.com27c9c8a2014-09-11 19:57:55 +00001081 '--ignore-submodules', 'HEAD', '--'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +00001082 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001083 except subprocess2.CalledProcessError:
agable83faed02016-10-24 14:37:10 -07001084 raise gclient_utils.Error('\n____ %s at %s\n'
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001085 '\tYour index contains uncommitted changes\n'
1086 '\tPlease commit, stash, or reset.\n'
agable83faed02016-10-24 14:37:10 -07001087 % (self.relpath, revision))
msb@chromium.org786fb682010-06-02 15:16:23 +00001088
agable83faed02016-10-24 14:37:10 -07001089 def _CheckDetachedHead(self, revision, _options):
msb@chromium.org786fb682010-06-02 15:16:23 +00001090 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
1091 # reference by a commit). If not, error out -- most likely a rebase is
1092 # in progress, try to detect so we can give a better error.
1093 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +00001094 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
1095 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +00001096 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +00001097 # Commit is not contained by any rev. See if the user is rebasing:
1098 if self._IsRebasing():
1099 # Punt to the user
agable83faed02016-10-24 14:37:10 -07001100 raise gclient_utils.Error('\n____ %s at %s\n'
msb@chromium.org786fb682010-06-02 15:16:23 +00001101 '\tAlready in a conflict, i.e. (no branch).\n'
1102 '\tFix the conflict and run gclient again.\n'
1103 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
1104 '\tSee man git-rebase for details.\n'
agable83faed02016-10-24 14:37:10 -07001105 % (self.relpath, revision))
msb@chromium.org786fb682010-06-02 15:16:23 +00001106 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001107 name = ('saved-by-gclient-' +
1108 self._Capture(['rev-parse', '--short', 'HEAD']))
mmoss@chromium.org77bd7362013-09-25 23:46:14 +00001109 self._Capture(['branch', '-f', name])
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001110 self.Print('_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +00001111 name)
msb@chromium.org786fb682010-06-02 15:16:23 +00001112
msb@chromium.org5bde4852009-12-14 16:47:12 +00001113 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +00001114 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001115 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +00001116 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +00001117 return None
1118 return branch
1119
borenet@google.comc3e09d22014-04-10 13:58:18 +00001120 def _Capture(self, args, **kwargs):
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001121 kwargs.setdefault('cwd', self.checkout_path)
1122 kwargs.setdefault('stderr', subprocess2.PIPE)
szager@chromium.org6d8115d2014-04-23 20:59:23 +00001123 env = scm.GIT.ApplyEnvVars(kwargs)
1124 return subprocess2.check_output(['git'] + args, env=env, **kwargs).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +00001125
dnj@chromium.orgbb424c02014-06-23 22:42:51 +00001126 def _Checkout(self, options, ref, force=False, quiet=None):
1127 """Performs a 'git-checkout' operation.
1128
1129 Args:
1130 options: The configured option set
1131 ref: (str) The branch/commit to checkout
1132 quiet: (bool/None) Whether or not the checkout shoud pass '--quiet'; if
1133 'None', the behavior is inferred from 'options.verbose'.
1134 Returns: (str) The output of the checkout operation
1135 """
1136 if quiet is None:
1137 quiet = (not options.verbose)
1138 checkout_args = ['checkout']
1139 if force:
1140 checkout_args.append('--force')
1141 if quiet:
1142 checkout_args.append('--quiet')
1143 checkout_args.append(ref)
1144 return self._Capture(checkout_args)
1145
dnj@chromium.org680f2172014-06-25 00:39:32 +00001146 def _Fetch(self, options, remote=None, prune=False, quiet=False):
1147 cfg = gclient_utils.DefaultIndexPackConfig(self.url)
1148 fetch_cmd = cfg + [
1149 'fetch',
1150 remote or self.remote,
1151 ]
1152
1153 if prune:
1154 fetch_cmd.append('--prune')
1155 if options.verbose:
1156 fetch_cmd.append('--verbose')
1157 elif quiet:
1158 fetch_cmd.append('--quiet')
tandrii64103db2016-10-11 05:30:05 -07001159 self._Run(fetch_cmd, options, show_header=options.verbose, retry=True)
dnj@chromium.org680f2172014-06-25 00:39:32 +00001160
1161 # Return the revision that was fetched; this will be stored in 'FETCH_HEAD'
1162 return self._Capture(['rev-parse', '--verify', 'FETCH_HEAD'])
1163
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001164 def _UpdateBranchHeads(self, options, fetch=False):
szager@chromium.org8d3348f2014-08-19 22:49:16 +00001165 """Adds, and optionally fetches, "branch-heads" and "tags" refspecs
1166 if requested."""
1167 need_fetch = fetch
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001168 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
maruel@chromium.org1a60dca2013-11-26 14:06:26 +00001169 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
szager@chromium.orgf2d7d6b2013-10-17 20:41:43 +00001170 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1171 '^\\+refs/branch-heads/\\*:.*$']
1172 self._Run(config_cmd, options)
szager@chromium.org8d3348f2014-08-19 22:49:16 +00001173 need_fetch = True
1174 if hasattr(options, 'with_tags') and options.with_tags:
1175 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
1176 '+refs/tags/*:refs/tags/*',
1177 '^\\+refs/tags/\\*:.*$']
1178 self._Run(config_cmd, options)
1179 need_fetch = True
1180 if fetch and need_fetch:
bpastene2a3e9912016-09-07 16:22:25 -07001181 self._Fetch(options, prune=options.force)
mmoss@chromium.orge409df62013-04-16 17:28:57 +00001182
dnj@chromium.org680f2172014-06-25 00:39:32 +00001183 def _Run(self, args, options, show_header=True, **kwargs):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -08001184 # Disable 'unused options' warning | pylint: disable=unused-argument
sbc@chromium.org2cd0b8e2014-09-22 21:17:59 +00001185 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001186 kwargs.setdefault('stdout', self.out_fh)
szager@chromium.org848fd492014-04-09 19:06:44 +00001187 kwargs['filter_fn'] = self.filter
szager@chromium.orgfe0d1902014-04-08 20:50:44 +00001188 kwargs.setdefault('print_stdout', False)
szager@chromium.org6d8115d2014-04-23 20:59:23 +00001189 env = scm.GIT.ApplyEnvVars(kwargs)
agable@chromium.org772efaf2014-04-01 02:35:44 +00001190 cmd = ['git'] + args
dnj@chromium.org680f2172014-06-25 00:39:32 +00001191 if show_header:
sbc@chromium.org2cd0b8e2014-09-22 21:17:59 +00001192 gclient_utils.CheckCallAndFilterAndHeader(cmd, env=env, **kwargs)
1193 else:
1194 gclient_utils.CheckCallAndFilter(cmd, env=env, **kwargs)