blob: b0ca58281781b1bfa08a7c8ac31a1e036b438e43 [file] [log] [blame]
[email protected]93567042012-02-15 01:02:261# Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]5aeb7dd2009-11-17 18:09:012# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
[email protected]5f3eee32009-09-17 00:34:304
[email protected]d5800f12009-11-12 20:03:435"""Gclient-specific SCM-specific operations."""
[email protected]5f3eee32009-09-17 00:34:306
[email protected]fe0d1902014-04-08 20:50:447from __future__ import print_function
8
[email protected]754960e2009-09-21 12:31:059import logging
[email protected]5f3eee32009-09-17 00:34:3010import os
[email protected]ee4071d2009-12-22 22:25:3711import posixpath
[email protected]5f3eee32009-09-17 00:34:3012import re
[email protected]88d10082014-03-21 17:24:4813import shlex
[email protected]90541732011-04-01 17:54:1814import sys
[email protected]3534aa52013-07-20 01:58:0815import tempfile
[email protected]6279e8a2014-02-13 01:45:2516import traceback
[email protected]2f2ca142014-01-07 03:59:1817import urlparse
[email protected]5f3eee32009-09-17 00:34:3018
[email protected]2f2ca142014-01-07 03:59:1819import download_from_google_storage
[email protected]5f3eee32009-09-17 00:34:3020import gclient_utils
[email protected]848fd492014-04-09 19:06:4421import git_cache
[email protected]31cb48a2011-04-04 18:01:3622import scm
23import subprocess2
[email protected]5f3eee32009-09-17 00:34:3024
25
[email protected]71cbb502013-04-19 23:30:1526THIS_FILE_PATH = os.path.abspath(__file__)
27
[email protected]2f2ca142014-01-07 03:59:1828GSUTIL_DEFAULT_PATH = os.path.join(
29 os.path.dirname(os.path.abspath(__file__)),
30 'third_party', 'gsutil', 'gsutil')
31
[email protected]848fd492014-04-09 19:06:4432CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src.git'
[email protected]306080c2012-05-04 13:11:2933class DiffFiltererWrapper(object):
34 """Simple base class which tracks which file is being diffed and
[email protected]ee4071d2009-12-22 22:25:3735 replaces instances of its file name in the original and
[email protected]d6504212010-01-13 17:34:3136 working copy lines of the svn/git diff output."""
[email protected]306080c2012-05-04 13:11:2937 index_string = None
[email protected]ee4071d2009-12-22 22:25:3738 original_prefix = "--- "
39 working_prefix = "+++ "
40
[email protected]fe0d1902014-04-08 20:50:4441 def __init__(self, relpath, print_func):
[email protected]ee4071d2009-12-22 22:25:3742 # 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("\\", "/")
[email protected]306080c2012-05-04 13:11:2945 self._current_file = None
[email protected]fe0d1902014-04-08 20:50:4446 self._print_func = print_func
[email protected]ee4071d2009-12-22 22:25:3747
[email protected]6e29d572010-06-04 17:32:2048 def SetCurrentFile(self, current_file):
49 self._current_file = current_file
[email protected]306080c2012-05-04 13:11:2950
[email protected]3830a672013-02-19 20:15:1451 @property
52 def _replacement_file(self):
[email protected]306080c2012-05-04 13:11:2953 return posixpath.join(self._relpath, self._current_file)
[email protected]ee4071d2009-12-22 22:25:3754
[email protected]f5d37bf2010-09-02 00:50:3455 def _Replace(self, line):
56 return line.replace(self._current_file, self._replacement_file)
[email protected]ee4071d2009-12-22 22:25:3757
58 def Filter(self, line):
59 if (line.startswith(self.index_string)):
60 self.SetCurrentFile(line[len(self.index_string):])
[email protected]f5d37bf2010-09-02 00:50:3461 line = self._Replace(line)
[email protected]ee4071d2009-12-22 22:25:3762 else:
63 if (line.startswith(self.original_prefix) or
64 line.startswith(self.working_prefix)):
[email protected]f5d37bf2010-09-02 00:50:3465 line = self._Replace(line)
[email protected]fe0d1902014-04-08 20:50:4466 self._print_func(line)
[email protected]ee4071d2009-12-22 22:25:3767
68
[email protected]306080c2012-05-04 13:11:2969class 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
[email protected]5f3eee32009-09-17 00:34:3084### SCM abstraction layer
85
[email protected]cb5442b2009-09-22 16:51:2486# Factory Method for SCM wrapper creation
87
[email protected]9eda4112010-06-11 18:56:1088def GetScmName(url):
89 if url:
90 url, _ = gclient_utils.SplitUrlRevision(url)
91 if (url.startswith('git://') or url.startswith('ssh://') or
[email protected]4e075672011-11-21 16:35:0892 url.startswith('git+http://') or url.startswith('git+https://') or
[email protected]a2aec972014-04-22 21:35:1593 url.endswith('.git') or url.startswith('sso://') or
94 'googlesource' in url):
[email protected]9eda4112010-06-11 18:56:1095 return 'git'
[email protected]b74dca22010-06-11 20:10:4096 elif (url.startswith('http://') or url.startswith('https://') or
[email protected]54a07a22010-06-14 19:07:3997 url.startswith('svn://') or url.startswith('svn+ssh://')):
[email protected]9eda4112010-06-11 18:56:1098 return 'svn'
99 return None
100
101
[email protected]fe0d1902014-04-08 20:50:44102def CreateSCM(url, root_dir=None, relpath=None, out_fh=None, out_cb=None):
[email protected]9eda4112010-06-11 18:56:10103 SCM_MAP = {
[email protected]cb5442b2009-09-22 16:51:24104 'svn' : SVNWrapper,
[email protected]e28e4982009-09-25 20:51:45105 'git' : GitWrapper,
[email protected]cb5442b2009-09-22 16:51:24106 }
[email protected]e28e4982009-09-25 20:51:45107
[email protected]9eda4112010-06-11 18:56:10108 scm_name = GetScmName(url)
109 if not scm_name in SCM_MAP:
110 raise gclient_utils.Error('No SCM found for url %s' % url)
[email protected]9e3e82c2012-04-18 12:55:43111 scm_class = SCM_MAP[scm_name]
112 if not scm_class.BinaryExists():
113 raise gclient_utils.Error('%s command not found' % scm_name)
[email protected]fe0d1902014-04-08 20:50:44114 return scm_class(url, root_dir, relpath, out_fh, out_cb)
[email protected]cb5442b2009-09-22 16:51:24115
116
117# SCMWrapper base class
118
[email protected]5f3eee32009-09-17 00:34:30119class SCMWrapper(object):
120 """Add necessary glue between all the supported SCM.
121
[email protected]d6504212010-01-13 17:34:31122 This is the abstraction layer to bind to different SCM.
123 """
[email protected]fe0d1902014-04-08 20:50:44124
125 def __init__(self, url=None, root_dir=None, relpath=None, out_fh=None,
126 out_cb=None):
[email protected]5f3eee32009-09-17 00:34:30127 self.url = url
[email protected]5e73b0c2009-09-18 19:47:48128 self._root_dir = root_dir
129 if self._root_dir:
130 self._root_dir = self._root_dir.replace('/', os.sep)
131 self.relpath = relpath
132 if self.relpath:
133 self.relpath = self.relpath.replace('/', os.sep)
[email protected]e28e4982009-09-25 20:51:45134 if self.relpath and self._root_dir:
135 self.checkout_path = os.path.join(self._root_dir, self.relpath)
[email protected]fe0d1902014-04-08 20:50:44136 if out_fh is None:
137 out_fh = sys.stdout
138 self.out_fh = out_fh
139 self.out_cb = out_cb
140
141 def Print(self, *args, **kwargs):
142 kwargs.setdefault('file', self.out_fh)
143 if kwargs.pop('timestamp', True):
144 self.out_fh.write('[%s] ' % gclient_utils.Elapsed())
145 print(*args, **kwargs)
[email protected]5f3eee32009-09-17 00:34:30146
[email protected]5f3eee32009-09-17 00:34:30147 def RunCommand(self, command, options, args, file_list=None):
[email protected]6e043f72011-05-02 07:24:32148 commands = ['cleanup', 'update', 'updatesingle', 'revert',
[email protected]4b5b1772010-04-08 01:52:56149 'revinfo', 'status', 'diff', 'pack', 'runhooks']
[email protected]5f3eee32009-09-17 00:34:30150
151 if not command in commands:
152 raise gclient_utils.Error('Unknown command %s' % command)
153
[email protected]cb5442b2009-09-22 16:51:24154 if not command in dir(self):
[email protected]ee4071d2009-12-22 22:25:37155 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
[email protected]9eda4112010-06-11 18:56:10156 command, self.__class__.__name__))
[email protected]cb5442b2009-09-22 16:51:24157
158 return getattr(self, command)(options, args, file_list)
159
[email protected]4e9be262014-04-08 19:40:30160 def GetActualRemoteURL(self, options):
[email protected]88d10082014-03-21 17:24:48161 """Attempt to determine the remote URL for this SCMWrapper."""
[email protected]4e9be262014-04-08 19:40:30162 # Git
[email protected]bda475e2014-03-24 19:04:45163 if os.path.exists(os.path.join(self.checkout_path, '.git')):
[email protected]ce2fccb2014-05-02 00:57:10164 actual_remote_url = shlex.split(scm.GIT.Capture(
[email protected]88d10082014-03-21 17:24:48165 ['config', '--local', '--get-regexp', r'remote.*.url'],
[email protected]c3e09d22014-04-10 13:58:18166 cwd=self.checkout_path))[1]
[email protected]4e9be262014-04-08 19:40:30167
168 # If a cache_dir is used, obtain the actual remote URL from the cache.
169 if getattr(self, 'cache_dir', None):
[email protected]46d09f62014-04-10 18:50:23170 url, _ = gclient_utils.SplitUrlRevision(self.url)
171 mirror = git_cache.Mirror(url)
[email protected]848fd492014-04-09 19:06:44172 if (mirror.exists() and mirror.mirror_path.replace('\\', '/') ==
[email protected]4e9be262014-04-08 19:40:30173 actual_remote_url.replace('\\', '/')):
[email protected]ce2fccb2014-05-02 00:57:10174 actual_remote_url = shlex.split(scm.GIT.Capture(
[email protected]4e9be262014-04-08 19:40:30175 ['config', '--local', '--get-regexp', r'remote.*.url'],
[email protected]848fd492014-04-09 19:06:44176 cwd=mirror.mirror_path))[1]
[email protected]4e9be262014-04-08 19:40:30177 return actual_remote_url
178
179 # Svn
[email protected]bda475e2014-03-24 19:04:45180 if os.path.exists(os.path.join(self.checkout_path, '.svn')):
[email protected]88d10082014-03-21 17:24:48181 return scm.SVN.CaptureLocalInfo([], self.checkout_path)['URL']
[email protected]88d10082014-03-21 17:24:48182 return None
183
[email protected]4e9be262014-04-08 19:40:30184 def DoesRemoteURLMatch(self, options):
[email protected]88d10082014-03-21 17:24:48185 """Determine whether the remote URL of this checkout is the expected URL."""
186 if not os.path.exists(self.checkout_path):
187 # A checkout which doesn't exist can't be broken.
188 return True
189
[email protected]4e9be262014-04-08 19:40:30190 actual_remote_url = self.GetActualRemoteURL(options)
[email protected]88d10082014-03-21 17:24:48191 if actual_remote_url:
[email protected]8156c9f2014-04-01 16:41:36192 return (gclient_utils.SplitUrlRevision(actual_remote_url)[0].rstrip('/')
193 == gclient_utils.SplitUrlRevision(self.url)[0].rstrip('/'))
[email protected]88d10082014-03-21 17:24:48194 else:
195 # This may occur if the self.checkout_path exists but does not contain a
196 # valid git or svn checkout.
197 return False
198
[email protected]b09097a2014-04-09 19:09:08199 # TODO(borenet): Remove this once SCMWrapper._DeleteOrMove is enabled.
200 # pylint: disable=R0201
201 def _DeleteOrMove(self, force):
202 """Delete the checkout directory or move it out of the way.
203
204 Args:
205 force: bool; if True, delete the directory. Otherwise, just move it.
206 """
207 gclient_utils.AddWarning('WARNING: Upcoming change in '
208 'https://codereview.chromium.org/225403015 would '
209 'cause %s to be deleted or moved to the side. '
210 'This is intended to ease changes to DEPS in the '
211 'future. If you are seeing this warning and '
212 'haven\'t changed the DEPS file, please contact '
213 'borenet@ immediately.' % self.checkout_path)
214
[email protected]cb5442b2009-09-22 16:51:24215
[email protected]55e724e2010-03-11 19:36:49216class GitWrapper(SCMWrapper):
[email protected]e28e4982009-09-25 20:51:45217 """Wrapper for Git"""
[email protected]2702bcd2013-09-24 19:10:07218 name = 'git'
[email protected]1a60dca2013-11-26 14:06:26219 remote = 'origin'
[email protected]e28e4982009-09-25 20:51:45220
[email protected]53456aa2013-07-03 19:38:34221 cache_dir = None
[email protected]53456aa2013-07-03 19:38:34222
[email protected]848fd492014-04-09 19:06:44223 def __init__(self, url=None, *args):
[email protected]4e075672011-11-21 16:35:08224 """Removes 'git+' fake prefix from git URL."""
225 if url.startswith('git+http://') or url.startswith('git+https://'):
226 url = url[4:]
[email protected]848fd492014-04-09 19:06:44227 SCMWrapper.__init__(self, url, *args)
228 filter_kwargs = { 'time_throttle': 1, 'out_fh': self.out_fh }
229 if self.out_cb:
230 filter_kwargs['predicate'] = self.out_cb
231 self.filter = gclient_utils.GitFilter(**filter_kwargs)
[email protected]4e075672011-11-21 16:35:08232
[email protected]9e3e82c2012-04-18 12:55:43233 @staticmethod
234 def BinaryExists():
235 """Returns true if the command exists."""
236 try:
237 # We assume git is newer than 1.7. See: crbug.com/114483
238 result, version = scm.GIT.AssertVersion('1.7')
239 if not result:
240 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
241 return result
242 except OSError:
243 return False
244
[email protected]885a9602013-05-31 09:54:40245 def GetCheckoutRoot(self):
246 return scm.GIT.GetCheckoutRoot(self.checkout_path)
247
[email protected]396e1a62013-07-03 19:41:04248 def GetRevisionDate(self, _revision):
[email protected]eaab7842011-04-28 09:07:58249 """Returns the given revision's date in ISO-8601 format (which contains the
250 time zone)."""
251 # TODO(floitsch): get the time-stamp of the given revision and not just the
252 # time-stamp of the currently checked out revision.
253 return self._Capture(['log', '-n', '1', '--format=%ai'])
254
[email protected]6e29d572010-06-04 17:32:20255 @staticmethod
256 def cleanup(options, args, file_list):
[email protected]d8a63782010-01-25 17:47:05257 """'Cleanup' the repo.
258
259 There's no real git equivalent for the svn cleanup command, do a no-op.
260 """
[email protected]e28e4982009-09-25 20:51:45261
[email protected]396e1a62013-07-03 19:41:04262 def diff(self, options, _args, _file_list):
[email protected]1a60dca2013-11-26 14:06:26263 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
[email protected]37e89872010-09-07 16:11:33264 self._Run(['diff', merge_base], options)
[email protected]e28e4982009-09-25 20:51:45265
[email protected]396e1a62013-07-03 19:41:04266 def pack(self, _options, _args, _file_list):
[email protected]ee4071d2009-12-22 22:25:37267 """Generates a patch file which can be applied to the root of the
[email protected]d6504212010-01-13 17:34:31268 repository.
269
270 The patch file is generated from a diff of the merge base of HEAD and
271 its upstream branch.
272 """
[email protected]1a60dca2013-11-26 14:06:26273 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
[email protected]17d01792010-09-01 18:07:10274 gclient_utils.CheckCallAndFilter(
[email protected]8469bf92010-09-03 19:03:15275 ['git', 'diff', merge_base],
276 cwd=self.checkout_path,
[email protected]fe0d1902014-04-08 20:50:44277 filter_fn=GitDiffFilterer(self.relpath).Filter, print_func=self.Print)
[email protected]ee4071d2009-12-22 22:25:37278
[email protected]50fd47f2014-02-13 01:03:19279 def _FetchAndReset(self, revision, file_list, options):
280 """Equivalent to git fetch; git reset."""
281 quiet = []
282 if not options.verbose:
283 quiet = ['--quiet']
284 self._UpdateBranchHeads(options, fetch=False)
285
[email protected]ff113292014-03-25 06:02:08286 cfg = gclient_utils.DefaultIndexPackConfig(self.url)
[email protected]fc616382014-03-18 20:32:04287 fetch_cmd = cfg + ['fetch', self.remote, '--prune']
[email protected]50fd47f2014-02-13 01:03:19288 self._Run(fetch_cmd + quiet, options, retry=True)
289 self._Run(['reset', '--hard', revision] + quiet, options)
[email protected]50fd47f2014-02-13 01:03:19290 if file_list is not None:
291 files = self._Capture(['ls-files']).splitlines()
292 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
293
[email protected]e28e4982009-09-25 20:51:45294 def update(self, options, args, file_list):
295 """Runs git to update or transparently checkout the working copy.
296
297 All updated files will be appended to file_list.
298
299 Raises:
300 Error: if can't get URL for relative path.
301 """
[email protected]e28e4982009-09-25 20:51:45302 if args:
303 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
304
[email protected]ece406f2010-02-23 17:29:15305 self._CheckMinVersion("1.6.6")
[email protected]923a0372009-12-11 20:42:43306
[email protected]1a60dca2013-11-26 14:06:26307 # If a dependency is not pinned, track the default remote branch.
308 default_rev = 'refs/remotes/%s/master' % self.remote
[email protected]7080e942010-03-15 15:06:16309 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]ac915bb2009-11-13 17:03:01310 rev_str = ""
[email protected]7080e942010-03-15 15:06:16311 revision = deps_revision
[email protected]eb2756d2011-09-20 20:17:51312 managed = True
[email protected]e28e4982009-09-25 20:51:45313 if options.revision:
[email protected]ac915bb2009-11-13 17:03:01314 # Override the revision number.
315 revision = str(options.revision)
[email protected]eb2756d2011-09-20 20:17:51316 if revision == 'unmanaged':
317 revision = None
318 managed = False
[email protected]d90ba3f2010-02-23 14:42:57319 if not revision:
320 revision = default_rev
[email protected]e28e4982009-09-25 20:51:45321
[email protected]eaab7842011-04-28 09:07:58322 if gclient_utils.IsDateRevision(revision):
323 # Date-revisions only work on git-repositories if the reflog hasn't
324 # expired yet. Use rev-list to get the corresponding revision.
325 # git rev-list -n 1 --before='time-stamp' branchname
326 if options.transitive:
[email protected]fe0d1902014-04-08 20:50:44327 self.Print('Warning: --transitive only works for SVN repositories.')
[email protected]eaab7842011-04-28 09:07:58328 revision = default_rev
329
[email protected]d90ba3f2010-02-23 14:42:57330 rev_str = ' at %s' % revision
[email protected]396e1a62013-07-03 19:41:04331 files = [] if file_list is not None else None
[email protected]d90ba3f2010-02-23 14:42:57332
333 printed_path = False
334 verbose = []
[email protected]b1a22bf2009-11-07 02:33:50335 if options.verbose:
[email protected]fe0d1902014-04-08 20:50:44336 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
[email protected]d90ba3f2010-02-23 14:42:57337 verbose = ['--verbose']
338 printed_path = True
339
[email protected]53456aa2013-07-03 19:38:34340 url = self._CreateOrUpdateCache(url, options)
341
[email protected]a41249c2013-07-03 00:09:12342 if revision.startswith('refs/'):
[email protected]d90ba3f2010-02-23 14:42:57343 rev_type = "branch"
[email protected]1a60dca2013-11-26 14:06:26344 elif revision.startswith(self.remote + '/'):
[email protected]69995f42014-04-25 21:43:29345 # Rewrite remote refs to their local equivalents.
346 revision = 'refs/remotes/' + revision
[email protected]d90ba3f2010-02-23 14:42:57347 rev_type = "branch"
348 else:
349 # hash is also a tag, only make a distinction at checkout
350 rev_type = "hash"
351
[email protected]6c2b49d2014-02-26 23:57:38352 if (not os.path.exists(self.checkout_path) or
353 (os.path.isdir(self.checkout_path) and
354 not os.path.exists(os.path.join(self.checkout_path, '.git')))):
[email protected]90fe58b2014-05-01 18:22:00355 try:
356 self._Clone(revision, url, options)
357 except subprocess2.CalledProcessError:
358 self._DeleteOrMove(options.force)
359 self._Clone(revision, url, options)
[email protected]3676b3f2014-04-08 21:06:11360 self._UpdateBranchHeads(options, fetch=True)
[email protected]048da082014-05-06 08:32:40361 if deps_revision and deps_revision.startswith('branch-heads/'):
362 deps_branch = deps_revision.replace('branch-heads/', '')
363 self._Capture(['branch', deps_branch, deps_revision])
364 self._Capture(['checkout', '--quiet', deps_branch])
[email protected]396e1a62013-07-03 19:41:04365 if file_list is not None:
366 files = self._Capture(['ls-files']).splitlines()
367 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]d90ba3f2010-02-23 14:42:57368 if not verbose:
369 # Make the output a little prettier. It's nice to have some whitespace
370 # between projects when cloning.
[email protected]fe0d1902014-04-08 20:50:44371 self.Print('')
[email protected]2702bcd2013-09-24 19:10:07372 return self._Capture(['rev-parse', '--verify', 'HEAD'])
[email protected]e28e4982009-09-25 20:51:45373
[email protected]6c2b49d2014-02-26 23:57:38374 if not managed:
375 self._UpdateBranchHeads(options, fetch=False)
[email protected]fe0d1902014-04-08 20:50:44376 self.Print('________ unmanaged solution; skipping %s' % self.relpath)
[email protected]6c2b49d2014-02-26 23:57:38377 return self._Capture(['rev-parse', '--verify', 'HEAD'])
378
[email protected]6c2b49d2014-02-26 23:57:38379 # See if the url has changed (the unittests use git://foo for the url, let
380 # that through).
381 current_url = self._Capture(['config', 'remote.%s.url' % self.remote])
382 return_early = False
383 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
384 # unit test pass. (and update the comment above)
385 # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
386 # This allows devs to use experimental repos which have a different url
387 # but whose branch(s) are the same as official repos.
[email protected]b09097a2014-04-09 19:09:08388 if (current_url.rstrip('/') != url.rstrip('/') and
[email protected]6c2b49d2014-02-26 23:57:38389 url != 'git://foo' and
390 subprocess2.capture(
391 ['git', 'config', 'remote.%s.gclient-auto-fix-url' % self.remote],
392 cwd=self.checkout_path).strip() != 'False'):
[email protected]fe0d1902014-04-08 20:50:44393 self.Print('_____ switching %s to a new upstream' % self.relpath)
[email protected]6c2b49d2014-02-26 23:57:38394 # Make sure it's clean
395 self._CheckClean(rev_str)
396 # Switch over to the new upstream
397 self._Run(['remote', 'set-url', self.remote, url], options)
398 self._FetchAndReset(revision, file_list, options)
399 return_early = True
400
[email protected]50fd47f2014-02-13 01:03:19401 if return_early:
402 return self._Capture(['rev-parse', '--verify', 'HEAD'])
403
[email protected]5bde4852009-12-14 16:47:12404 cur_branch = self._GetCurrentBranch()
405
[email protected]d90ba3f2010-02-23 14:42:57406 # Cases:
[email protected]786fb682010-06-02 15:16:23407 # 0) HEAD is detached. Probably from our initial clone.
408 # - make sure HEAD is contained by a named ref, then update.
409 # Cases 1-4. HEAD is a branch.
410 # 1) current branch is not tracking a remote branch (could be git-svn)
411 # - try to rebase onto the new hash or branch
412 # 2) current branch is tracking a remote branch with local committed
413 # changes, but the DEPS file switched to point to a hash
[email protected]d90ba3f2010-02-23 14:42:57414 # - rebase those changes on top of the hash
[email protected]786fb682010-06-02 15:16:23415 # 3) current branch is tracking a remote branch w/or w/out changes,
416 # no switch
[email protected]d90ba3f2010-02-23 14:42:57417 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
[email protected]786fb682010-06-02 15:16:23418 # 4) current branch is tracking a remote branch, switches to a different
419 # remote branch
[email protected]d90ba3f2010-02-23 14:42:57420 # - exit
421
[email protected]81e012c2010-04-29 16:07:24422 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
423 # a tracking branch
[email protected]d90ba3f2010-02-23 14:42:57424 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
425 # or it returns None if it couldn't find an upstream
[email protected]786fb682010-06-02 15:16:23426 if cur_branch is None:
427 upstream_branch = None
428 current_type = "detached"
429 logging.debug("Detached HEAD")
[email protected]d90ba3f2010-02-23 14:42:57430 else:
[email protected]786fb682010-06-02 15:16:23431 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
432 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
433 current_type = "hash"
434 logging.debug("Current branch is not tracking an upstream (remote)"
435 " branch.")
436 elif upstream_branch.startswith('refs/remotes'):
437 current_type = "branch"
438 else:
439 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
[email protected]d90ba3f2010-02-23 14:42:57440
[email protected]a41249c2013-07-03 00:09:12441 if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
[email protected]cbd20a42012-06-27 13:49:27442 # Update the remotes first so we have all the refs.
[email protected]a41249c2013-07-03 00:09:12443 remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
[email protected]cbd20a42012-06-27 13:49:27444 cwd=self.checkout_path)
[email protected]cbd20a42012-06-27 13:49:27445 if verbose:
[email protected]fe0d1902014-04-08 20:50:44446 self.Print(remote_output)
[email protected]d90ba3f2010-02-23 14:42:57447
[email protected]e409df62013-04-16 17:28:57448 self._UpdateBranchHeads(options, fetch=True)
449
[email protected]d90ba3f2010-02-23 14:42:57450 # This is a big hammer, debatable if it should even be here...
[email protected]793796d2010-02-19 17:27:41451 if options.force or options.reset:
[email protected]d4fffee2013-06-28 00:35:26452 target = 'HEAD'
453 if options.upstream and upstream_branch:
454 target = upstream_branch
455 self._Run(['reset', '--hard', target], options)
[email protected]d90ba3f2010-02-23 14:42:57456
[email protected]786fb682010-06-02 15:16:23457 if current_type == 'detached':
458 # case 0
459 self._CheckClean(rev_str)
[email protected]f5d37bf2010-09-02 00:50:34460 self._CheckDetachedHead(rev_str, options)
[email protected]848fd492014-04-09 19:06:44461 if self._Capture(['rev-list', '-n', '1', 'HEAD']) == revision:
462 self.Print('Up-to-date; skipping checkout.')
463 else:
464 self._Capture(['checkout', '--quiet', '%s' % revision])
[email protected]786fb682010-06-02 15:16:23465 if not printed_path:
[email protected]fe0d1902014-04-08 20:50:44466 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
[email protected]786fb682010-06-02 15:16:23467 elif current_type == 'hash':
[email protected]d90ba3f2010-02-23 14:42:57468 # case 1
[email protected]55e724e2010-03-11 19:36:49469 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
[email protected]d90ba3f2010-02-23 14:42:57470 # Our git-svn branch (upstream_branch) is our upstream
[email protected]f5d37bf2010-09-02 00:50:34471 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56472 newbase=revision, printed_path=printed_path,
473 merge=options.merge)
[email protected]d90ba3f2010-02-23 14:42:57474 printed_path = True
475 else:
476 # Can't find a merge-base since we don't know our upstream. That makes
477 # this command VERY likely to produce a rebase failure. For now we
478 # assume origin is our upstream since that's what the old behavior was.
[email protected]1a60dca2013-11-26 14:06:26479 upstream_branch = self.remote
[email protected]7080e942010-03-15 15:06:16480 if options.revision or deps_revision:
[email protected]3b29de12010-03-08 18:34:28481 upstream_branch = revision
[email protected]f5d37bf2010-09-02 00:50:34482 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56483 printed_path=printed_path, merge=options.merge)
[email protected]d90ba3f2010-02-23 14:42:57484 printed_path = True
[email protected]55e724e2010-03-11 19:36:49485 elif rev_type == 'hash':
[email protected]d90ba3f2010-02-23 14:42:57486 # case 2
[email protected]f5d37bf2010-09-02 00:50:34487 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56488 newbase=revision, printed_path=printed_path,
489 merge=options.merge)
[email protected]d90ba3f2010-02-23 14:42:57490 printed_path = True
[email protected]1a60dca2013-11-26 14:06:26491 elif revision.replace('heads', 'remotes/' + self.remote) != upstream_branch:
[email protected]d90ba3f2010-02-23 14:42:57492 # case 4
[email protected]1a60dca2013-11-26 14:06:26493 new_base = revision.replace('heads', 'remotes/' + self.remote)
[email protected]d90ba3f2010-02-23 14:42:57494 if not printed_path:
[email protected]fe0d1902014-04-08 20:50:44495 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
[email protected]d90ba3f2010-02-23 14:42:57496 switch_error = ("Switching upstream branch from %s to %s\n"
497 % (upstream_branch, new_base) +
498 "Please merge or rebase manually:\n" +
499 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
500 "OR git checkout -b <some new branch> %s" % new_base)
501 raise gclient_utils.Error(switch_error)
502 else:
503 # case 3 - the default case
[email protected]396e1a62013-07-03 19:41:04504 if files is not None:
505 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
[email protected]d90ba3f2010-02-23 14:42:57506 if verbose:
[email protected]fe0d1902014-04-08 20:50:44507 self.Print('Trying fast-forward merge to branch : %s' % upstream_branch)
[email protected]d90ba3f2010-02-23 14:42:57508 try:
[email protected]2aad1b22011-07-22 12:00:41509 merge_args = ['merge']
[email protected]30c46d62014-01-23 12:11:56510 if options.merge:
511 merge_args.append('--ff')
512 else:
[email protected]2aad1b22011-07-22 12:00:41513 merge_args.append('--ff-only')
514 merge_args.append(upstream_branch)
[email protected]fe0d1902014-04-08 20:50:44515 merge_output = self._Capture(merge_args)
[email protected]18fa4542013-05-21 13:30:46516 except subprocess2.CalledProcessError as e:
[email protected]d90ba3f2010-02-23 14:42:57517 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
[email protected]30c46d62014-01-23 12:11:56518 files = []
[email protected]d90ba3f2010-02-23 14:42:57519 if not printed_path:
[email protected]fe0d1902014-04-08 20:50:44520 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
[email protected]d90ba3f2010-02-23 14:42:57521 printed_path = True
522 while True:
523 try:
[email protected]30c46d62014-01-23 12:11:56524 action = self._AskForData(
525 'Cannot %s, attempt to rebase? '
526 '(y)es / (q)uit / (s)kip : ' %
527 ('merge' if options.merge else 'fast-forward merge'),
528 options)
[email protected]d90ba3f2010-02-23 14:42:57529 except ValueError:
[email protected]90541732011-04-01 17:54:18530 raise gclient_utils.Error('Invalid Character')
[email protected]d90ba3f2010-02-23 14:42:57531 if re.match(r'yes|y', action, re.I):
[email protected]f5d37bf2010-09-02 00:50:34532 self._AttemptRebase(upstream_branch, files, options,
[email protected]30c46d62014-01-23 12:11:56533 printed_path=printed_path, merge=False)
[email protected]d90ba3f2010-02-23 14:42:57534 printed_path = True
535 break
536 elif re.match(r'quit|q', action, re.I):
537 raise gclient_utils.Error("Can't fast-forward, please merge or "
538 "rebase manually.\n"
539 "cd %s && git " % self.checkout_path
540 + "rebase %s" % upstream_branch)
541 elif re.match(r'skip|s', action, re.I):
[email protected]fe0d1902014-04-08 20:50:44542 self.Print('Skipping %s' % self.relpath)
[email protected]d90ba3f2010-02-23 14:42:57543 return
544 else:
[email protected]fe0d1902014-04-08 20:50:44545 self.Print('Input not recognized')
[email protected]d90ba3f2010-02-23 14:42:57546 elif re.match("error: Your local changes to '.*' would be "
547 "overwritten by merge. Aborting.\nPlease, commit your "
548 "changes or stash them before you can merge.\n",
549 e.stderr):
550 if not printed_path:
[email protected]fe0d1902014-04-08 20:50:44551 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
[email protected]d90ba3f2010-02-23 14:42:57552 printed_path = True
553 raise gclient_utils.Error(e.stderr)
554 else:
555 # Some other problem happened with the merge
556 logging.error("Error during fast-forward merge in %s!" % self.relpath)
[email protected]fe0d1902014-04-08 20:50:44557 self.Print(e.stderr)
[email protected]d90ba3f2010-02-23 14:42:57558 raise
559 else:
560 # Fast-forward merge was successful
561 if not re.match('Already up-to-date.', merge_output) or verbose:
562 if not printed_path:
[email protected]fe0d1902014-04-08 20:50:44563 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
[email protected]d90ba3f2010-02-23 14:42:57564 printed_path = True
[email protected]fe0d1902014-04-08 20:50:44565 self.Print(merge_output.strip())
[email protected]d90ba3f2010-02-23 14:42:57566 if not verbose:
567 # Make the output a little prettier. It's nice to have some
568 # whitespace between projects when syncing.
[email protected]fe0d1902014-04-08 20:50:44569 self.Print('')
[email protected]d90ba3f2010-02-23 14:42:57570
[email protected]396e1a62013-07-03 19:41:04571 if file_list is not None:
572 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]5bde4852009-12-14 16:47:12573
574 # If the rebase generated a conflict, abort and ask user to fix
[email protected]786fb682010-06-02 15:16:23575 if self._IsRebasing():
[email protected]5bde4852009-12-14 16:47:12576 raise gclient_utils.Error('\n____ %s%s\n'
577 '\nConflict while rebasing this branch.\n'
578 'Fix the conflict and run gclient again.\n'
579 'See man git-rebase for details.\n'
580 % (self.relpath, rev_str))
581
[email protected]d90ba3f2010-02-23 14:42:57582 if verbose:
[email protected]fe0d1902014-04-08 20:50:44583 self.Print('Checked out revision %s' % self.revinfo(options, (), None),
584 timestamp=False)
[email protected]e28e4982009-09-25 20:51:45585
[email protected]98e69452012-02-16 16:36:43586 # If --reset and --delete_unversioned_trees are specified, remove any
587 # untracked directories.
588 if options.reset and options.delete_unversioned_trees:
589 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
590 # merge-base by default), so doesn't include untracked files. So we use
591 # 'git ls-files --directory --others --exclude-standard' here directly.
592 paths = scm.GIT.Capture(
593 ['ls-files', '--directory', '--others', '--exclude-standard'],
594 self.checkout_path)
595 for path in (p for p in paths.splitlines() if p.endswith('/')):
596 full_path = os.path.join(self.checkout_path, path)
597 if not os.path.islink(full_path):
[email protected]fe0d1902014-04-08 20:50:44598 self.Print('_____ removing unversioned directory %s' % path)
[email protected]dc112ac2013-04-24 13:00:19599 gclient_utils.rmtree(full_path)
[email protected]98e69452012-02-16 16:36:43600
[email protected]2702bcd2013-09-24 19:10:07601 return self._Capture(['rev-parse', '--verify', 'HEAD'])
602
[email protected]98e69452012-02-16 16:36:43603
[email protected]396e1a62013-07-03 19:41:04604 def revert(self, options, _args, file_list):
[email protected]e28e4982009-09-25 20:51:45605 """Reverts local modifications.
606
607 All reverted files will be appended to file_list.
608 """
[email protected]8469bf92010-09-03 19:03:15609 if not os.path.isdir(self.checkout_path):
[email protected]260c6532009-10-28 03:22:35610 # revert won't work if the directory doesn't exist. It needs to
611 # checkout instead.
[email protected]fe0d1902014-04-08 20:50:44612 self.Print('_____ %s is missing, synching instead' % self.relpath)
[email protected]260c6532009-10-28 03:22:35613 # Don't reuse the args.
614 return self.update(options, [], file_list)
[email protected]b2b46312010-04-30 20:58:03615
616 default_rev = "refs/heads/master"
[email protected]d4fffee2013-06-28 00:35:26617 if options.upstream:
618 if self._GetCurrentBranch():
619 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
620 default_rev = upstream_branch or default_rev
[email protected]6e29d572010-06-04 17:32:20621 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]b2b46312010-04-30 20:58:03622 if not deps_revision:
623 deps_revision = default_rev
624 if deps_revision.startswith('refs/heads/'):
[email protected]1a60dca2013-11-26 14:06:26625 deps_revision = deps_revision.replace('refs/heads/', self.remote + '/')
[email protected]9a8b0662014-02-20 00:56:15626 deps_revision = self.GetUsableRev(deps_revision, options)
[email protected]b2b46312010-04-30 20:58:03627
[email protected]396e1a62013-07-03 19:41:04628 if file_list is not None:
629 files = self._Capture(['diff', deps_revision, '--name-only']).split()
630
[email protected]37e89872010-09-07 16:11:33631 self._Run(['reset', '--hard', deps_revision], options)
[email protected]ade83db2012-09-27 14:06:49632 self._Run(['clean', '-f', '-d'], options)
[email protected]e28e4982009-09-25 20:51:45633
[email protected]396e1a62013-07-03 19:41:04634 if file_list is not None:
635 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
636
637 def revinfo(self, _options, _args, _file_list):
[email protected]6cafa132010-09-07 14:17:26638 """Returns revision"""
639 return self._Capture(['rev-parse', 'HEAD'])
[email protected]0f282062009-11-06 20:14:02640
[email protected]e28e4982009-09-25 20:51:45641 def runhooks(self, options, args, file_list):
642 self.status(options, args, file_list)
643
[email protected]396e1a62013-07-03 19:41:04644 def status(self, options, _args, file_list):
[email protected]e28e4982009-09-25 20:51:45645 """Display status information."""
646 if not os.path.isdir(self.checkout_path):
[email protected]fe0d1902014-04-08 20:50:44647 self.Print('________ couldn\'t run status in %s:\n'
648 'The directory does not exist.' % self.checkout_path)
[email protected]e28e4982009-09-25 20:51:45649 else:
[email protected]1a60dca2013-11-26 14:06:26650 merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
[email protected]fe0d1902014-04-08 20:50:44651 self._Run(['diff', '--name-status', merge_base], options,
652 stdout=self.out_fh)
[email protected]396e1a62013-07-03 19:41:04653 if file_list is not None:
654 files = self._Capture(['diff', '--name-only', merge_base]).split()
655 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
[email protected]e28e4982009-09-25 20:51:45656
[email protected]e5d1e612011-12-19 19:49:19657 def GetUsableRev(self, rev, options):
658 """Finds a useful revision for this repository.
659
660 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
661 will be called on the source."""
662 sha1 = None
[email protected]3830a672013-02-19 20:15:14663 if not os.path.isdir(self.checkout_path):
664 raise gclient_utils.Error(
665 ( 'We could not find a valid hash for safesync_url response "%s".\n'
666 'Safesync URLs with a git checkout currently require the repo to\n'
667 'be cloned without a safesync_url before adding the safesync_url.\n'
668 'For more info, see: '
669 'http://code.google.com/p/chromium/wiki/UsingNewGit'
670 '#Initial_checkout' ) % rev)
671 elif rev.isdigit() and len(rev) < 7:
672 # Handles an SVN rev. As an optimization, only verify an SVN revision as
673 # [0-9]{1,6} for now to avoid making a network request.
[email protected]6c2b49d2014-02-26 23:57:38674 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
[email protected]051c88b2011-12-22 00:23:03675 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
676 if not local_head or local_head < int(rev):
[email protected]2a75fdb2012-02-15 01:32:57677 try:
678 logging.debug('Looking for git-svn configuration optimizations.')
679 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
680 cwd=self.checkout_path):
681 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
682 except subprocess2.CalledProcessError:
683 logging.debug('git config --get svn-remote.svn.fetch failed, '
684 'ignoring possible optimization.')
[email protected]051c88b2011-12-22 00:23:03685 if options.verbose:
[email protected]fe0d1902014-04-08 20:50:44686 self.Print('Running git svn fetch. This might take a while.\n')
[email protected]051c88b2011-12-22 00:23:03687 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
[email protected]312a6a42012-10-11 21:19:42688 try:
[email protected]c51def32012-10-15 18:50:37689 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
690 cwd=self.checkout_path, rev=rev)
[email protected]312a6a42012-10-11 21:19:42691 except gclient_utils.Error, e:
692 sha1 = e.message
[email protected]fe0d1902014-04-08 20:50:44693 self.Print('Warning: Could not find a git revision with accurate\n'
[email protected]312a6a42012-10-11 21:19:42694 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
695 'the closest sane git revision, which is:\n'
696 ' %s\n' % (rev, e.message))
[email protected]051c88b2011-12-22 00:23:03697 if not sha1:
698 raise gclient_utils.Error(
699 ( 'It appears that either your git-svn remote is incorrectly\n'
700 'configured or the revision in your safesync_url is\n'
701 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
702 'corresponding git hash for SVN rev %s.' ) % rev)
[email protected]3830a672013-02-19 20:15:14703 else:
704 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
705 sha1 = rev
706 else:
707 # May exist in origin, but we don't have it yet, so fetch and look
708 # again.
[email protected]1a60dca2013-11-26 14:06:26709 scm.GIT.Capture(['fetch', self.remote], cwd=self.checkout_path)
[email protected]3830a672013-02-19 20:15:14710 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
711 sha1 = rev
[email protected]051c88b2011-12-22 00:23:03712
[email protected]e5d1e612011-12-19 19:49:19713 if not sha1:
714 raise gclient_utils.Error(
[email protected]051c88b2011-12-22 00:23:03715 ( 'We could not find a valid hash for safesync_url response "%s".\n'
716 'Safesync URLs with a git checkout currently require a git-svn\n'
717 'remote or a safesync_url that provides git sha1s. Please add a\n'
718 'git-svn remote or change your safesync_url. For more info, see:\n'
[email protected]e5d1e612011-12-19 19:49:19719 'http://code.google.com/p/chromium/wiki/UsingNewGit'
[email protected]051c88b2011-12-22 00:23:03720 '#Initial_checkout' ) % rev)
721
[email protected]e5d1e612011-12-19 19:49:19722 return sha1
723
[email protected]e6f78352010-01-13 17:05:33724 def FullUrlForRelativeUrl(self, url):
725 # Strip from last '/'
726 # Equivalent to unix basename
727 base_url = self.url
728 return base_url[:base_url.rfind('/')] + url
729
[email protected]53456aa2013-07-03 19:38:34730 def _CreateOrUpdateCache(self, url, options):
731 """Make a new git mirror or update existing mirror for |url|, and return the
732 mirror URI to clone from.
733
734 If no cache-dir is specified, just return |url| unchanged.
735 """
736 if not self.cache_dir:
737 return url
[email protected]b1b54572014-04-16 22:29:23738 mirror_kwargs = {
739 'print_func': self.filter,
740 'refs': []
741 }
[email protected]356cb5f2014-04-25 00:02:21742 # TODO(hinoka): This currently just fails because lkcr/lkgr are branches
743 # not tags. This also adds 20 seconds to every bot_update
744 # run, so I'm commenting this out until lkcr/lkgr become
745 # tags. (2014/4/24)
746 # if url == CHROMIUM_SRC_URL or url + '.git' == CHROMIUM_SRC_URL:
747 # mirror_kwargs['refs'].extend(['refs/tags/lkgr', 'refs/tags/lkcr'])
[email protected]b1b54572014-04-16 22:29:23748 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
749 mirror_kwargs['refs'].append('refs/branch-heads/*')
[email protected]848fd492014-04-09 19:06:44750 mirror = git_cache.Mirror(url, **mirror_kwargs)
751 mirror.populate(verbose=options.verbose, bootstrap=True)
752 mirror.unlock()
753 return mirror.mirror_path if mirror.exists() else None
[email protected]53456aa2013-07-03 19:38:34754
[email protected]f5d37bf2010-09-02 00:50:34755 def _Clone(self, revision, url, options):
[email protected]d90ba3f2010-02-23 14:42:57756 """Clone a git repository from the given URL.
757
[email protected]786fb682010-06-02 15:16:23758 Once we've cloned the repo, we checkout a working branch if the specified
759 revision is a branch head. If it is a tag or a specific commit, then we
760 leave HEAD detached as it makes future updates simpler -- in this case the
761 user should first create a new branch or switch to an existing branch before
762 making changes in the repo."""
[email protected]f5d37bf2010-09-02 00:50:34763 if not options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57764 # git clone doesn't seem to insert a newline properly before printing
765 # to stdout
[email protected]fe0d1902014-04-08 20:50:44766 self.Print('')
[email protected]ecb75422013-07-12 21:57:33767 template_path = os.path.join(
768 os.path.dirname(THIS_FILE_PATH), 'git-templates')
[email protected]f1d73eb2014-04-21 17:07:04769 cfg = gclient_utils.DefaultIndexPackConfig(url)
[email protected]fc616382014-03-18 20:32:04770 clone_cmd = cfg + [
771 'clone', '--no-checkout', '--progress', '--template=%s' % template_path]
[email protected]53456aa2013-07-03 19:38:34772 if self.cache_dir:
773 clone_cmd.append('--shared')
[email protected]f5d37bf2010-09-02 00:50:34774 if options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57775 clone_cmd.append('--verbose')
[email protected]3534aa52013-07-20 01:58:08776 clone_cmd.append(url)
[email protected]328c3c72011-06-01 20:50:27777 # If the parent directory does not exist, Git clone on Windows will not
778 # create it, so we need to do it manually.
779 parent_dir = os.path.dirname(self.checkout_path)
[email protected]3534aa52013-07-20 01:58:08780 gclient_utils.safe_makedirs(parent_dir)
781 tmp_dir = tempfile.mkdtemp(
782 prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
783 dir=parent_dir)
784 try:
785 clone_cmd.append(tmp_dir)
[email protected]fd5b6382013-10-25 20:54:34786 self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
[email protected]3534aa52013-07-20 01:58:08787 gclient_utils.safe_makedirs(self.checkout_path)
[email protected]ef509e42013-09-20 13:19:08788 gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
789 os.path.join(self.checkout_path, '.git'))
[email protected]6279e8a2014-02-13 01:45:25790 except:
[email protected]fe0d1902014-04-08 20:50:44791 traceback.print_exc(file=self.out_fh)
[email protected]6279e8a2014-02-13 01:45:25792 raise
[email protected]3534aa52013-07-20 01:58:08793 finally:
794 if os.listdir(tmp_dir):
[email protected]fe0d1902014-04-08 20:50:44795 self.Print('_____ removing non-empty tmp dir %s' % tmp_dir)
[email protected]3534aa52013-07-20 01:58:08796 gclient_utils.rmtree(tmp_dir)
797 if revision.startswith('refs/heads/'):
798 self._Run(
799 ['checkout', '--quiet', revision.replace('refs/heads/', '')], options)
800 else:
[email protected]786fb682010-06-02 15:16:23801 # Squelch git's very verbose detached HEAD warning and use our own
[email protected]3534aa52013-07-20 01:58:08802 self._Run(['checkout', '--quiet', revision], options)
[email protected]fe0d1902014-04-08 20:50:44803 self.Print(
[email protected]f5d37bf2010-09-02 00:50:34804 ('Checked out %s to a detached HEAD. Before making any commits\n'
805 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
[email protected]1a60dca2013-11-26 14:06:26806 'an existing branch or use \'git checkout %s -b <branch>\' to\n'
807 'create a new branch for your work.') % (revision, self.remote))
[email protected]d90ba3f2010-02-23 14:42:57808
[email protected]6cd41b62014-04-21 23:55:22809 def _AskForData(self, prompt, options):
[email protected]30c46d62014-01-23 12:11:56810 if options.jobs > 1:
[email protected]6cd41b62014-04-21 23:55:22811 self.Print(prompt)
[email protected]30c46d62014-01-23 12:11:56812 raise gclient_utils.Error("Background task requires input. Rerun "
813 "gclient with --jobs=1 so that\n"
814 "interaction is possible.")
815 try:
816 return raw_input(prompt)
817 except KeyboardInterrupt:
818 # Hide the exception.
819 sys.exit(1)
820
821
[email protected]f5d37bf2010-09-02 00:50:34822 def _AttemptRebase(self, upstream, files, options, newbase=None,
[email protected]30c46d62014-01-23 12:11:56823 branch=None, printed_path=False, merge=False):
[email protected]d90ba3f2010-02-23 14:42:57824 """Attempt to rebase onto either upstream or, if specified, newbase."""
[email protected]396e1a62013-07-03 19:41:04825 if files is not None:
826 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
[email protected]d90ba3f2010-02-23 14:42:57827 revision = upstream
828 if newbase:
829 revision = newbase
[email protected]30c46d62014-01-23 12:11:56830 action = 'merge' if merge else 'rebase'
[email protected]d90ba3f2010-02-23 14:42:57831 if not printed_path:
[email protected]fe0d1902014-04-08 20:50:44832 self.Print('_____ %s : Attempting %s onto %s...' % (
[email protected]30c46d62014-01-23 12:11:56833 self.relpath, action, revision))
[email protected]d90ba3f2010-02-23 14:42:57834 printed_path = True
835 else:
[email protected]fe0d1902014-04-08 20:50:44836 self.Print('Attempting %s onto %s...' % (action, revision))
[email protected]30c46d62014-01-23 12:11:56837
838 if merge:
839 merge_output = self._Capture(['merge', revision])
840 if options.verbose:
[email protected]fe0d1902014-04-08 20:50:44841 self.Print(merge_output)
[email protected]30c46d62014-01-23 12:11:56842 return
[email protected]d90ba3f2010-02-23 14:42:57843
844 # Build the rebase command here using the args
845 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
846 rebase_cmd = ['rebase']
[email protected]f5d37bf2010-09-02 00:50:34847 if options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57848 rebase_cmd.append('--verbose')
849 if newbase:
850 rebase_cmd.extend(['--onto', newbase])
851 rebase_cmd.append(upstream)
852 if branch:
853 rebase_cmd.append(branch)
854
855 try:
[email protected]ad80e3b2010-09-09 14:18:28856 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22857 except subprocess2.CalledProcessError, e:
[email protected]ad80e3b2010-09-09 14:18:28858 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
859 re.match(r'cannot rebase: your index contains uncommitted changes',
860 e.stderr)):
[email protected]d90ba3f2010-02-23 14:42:57861 while True:
[email protected]30c46d62014-01-23 12:11:56862 rebase_action = self._AskForData(
[email protected]90541732011-04-01 17:54:18863 'Cannot rebase because of unstaged changes.\n'
864 '\'git reset --hard HEAD\' ?\n'
865 'WARNING: destroys any uncommitted work in your current branch!'
[email protected]18fa4542013-05-21 13:30:46866 ' (y)es / (q)uit / (s)how : ', options)
[email protected]d90ba3f2010-02-23 14:42:57867 if re.match(r'yes|y', rebase_action, re.I):
[email protected]37e89872010-09-07 16:11:33868 self._Run(['reset', '--hard', 'HEAD'], options)
[email protected]d90ba3f2010-02-23 14:42:57869 # Should this be recursive?
[email protected]ad80e3b2010-09-09 14:18:28870 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
[email protected]d90ba3f2010-02-23 14:42:57871 break
872 elif re.match(r'quit|q', rebase_action, re.I):
873 raise gclient_utils.Error("Please merge or rebase manually\n"
874 "cd %s && git " % self.checkout_path
875 + "%s" % ' '.join(rebase_cmd))
876 elif re.match(r'show|s', rebase_action, re.I):
[email protected]fe0d1902014-04-08 20:50:44877 self.Print('%s' % e.stderr.strip())
[email protected]d90ba3f2010-02-23 14:42:57878 continue
879 else:
880 gclient_utils.Error("Input not recognized")
881 continue
882 elif re.search(r'^CONFLICT', e.stdout, re.M):
883 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
884 "Fix the conflict and run gclient again.\n"
885 "See 'man git-rebase' for details.\n")
886 else:
[email protected]fe0d1902014-04-08 20:50:44887 self.Print(e.stdout.strip())
888 self.Print('Rebase produced error output:\n%s' % e.stderr.strip())
[email protected]d90ba3f2010-02-23 14:42:57889 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
890 "manually.\ncd %s && git " %
891 self.checkout_path
892 + "%s" % ' '.join(rebase_cmd))
893
[email protected]fe0d1902014-04-08 20:50:44894 self.Print(rebase_output.strip())
[email protected]f5d37bf2010-09-02 00:50:34895 if not options.verbose:
[email protected]d90ba3f2010-02-23 14:42:57896 # Make the output a little prettier. It's nice to have some
897 # whitespace between projects when syncing.
[email protected]fe0d1902014-04-08 20:50:44898 self.Print('')
[email protected]d90ba3f2010-02-23 14:42:57899
[email protected]6e29d572010-06-04 17:32:20900 @staticmethod
901 def _CheckMinVersion(min_version):
[email protected]d0f854a2010-03-11 19:35:53902 (ok, current_version) = scm.GIT.AssertVersion(min_version)
903 if not ok:
904 raise gclient_utils.Error('git version %s < minimum required %s' %
905 (current_version, min_version))
[email protected]923a0372009-12-11 20:42:43906
[email protected]786fb682010-06-02 15:16:23907 def _IsRebasing(self):
908 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
909 # have a plumbing command to determine whether a rebase is in progress, so
910 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
911 g = os.path.join(self.checkout_path, '.git')
912 return (
913 os.path.isdir(os.path.join(g, "rebase-merge")) or
914 os.path.isdir(os.path.join(g, "rebase-apply")))
915
916 def _CheckClean(self, rev_str):
917 # Make sure the tree is clean; see git-rebase.sh for reference
918 try:
919 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
[email protected]ad80e3b2010-09-09 14:18:28920 cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22921 except subprocess2.CalledProcessError:
[email protected]6e29d572010-06-04 17:32:20922 raise gclient_utils.Error('\n____ %s%s\n'
923 '\tYou have unstaged changes.\n'
924 '\tPlease commit, stash, or reset.\n'
925 % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23926 try:
927 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
[email protected]ad80e3b2010-09-09 14:18:28928 '--ignore-submodules', 'HEAD', '--'],
929 cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22930 except subprocess2.CalledProcessError:
[email protected]6e29d572010-06-04 17:32:20931 raise gclient_utils.Error('\n____ %s%s\n'
932 '\tYour index contains uncommitted changes\n'
933 '\tPlease commit, stash, or reset.\n'
934 % (self.relpath, rev_str))
[email protected]786fb682010-06-02 15:16:23935
[email protected]396e1a62013-07-03 19:41:04936 def _CheckDetachedHead(self, rev_str, _options):
[email protected]786fb682010-06-02 15:16:23937 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
938 # reference by a commit). If not, error out -- most likely a rebase is
939 # in progress, try to detect so we can give a better error.
940 try:
[email protected]ad80e3b2010-09-09 14:18:28941 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
942 cwd=self.checkout_path)
[email protected]bffad372011-09-08 17:54:22943 except subprocess2.CalledProcessError:
[email protected]786fb682010-06-02 15:16:23944 # Commit is not contained by any rev. See if the user is rebasing:
945 if self._IsRebasing():
946 # Punt to the user
947 raise gclient_utils.Error('\n____ %s%s\n'
948 '\tAlready in a conflict, i.e. (no branch).\n'
949 '\tFix the conflict and run gclient again.\n'
950 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
951 '\tSee man git-rebase for details.\n'
952 % (self.relpath, rev_str))
953 # Let's just save off the commit so we can proceed.
[email protected]6cafa132010-09-07 14:17:26954 name = ('saved-by-gclient-' +
955 self._Capture(['rev-parse', '--short', 'HEAD']))
[email protected]77bd7362013-09-25 23:46:14956 self._Capture(['branch', '-f', name])
[email protected]fe0d1902014-04-08 20:50:44957 self.Print('_____ found an unreferenced commit and saved it as \'%s\'' %
[email protected]f5d37bf2010-09-02 00:50:34958 name)
[email protected]786fb682010-06-02 15:16:23959
[email protected]5bde4852009-12-14 16:47:12960 def _GetCurrentBranch(self):
[email protected]786fb682010-06-02 15:16:23961 # Returns name of current branch or None for detached HEAD
[email protected]6cafa132010-09-07 14:17:26962 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
[email protected]786fb682010-06-02 15:16:23963 if branch == 'HEAD':
[email protected]5bde4852009-12-14 16:47:12964 return None
965 return branch
966
[email protected]c3e09d22014-04-10 13:58:18967 def _Capture(self, args, **kwargs):
[email protected]fe0d1902014-04-08 20:50:44968 kwargs.setdefault('cwd', self.checkout_path)
969 kwargs.setdefault('stderr', subprocess2.PIPE)
[email protected]6d8115d2014-04-23 20:59:23970 env = scm.GIT.ApplyEnvVars(kwargs)
971 return subprocess2.check_output(['git'] + args, env=env, **kwargs).strip()
[email protected]6cafa132010-09-07 14:17:26972
[email protected]e409df62013-04-16 17:28:57973 def _UpdateBranchHeads(self, options, fetch=False):
974 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
975 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
[email protected]1a60dca2013-11-26 14:06:26976 config_cmd = ['config', 'remote.%s.fetch' % self.remote,
[email protected]f2d7d6b2013-10-17 20:41:43977 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
978 '^\\+refs/branch-heads/\\*:.*$']
979 self._Run(config_cmd, options)
980 if fetch:
[email protected]ff113292014-03-25 06:02:08981 cfg = gclient_utils.DefaultIndexPackConfig(self.url)
[email protected]fc616382014-03-18 20:32:04982 fetch_cmd = cfg + ['fetch', self.remote]
[email protected]f2d7d6b2013-10-17 20:41:43983 if options.verbose:
984 fetch_cmd.append('--verbose')
985 self._Run(fetch_cmd, options, retry=True)
[email protected]e409df62013-04-16 17:28:57986
[email protected]fd5b6382013-10-25 20:54:34987 def _Run(self, args, options, **kwargs):
[email protected]fe0d1902014-04-08 20:50:44988 cwd = kwargs.setdefault('cwd', self.checkout_path)
989 kwargs.setdefault('stdout', self.out_fh)
[email protected]848fd492014-04-09 19:06:44990 kwargs['filter_fn'] = self.filter
[email protected]fe0d1902014-04-08 20:50:44991 kwargs.setdefault('print_stdout', False)
[email protected]6d8115d2014-04-23 20:59:23992 env = scm.GIT.ApplyEnvVars(kwargs)
[email protected]772efaf2014-04-01 02:35:44993 cmd = ['git'] + args
[email protected]fe0d1902014-04-08 20:50:44994 header = "running '%s' in '%s'" % (' '.join(cmd), cwd)
[email protected]848fd492014-04-09 19:06:44995 self.filter(header)
[email protected]6d8115d2014-04-23 20:59:23996 return gclient_utils.CheckCallAndFilter(cmd, env=env, **kwargs)
[email protected]e28e4982009-09-25 20:51:45997
998
[email protected]55e724e2010-03-11 19:36:49999class SVNWrapper(SCMWrapper):
[email protected]cb5442b2009-09-22 16:51:241000 """ Wrapper for SVN """
[email protected]2702bcd2013-09-24 19:10:071001 name = 'svn'
[email protected]5f3eee32009-09-17 00:34:301002
[email protected]9e3e82c2012-04-18 12:55:431003 @staticmethod
1004 def BinaryExists():
1005 """Returns true if the command exists."""
1006 try:
1007 result, version = scm.SVN.AssertVersion('1.4')
1008 if not result:
1009 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1010 return result
1011 except OSError:
1012 return False
1013
[email protected]885a9602013-05-31 09:54:401014 def GetCheckoutRoot(self):
1015 return scm.SVN.GetCheckoutRoot(self.checkout_path)
1016
[email protected]eaab7842011-04-28 09:07:581017 def GetRevisionDate(self, revision):
1018 """Returns the given revision's date in ISO-8601 format (which contains the
1019 time zone)."""
[email protected]d579fcf2011-12-13 20:36:031020 date = scm.SVN.Capture(
1021 ['propget', '--revprop', 'svn:date', '-r', revision],
1022 os.path.join(self.checkout_path, '.'))
[email protected]eaab7842011-04-28 09:07:581023 return date.strip()
1024
[email protected]396e1a62013-07-03 19:41:041025 def cleanup(self, options, args, _file_list):
[email protected]5f3eee32009-09-17 00:34:301026 """Cleanup working copy."""
[email protected]669600d2010-09-01 19:06:311027 self._Run(['cleanup'] + args, options)
[email protected]5f3eee32009-09-17 00:34:301028
[email protected]396e1a62013-07-03 19:41:041029 def diff(self, options, args, _file_list):
[email protected]5f3eee32009-09-17 00:34:301030 # NOTE: This function does not currently modify file_list.
[email protected]8469bf92010-09-03 19:03:151031 if not os.path.isdir(self.checkout_path):
1032 raise gclient_utils.Error('Directory %s is not present.' %
1033 self.checkout_path)
[email protected]669600d2010-09-01 19:06:311034 self._Run(['diff'] + args, options)
[email protected]5f3eee32009-09-17 00:34:301035
[email protected]396e1a62013-07-03 19:41:041036 def pack(self, _options, args, _file_list):
[email protected]ee4071d2009-12-22 22:25:371037 """Generates a patch file which can be applied to the root of the
1038 repository."""
[email protected]8469bf92010-09-03 19:03:151039 if not os.path.isdir(self.checkout_path):
1040 raise gclient_utils.Error('Directory %s is not present.' %
1041 self.checkout_path)
1042 gclient_utils.CheckCallAndFilter(
1043 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1044 cwd=self.checkout_path,
1045 print_stdout=False,
[email protected]fe0d1902014-04-08 20:50:441046 filter_fn=SvnDiffFilterer(self.relpath).Filter, print_func=self.Print)
[email protected]ee4071d2009-12-22 22:25:371047
[email protected]5f3eee32009-09-17 00:34:301048 def update(self, options, args, file_list):
[email protected]d6504212010-01-13 17:34:311049 """Runs svn to update or transparently checkout the working copy.
[email protected]5f3eee32009-09-17 00:34:301050
1051 All updated files will be appended to file_list.
1052
1053 Raises:
1054 Error: if can't get URL for relative path.
1055 """
[email protected]b09097a2014-04-09 19:09:081056 # Only update if hg is not controlling the directory.
[email protected]6c2b49d2014-02-26 23:57:381057 hg_path = os.path.join(self.checkout_path, '.hg')
1058 if os.path.exists(hg_path):
[email protected]fe0d1902014-04-08 20:50:441059 self.Print('________ found .hg directory; skipping %s' % self.relpath)
[email protected]6c2b49d2014-02-26 23:57:381060 return
1061
[email protected]5f3eee32009-09-17 00:34:301062 if args:
1063 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1064
[email protected]8e0e9262010-08-17 19:20:271065 # revision is the revision to match. It is None if no revision is specified,
1066 # i.e. the 'deps ain't pinned'.
[email protected]ac915bb2009-11-13 17:03:011067 url, revision = gclient_utils.SplitUrlRevision(self.url)
[email protected]50fd47f2014-02-13 01:03:191068 # Keep the original unpinned url for reference in case the repo is switched.
1069 base_url = url
[email protected]eb2756d2011-09-20 20:17:511070 managed = True
[email protected]5f3eee32009-09-17 00:34:301071 if options.revision:
1072 # Override the revision number.
[email protected]ac915bb2009-11-13 17:03:011073 revision = str(options.revision)
[email protected]5f3eee32009-09-17 00:34:301074 if revision:
[email protected]eb2756d2011-09-20 20:17:511075 if revision != 'unmanaged':
1076 forced_revision = True
1077 # Reconstruct the url.
1078 url = '%s@%s' % (url, revision)
1079 rev_str = ' at %s' % revision
1080 else:
1081 managed = False
1082 revision = None
[email protected]8e0e9262010-08-17 19:20:271083 else:
1084 forced_revision = False
1085 rev_str = ''
[email protected]5f3eee32009-09-17 00:34:301086
[email protected]d0b0a5b2014-03-10 19:30:211087 exists = os.path.exists(self.checkout_path)
[email protected]7ff04292014-03-10 12:57:251088 if exists and managed:
[email protected]b09097a2014-04-09 19:09:081089 # Git is only okay if it's a git-svn checkout of the right repo.
1090 if scm.GIT.IsGitSvn(self.checkout_path):
1091 remote_url = scm.GIT.Capture(['config', '--local', '--get',
1092 'svn-remote.svn.url'],
1093 cwd=self.checkout_path).rstrip()
1094 if remote_url.rstrip('/') == base_url.rstrip('/'):
1095 print('\n_____ %s looks like a git-svn checkout. Skipping.'
1096 % self.relpath)
1097 return # TODO(borenet): Get the svn revision number?
1098
1099 # Get the existing scm url and the revision number of the current checkout.
1100 if exists and managed:
[email protected]13349e22012-11-15 17:11:281101 try:
1102 from_info = scm.SVN.CaptureLocalInfo(
1103 [], os.path.join(self.checkout_path, '.'))
1104 except (gclient_utils.Error, subprocess2.CalledProcessError):
[email protected]b09097a2014-04-09 19:09:081105 self._DeleteOrMove(options.force)
1106 exists = False
[email protected]13349e22012-11-15 17:11:281107
[email protected]2f2ca142014-01-07 03:59:181108 BASE_URLS = {
1109 '/chrome/trunk/src': 'gs://chromium-svn-checkout/chrome/',
1110 '/blink/trunk': 'gs://chromium-svn-checkout/blink/',
1111 }
[email protected]ca35be32014-01-17 01:48:181112 WHITELISTED_ROOTS = [
1113 'svn://svn.chromium.org',
1114 'svn://svn-mirror.golo.chromium.org',
1115 ]
[email protected]13349e22012-11-15 17:11:281116 if not exists:
[email protected]2f2ca142014-01-07 03:59:181117 try:
1118 # Split out the revision number since it's not useful for us.
1119 base_path = urlparse.urlparse(url).path.split('@')[0]
[email protected]ca35be32014-01-17 01:48:181120 # Check to see if we're on a whitelisted root. We do this because
1121 # only some svn servers have matching UUIDs.
1122 local_parsed = urlparse.urlparse(url)
1123 local_root = '%s://%s' % (local_parsed.scheme, local_parsed.netloc)
[email protected]2f2ca142014-01-07 03:59:181124 if ('CHROME_HEADLESS' in os.environ
1125 and sys.platform == 'linux2' # TODO(hinoka): Enable for win/mac.
[email protected]ca35be32014-01-17 01:48:181126 and base_path in BASE_URLS
1127 and local_root in WHITELISTED_ROOTS):
1128
[email protected]2f2ca142014-01-07 03:59:181129 # Use a tarball for initial sync if we are on a bot.
1130 # Get an unauthenticated gsutil instance.
1131 gsutil = download_from_google_storage.Gsutil(
1132 GSUTIL_DEFAULT_PATH, boto_path=os.devnull)
1133
1134 gs_path = BASE_URLS[base_path]
1135 _, out, _ = gsutil.check_call('ls', gs_path)
1136 # So that we can get the most recent revision.
1137 sorted_items = sorted(out.splitlines())
1138 latest_checkout = sorted_items[-1]
1139
1140 tempdir = tempfile.mkdtemp()
[email protected]fe0d1902014-04-08 20:50:441141 self.Print('Downloading %s...' % latest_checkout)
[email protected]2f2ca142014-01-07 03:59:181142 code, out, err = gsutil.check_call('cp', latest_checkout, tempdir)
1143 if code:
[email protected]fe0d1902014-04-08 20:50:441144 self.Print('%s\n%s' % (out, err))
[email protected]2f2ca142014-01-07 03:59:181145 raise Exception()
1146 filename = latest_checkout.split('/')[-1]
1147 tarball = os.path.join(tempdir, filename)
[email protected]fe0d1902014-04-08 20:50:441148 self.Print('Unpacking into %s...' % self.checkout_path)
[email protected]2f2ca142014-01-07 03:59:181149 gclient_utils.safe_makedirs(self.checkout_path)
1150 # TODO(hinoka): Use 7z for windows.
1151 cmd = ['tar', '--extract', '--ungzip',
1152 '--directory', self.checkout_path,
1153 '--file', tarball]
1154 gclient_utils.CheckCallAndFilter(
1155 cmd, stdout=sys.stdout, print_stdout=True)
1156
[email protected]fe0d1902014-04-08 20:50:441157 self.Print('Deleting temp file')
[email protected]2f2ca142014-01-07 03:59:181158 gclient_utils.rmtree(tempdir)
1159
1160 # Rewrite the repository root to match.
1161 tarball_url = scm.SVN.CaptureLocalInfo(
1162 ['.'], self.checkout_path)['Repository Root']
1163 tarball_parsed = urlparse.urlparse(tarball_url)
1164 tarball_root = '%s://%s' % (tarball_parsed.scheme,
1165 tarball_parsed.netloc)
[email protected]2f2ca142014-01-07 03:59:181166
1167 if tarball_root != local_root:
[email protected]fe0d1902014-04-08 20:50:441168 self.Print('Switching repository root to %s' % local_root)
[email protected]2f2ca142014-01-07 03:59:181169 self._Run(['switch', '--relocate', tarball_root,
1170 local_root, self.checkout_path],
1171 options)
1172 except Exception as e:
[email protected]fe0d1902014-04-08 20:50:441173 self.Print('We tried to get a source tarball but failed.')
1174 self.Print('Resuming normal operations.')
1175 self.Print(str(e))
[email protected]2f2ca142014-01-07 03:59:181176
[email protected]6c48a302011-10-20 23:44:201177 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
[email protected]5f3eee32009-09-17 00:34:301178 # We need to checkout.
[email protected]8469bf92010-09-03 19:03:151179 command = ['checkout', url, self.checkout_path]
[email protected]8e0e9262010-08-17 19:20:271180 command = self._AddAdditionalUpdateFlags(command, options, revision)
[email protected]669600d2010-09-01 19:06:311181 self._RunAndGetFileList(command, options, file_list, self._root_dir)
[email protected]2702bcd2013-09-24 19:10:071182 return self.Svnversion()
[email protected]5f3eee32009-09-17 00:34:301183
[email protected]6c2b49d2014-02-26 23:57:381184 if not managed:
[email protected]fe0d1902014-04-08 20:50:441185 self.Print(('________ unmanaged solution; skipping %s' % self.relpath))
[email protected]b09097a2014-04-09 19:09:081186 if os.path.exists(os.path.join(self.checkout_path, '.svn')):
1187 return self.Svnversion()
1188 return
[email protected]6c2b49d2014-02-26 23:57:381189
[email protected]49fcb0c2011-09-23 14:34:381190 if 'URL' not in from_info:
1191 raise gclient_utils.Error(
1192 ('gclient is confused. Couldn\'t get the url for %s.\n'
1193 'Try using @unmanaged.\n%s') % (
1194 self.checkout_path, from_info))
1195
[email protected]3031d732014-04-21 22:18:021196 # Look for locked directories.
1197 dir_info = scm.SVN.CaptureStatus(
1198 None, os.path.join(self.checkout_path, '.'))
1199 if any(d[0][2] == 'L' for d in dir_info):
1200 try:
1201 self._Run(['cleanup', self.checkout_path], options)
1202 except subprocess2.CalledProcessError, e:
1203 # Get the status again, svn cleanup may have cleaned up at least
1204 # something.
1205 dir_info = scm.SVN.CaptureStatus(
1206 None, os.path.join(self.checkout_path, '.'))
1207
[email protected]d558c4b2011-09-22 18:56:241208 # Try to fix the failures by removing troublesome files.
1209 for d in dir_info:
1210 if d[0][2] == 'L':
1211 if d[0][0] == '!' and options.force:
[email protected]1580d952013-08-19 07:31:401212 # We don't pass any files/directories to CaptureStatus and set
1213 # cwd=self.checkout_path, so we should get relative paths here.
1214 assert not os.path.isabs(d[1])
1215 path_to_remove = os.path.normpath(
1216 os.path.join(self.checkout_path, d[1]))
[email protected]fe0d1902014-04-08 20:50:441217 self.Print('Removing troublesome path %s' % path_to_remove)
[email protected]1580d952013-08-19 07:31:401218 gclient_utils.rmtree(path_to_remove)
[email protected]d558c4b2011-09-22 18:56:241219 else:
[email protected]fe0d1902014-04-08 20:50:441220 self.Print(
1221 'Not removing troublesome path %s automatically.' % d[1])
[email protected]d558c4b2011-09-22 18:56:241222 if d[0][0] == '!':
[email protected]fe0d1902014-04-08 20:50:441223 self.Print('You can pass --force to enable automatic removal.')
[email protected]d558c4b2011-09-22 18:56:241224 raise e
[email protected]e407c9a2010-08-09 19:11:371225
[email protected]8e0e9262010-08-17 19:20:271226 # Retrieve the current HEAD version because svn is slow at null updates.
1227 if options.manually_grab_svn_rev and not revision:
[email protected]d579fcf2011-12-13 20:36:031228 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
[email protected]8e0e9262010-08-17 19:20:271229 revision = str(from_info_live['Revision'])
1230 rev_str = ' at %s' % revision
[email protected]5f3eee32009-09-17 00:34:301231
[email protected]b09097a2014-04-09 19:09:081232 if from_info['URL'].rstrip('/') != base_url.rstrip('/'):
[email protected]6c2b49d2014-02-26 23:57:381233 # The repository url changed, need to switch.
1234 try:
1235 to_info = scm.SVN.CaptureRemoteInfo(url)
1236 except (gclient_utils.Error, subprocess2.CalledProcessError):
1237 # The url is invalid or the server is not accessible, it's safer to bail
1238 # out right now.
1239 raise gclient_utils.Error('This url is unreachable: %s' % url)
1240 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1241 and (from_info['UUID'] == to_info['UUID']))
1242 if can_switch:
[email protected]fe0d1902014-04-08 20:50:441243 self.Print('_____ relocating %s to a new checkout' % self.relpath)
[email protected]6c2b49d2014-02-26 23:57:381244 # We have different roots, so check if we can switch --relocate.
1245 # Subversion only permits this if the repository UUIDs match.
1246 # Perform the switch --relocate, then rewrite the from_url
1247 # to reflect where we "are now." (This is the same way that
1248 # Subversion itself handles the metadata when switch --relocate
1249 # is used.) This makes the checks below for whether we
1250 # can update to a revision or have to switch to a different
1251 # branch work as expected.
1252 # TODO(maruel): TEST ME !
1253 command = ['switch', '--relocate',
1254 from_info['Repository Root'],
1255 to_info['Repository Root'],
1256 self.relpath]
1257 self._Run(command, options, cwd=self._root_dir)
1258 from_info['URL'] = from_info['URL'].replace(
1259 from_info['Repository Root'],
1260 to_info['Repository Root'])
1261 else:
1262 if not options.force and not options.reset:
1263 # Look for local modifications but ignore unversioned files.
1264 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1265 if status[0][0] != '?':
1266 raise gclient_utils.Error(
1267 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1268 'there is local changes in %s. Delete the directory and '
1269 'try again.') % (url, self.checkout_path))
1270 # Ok delete it.
[email protected]fe0d1902014-04-08 20:50:441271 self.Print('_____ switching %s to a new checkout' % self.relpath)
[email protected]6c2b49d2014-02-26 23:57:381272 gclient_utils.rmtree(self.checkout_path)
1273 # We need to checkout.
1274 command = ['checkout', url, self.checkout_path]
1275 command = self._AddAdditionalUpdateFlags(command, options, revision)
1276 self._RunAndGetFileList(command, options, file_list, self._root_dir)
1277 return self.Svnversion()
1278
[email protected]5f3eee32009-09-17 00:34:301279 # If the provided url has a revision number that matches the revision
1280 # number of the existing directory, then we don't need to bother updating.
[email protected]2e0c6852009-09-24 00:02:071281 if not options.force and str(from_info['Revision']) == revision:
[email protected]5f3eee32009-09-17 00:34:301282 if options.verbose or not forced_revision:
[email protected]fe0d1902014-04-08 20:50:441283 self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
[email protected]98e69452012-02-16 16:36:431284 else:
1285 command = ['update', self.checkout_path]
1286 command = self._AddAdditionalUpdateFlags(command, options, revision)
1287 self._RunAndGetFileList(command, options, file_list, self._root_dir)
[email protected]5f3eee32009-09-17 00:34:301288
[email protected]98e69452012-02-16 16:36:431289 # If --reset and --delete_unversioned_trees are specified, remove any
1290 # untracked files and directories.
1291 if options.reset and options.delete_unversioned_trees:
1292 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1293 full_path = os.path.join(self.checkout_path, status[1])
1294 if (status[0][0] == '?'
1295 and os.path.isdir(full_path)
1296 and not os.path.islink(full_path)):
[email protected]fe0d1902014-04-08 20:50:441297 self.Print('_____ removing unversioned directory %s' % status[1])
[email protected]dc112ac2013-04-24 13:00:191298 gclient_utils.rmtree(full_path)
[email protected]2702bcd2013-09-24 19:10:071299 return self.Svnversion()
[email protected]5f3eee32009-09-17 00:34:301300
[email protected]4b5b1772010-04-08 01:52:561301 def updatesingle(self, options, args, file_list):
[email protected]4b5b1772010-04-08 01:52:561302 filename = args.pop()
[email protected]57564662010-04-14 02:35:121303 if scm.SVN.AssertVersion("1.5")[0]:
[email protected]8469bf92010-09-03 19:03:151304 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
[email protected]57564662010-04-14 02:35:121305 # Create an empty checkout and then update the one file we want. Future
1306 # operations will only apply to the one file we checked out.
[email protected]8469bf92010-09-03 19:03:151307 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
[email protected]669600d2010-09-01 19:06:311308 self._Run(command, options, cwd=self._root_dir)
[email protected]8469bf92010-09-03 19:03:151309 if os.path.exists(os.path.join(self.checkout_path, filename)):
1310 os.remove(os.path.join(self.checkout_path, filename))
[email protected]57564662010-04-14 02:35:121311 command = ["update", filename]
[email protected]669600d2010-09-01 19:06:311312 self._RunAndGetFileList(command, options, file_list)
[email protected]57564662010-04-14 02:35:121313 # After the initial checkout, we can use update as if it were any other
1314 # dep.
1315 self.update(options, args, file_list)
1316 else:
1317 # If the installed version of SVN doesn't support --depth, fallback to
1318 # just exporting the file. This has the downside that revision
1319 # information is not stored next to the file, so we will have to
1320 # re-export the file every time we sync.
[email protected]8469bf92010-09-03 19:03:151321 if not os.path.exists(self.checkout_path):
[email protected]6c48a302011-10-20 23:44:201322 gclient_utils.safe_makedirs(self.checkout_path)
[email protected]57564662010-04-14 02:35:121323 command = ["export", os.path.join(self.url, filename),
[email protected]8469bf92010-09-03 19:03:151324 os.path.join(self.checkout_path, filename)]
[email protected]8e0e9262010-08-17 19:20:271325 command = self._AddAdditionalUpdateFlags(command, options,
1326 options.revision)
[email protected]669600d2010-09-01 19:06:311327 self._Run(command, options, cwd=self._root_dir)
[email protected]4b5b1772010-04-08 01:52:561328
[email protected]396e1a62013-07-03 19:41:041329 def revert(self, options, _args, file_list):
[email protected]5f3eee32009-09-17 00:34:301330 """Reverts local modifications. Subversion specific.
1331
1332 All reverted files will be appended to file_list, even if Subversion
1333 doesn't know about them.
1334 """
[email protected]8469bf92010-09-03 19:03:151335 if not os.path.isdir(self.checkout_path):
[email protected]c0cc0872011-10-12 17:02:411336 if os.path.exists(self.checkout_path):
1337 gclient_utils.rmtree(self.checkout_path)
[email protected]5f3eee32009-09-17 00:34:301338 # svn revert won't work if the directory doesn't exist. It needs to
1339 # checkout instead.
[email protected]fe0d1902014-04-08 20:50:441340 self.Print('_____ %s is missing, synching instead' % self.relpath)
[email protected]5f3eee32009-09-17 00:34:301341 # Don't reuse the args.
1342 return self.update(options, [], file_list)
1343
[email protected]c0cc0872011-10-12 17:02:411344 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
[email protected]50fd47f2014-02-13 01:03:191345 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
[email protected]fe0d1902014-04-08 20:50:441346 self.Print('________ found .git directory; skipping %s' % self.relpath)
[email protected]50fd47f2014-02-13 01:03:191347 return
[email protected]6c2b49d2014-02-26 23:57:381348 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
[email protected]fe0d1902014-04-08 20:50:441349 self.Print('________ found .hg directory; skipping %s' % self.relpath)
[email protected]6c2b49d2014-02-26 23:57:381350 return
[email protected]c0cc0872011-10-12 17:02:411351 if not options.force:
1352 raise gclient_utils.Error('Invalid checkout path, aborting')
[email protected]fe0d1902014-04-08 20:50:441353 self.Print(
[email protected]c0cc0872011-10-12 17:02:411354 '\n_____ %s is not a valid svn checkout, synching instead' %
1355 self.relpath)
1356 gclient_utils.rmtree(self.checkout_path)
1357 # Don't reuse the args.
1358 return self.update(options, [], file_list)
1359
[email protected]07ab60e2011-02-08 21:54:001360 def printcb(file_status):
[email protected]396e1a62013-07-03 19:41:041361 if file_list is not None:
1362 file_list.append(file_status[1])
[email protected]aa3dd472009-09-21 19:02:481363 if logging.getLogger().isEnabledFor(logging.INFO):
[email protected]07ab60e2011-02-08 21:54:001364 logging.info('%s%s' % (file_status[0], file_status[1]))
[email protected]aa3dd472009-09-21 19:02:481365 else:
[email protected]fe0d1902014-04-08 20:50:441366 self.Print(os.path.join(self.checkout_path, file_status[1]))
[email protected]07ab60e2011-02-08 21:54:001367 scm.SVN.Revert(self.checkout_path, callback=printcb)
[email protected]aa3dd472009-09-21 19:02:481368
[email protected]8b322b32011-11-01 19:05:501369 # Revert() may delete the directory altogether.
1370 if not os.path.isdir(self.checkout_path):
1371 # Don't reuse the args.
1372 return self.update(options, [], file_list)
1373
[email protected]810a50b2009-10-05 23:03:181374 try:
1375 # svn revert is so broken we don't even use it. Using
1376 # "svn up --revision BASE" achieve the same effect.
[email protected]07ab60e2011-02-08 21:54:001377 # file_list will contain duplicates.
[email protected]669600d2010-09-01 19:06:311378 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1379 file_list)
[email protected]810a50b2009-10-05 23:03:181380 except OSError, e:
[email protected]07ab60e2011-02-08 21:54:001381 # Maybe the directory disapeared meanwhile. Do not throw an exception.
[email protected]810a50b2009-10-05 23:03:181382 logging.error('Failed to update:\n%s' % str(e))
[email protected]5f3eee32009-09-17 00:34:301383
[email protected]396e1a62013-07-03 19:41:041384 def revinfo(self, _options, _args, _file_list):
[email protected]0f282062009-11-06 20:14:021385 """Display revision"""
[email protected]54019f32010-09-09 13:50:111386 try:
1387 return scm.SVN.CaptureRevision(self.checkout_path)
[email protected]31cb48a2011-04-04 18:01:361388 except (gclient_utils.Error, subprocess2.CalledProcessError):
[email protected]54019f32010-09-09 13:50:111389 return None
[email protected]0f282062009-11-06 20:14:021390
[email protected]cb5442b2009-09-22 16:51:241391 def runhooks(self, options, args, file_list):
1392 self.status(options, args, file_list)
1393
[email protected]5f3eee32009-09-17 00:34:301394 def status(self, options, args, file_list):
1395 """Display status information."""
[email protected]669600d2010-09-01 19:06:311396 command = ['status'] + args
[email protected]8469bf92010-09-03 19:03:151397 if not os.path.isdir(self.checkout_path):
[email protected]5f3eee32009-09-17 00:34:301398 # svn status won't work if the directory doesn't exist.
[email protected]fe0d1902014-04-08 20:50:441399 self.Print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
[email protected]77e4eca2010-09-21 13:23:071400 'The directory does not exist.') %
1401 (' '.join(command), self.checkout_path))
[email protected]5f3eee32009-09-17 00:34:301402 # There's no file list to retrieve.
1403 else:
[email protected]669600d2010-09-01 19:06:311404 self._RunAndGetFileList(command, options, file_list)
[email protected]e6f78352010-01-13 17:05:331405
[email protected]396e1a62013-07-03 19:41:041406 def GetUsableRev(self, rev, _options):
[email protected]e5d1e612011-12-19 19:49:191407 """Verifies the validity of the revision for this repository."""
1408 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1409 raise gclient_utils.Error(
1410 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1411 'correct.') % rev)
1412 return rev
1413
[email protected]e6f78352010-01-13 17:05:331414 def FullUrlForRelativeUrl(self, url):
1415 # Find the forth '/' and strip from there. A bit hackish.
1416 return '/'.join(self.url.split('/')[:4]) + url
[email protected]99828122010-06-04 01:41:021417
[email protected]669600d2010-09-01 19:06:311418 def _Run(self, args, options, **kwargs):
1419 """Runs a commands that goes to stdout."""
[email protected]8469bf92010-09-03 19:03:151420 kwargs.setdefault('cwd', self.checkout_path)
[email protected]669600d2010-09-01 19:06:311421 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
[email protected]77e4eca2010-09-21 13:23:071422 always=options.verbose, **kwargs)
[email protected]669600d2010-09-01 19:06:311423
[email protected]2702bcd2013-09-24 19:10:071424 def Svnversion(self):
1425 """Runs the lowest checked out revision in the current project."""
1426 info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1427 return info['Revision']
1428
[email protected]669600d2010-09-01 19:06:311429 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1430 """Runs a commands that goes to stdout and grabs the file listed."""
[email protected]8469bf92010-09-03 19:03:151431 cwd = cwd or self.checkout_path
[email protected]ce117f62011-01-17 20:04:251432 scm.SVN.RunAndGetFileList(
1433 options.verbose,
1434 args + ['--ignore-externals'],
1435 cwd=cwd,
[email protected]77e4eca2010-09-21 13:23:071436 file_list=file_list)
[email protected]669600d2010-09-01 19:06:311437
[email protected]6e29d572010-06-04 17:32:201438 @staticmethod
[email protected]8e0e9262010-08-17 19:20:271439 def _AddAdditionalUpdateFlags(command, options, revision):
[email protected]99828122010-06-04 01:41:021440 """Add additional flags to command depending on what options are set.
1441 command should be a list of strings that represents an svn command.
1442
1443 This method returns a new list to be used as a command."""
1444 new_command = command[:]
1445 if revision:
1446 new_command.extend(['--revision', str(revision).strip()])
[email protected]36ac2392011-10-12 16:36:111447 # We don't want interaction when jobs are used.
1448 if options.jobs > 1:
1449 new_command.append('--non-interactive')
[email protected]99828122010-06-04 01:41:021450 # --force was added to 'svn update' in svn 1.5.
[email protected]36ac2392011-10-12 16:36:111451 # --accept was added to 'svn update' in svn 1.6.
1452 if not scm.SVN.AssertVersion('1.5')[0]:
1453 return new_command
1454
1455 # It's annoying to have it block in the middle of a sync, just sensible
1456 # defaults.
1457 if options.force:
[email protected]99828122010-06-04 01:41:021458 new_command.append('--force')
[email protected]36ac2392011-10-12 16:36:111459 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1460 new_command.extend(('--accept', 'theirs-conflict'))
1461 elif options.manually_grab_svn_rev:
1462 new_command.append('--force')
1463 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1464 new_command.extend(('--accept', 'postpone'))
1465 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1466 new_command.extend(('--accept', 'postpone'))
[email protected]99828122010-06-04 01:41:021467 return new_command