blob: 18bc0e389653cfab2ec2fc1443a963c1887c5cb0 [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
maruel@chromium.org754960e2009-09-21 12:31:05 +00007import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00008import os
maruel@chromium.orgee4071d2009-12-22 22:25:37 +00009import posixpath
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000010import re
maruel@chromium.org90541732011-04-01 17:54:18 +000011import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000012import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013
14import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000015import scm
16import subprocess2
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000017
18
szager@chromium.org71cbb502013-04-19 23:30:15 +000019THIS_FILE_PATH = os.path.abspath(__file__)
20
21
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000022class DiffFiltererWrapper(object):
23 """Simple base class which tracks which file is being diffed and
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000024 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000025 working copy lines of the svn/git diff output."""
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000026 index_string = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000027 original_prefix = "--- "
28 working_prefix = "+++ "
29
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000030 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000031 # Note that we always use '/' as the path separator to be
32 # consistent with svn's cygwin-style output on Windows
33 self._relpath = relpath.replace("\\", "/")
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000034 self._current_file = None
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000035
maruel@chromium.org6e29d572010-06-04 17:32:20 +000036 def SetCurrentFile(self, current_file):
37 self._current_file = current_file
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000038
iannucci@chromium.org3830a672013-02-19 20:15:14 +000039 @property
40 def _replacement_file(self):
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000041 return posixpath.join(self._relpath, self._current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000042
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000043 def _Replace(self, line):
44 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000045
46 def Filter(self, line):
47 if (line.startswith(self.index_string)):
48 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000049 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000050 else:
51 if (line.startswith(self.original_prefix) or
52 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000053 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000054 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000055
56
haitao.feng@intel.com306080c2012-05-04 13:11:29 +000057class SvnDiffFilterer(DiffFiltererWrapper):
58 index_string = "Index: "
59
60
61class GitDiffFilterer(DiffFiltererWrapper):
62 index_string = "diff --git "
63
64 def SetCurrentFile(self, current_file):
65 # Get filename by parsing "a/<filename> b/<filename>"
66 self._current_file = current_file[:(len(current_file)/2)][2:]
67
68 def _Replace(self, line):
69 return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
70
71
maruel@chromium.org90541732011-04-01 17:54:18 +000072def ask_for_data(prompt):
73 try:
74 return raw_input(prompt)
75 except KeyboardInterrupt:
76 # Hide the exception.
77 sys.exit(1)
78
79
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000080### SCM abstraction layer
81
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000082# Factory Method for SCM wrapper creation
83
maruel@chromium.org9eda4112010-06-11 18:56:10 +000084def GetScmName(url):
85 if url:
86 url, _ = gclient_utils.SplitUrlRevision(url)
87 if (url.startswith('git://') or url.startswith('ssh://') or
igorgatis@gmail.com4e075672011-11-21 16:35:08 +000088 url.startswith('git+http://') or url.startswith('git+https://') or
maruel@chromium.org9eda4112010-06-11 18:56:10 +000089 url.endswith('.git')):
90 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000091 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000092 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000093 return 'svn'
94 return None
95
96
97def CreateSCM(url, root_dir=None, relpath=None):
98 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000099 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +0000100 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000101 }
msb@chromium.orge28e4982009-09-25 20:51:45 +0000102
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000103 scm_name = GetScmName(url)
104 if not scm_name in SCM_MAP:
105 raise gclient_utils.Error('No SCM found for url %s' % url)
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000106 scm_class = SCM_MAP[scm_name]
107 if not scm_class.BinaryExists():
108 raise gclient_utils.Error('%s command not found' % scm_name)
109 return scm_class(url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000110
111
112# SCMWrapper base class
113
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000114class SCMWrapper(object):
115 """Add necessary glue between all the supported SCM.
116
msb@chromium.orgd6504212010-01-13 17:34:31 +0000117 This is the abstraction layer to bind to different SCM.
118 """
szager@chromium.org12b07e72013-05-03 22:06:34 +0000119 nag_timer = 30
120 nag_max = 3
121
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000122 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000123 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +0000124 self._root_dir = root_dir
125 if self._root_dir:
126 self._root_dir = self._root_dir.replace('/', os.sep)
127 self.relpath = relpath
128 if self.relpath:
129 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000130 if self.relpath and self._root_dir:
131 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000132
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000133 def RunCommand(self, command, options, args, file_list=None):
134 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000135 if file_list is None:
136 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000137
phajdan.jr@chromium.org6e043f72011-05-02 07:24:32 +0000138 commands = ['cleanup', 'update', 'updatesingle', 'revert',
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000139 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000140
141 if not command in commands:
142 raise gclient_utils.Error('Unknown command %s' % command)
143
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000144 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000145 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000146 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000147
148 return getattr(self, command)(options, args, file_list)
149
150
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000151class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000152 """Wrapper for Git"""
153
igorgatis@gmail.com4e075672011-11-21 16:35:08 +0000154 def __init__(self, url=None, root_dir=None, relpath=None):
155 """Removes 'git+' fake prefix from git URL."""
156 if url.startswith('git+http://') or url.startswith('git+https://'):
157 url = url[4:]
158 SCMWrapper.__init__(self, url, root_dir, relpath)
159
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000160 @staticmethod
161 def BinaryExists():
162 """Returns true if the command exists."""
163 try:
164 # We assume git is newer than 1.7. See: crbug.com/114483
165 result, version = scm.GIT.AssertVersion('1.7')
166 if not result:
167 raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
168 return result
169 except OSError:
170 return False
171
floitsch@google.comeaab7842011-04-28 09:07:58 +0000172 def GetRevisionDate(self, revision):
173 """Returns the given revision's date in ISO-8601 format (which contains the
174 time zone)."""
175 # TODO(floitsch): get the time-stamp of the given revision and not just the
176 # time-stamp of the currently checked out revision.
177 return self._Capture(['log', '-n', '1', '--format=%ai'])
178
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000179 @staticmethod
180 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000181 """'Cleanup' the repo.
182
183 There's no real git equivalent for the svn cleanup command, do a no-op.
184 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000185
186 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000187 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000188 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000189
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000190 def pack(self, options, args, file_list):
191 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000192 repository.
193
194 The patch file is generated from a diff of the merge base of HEAD and
195 its upstream branch.
196 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000197 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000198 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000199 ['git', 'diff', merge_base],
200 cwd=self.checkout_path,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000201 nag_timer=self.nag_timer,
202 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000203 filter_fn=GitDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000204
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000205 def UpdateSubmoduleConfig(self):
206 submod_cmd = ['git', 'config', '-f', '$toplevel/.git/config',
207 'submodule.$name.ignore', '||',
208 'git', 'config', '-f', '$toplevel/.git/config',
szager@chromium.org37e4f232012-06-21 21:47:42 +0000209 'submodule.$name.ignore', 'all']
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000210 cmd = ['git', 'submodule', '--quiet', 'foreach', ' '.join(submod_cmd)]
szager@chromium.org78f5c162012-06-22 22:34:25 +0000211 cmd2 = ['git', 'config', 'diff.ignoreSubmodules', 'all']
szager@chromium.org987b0612012-07-09 23:41:08 +0000212 cmd3 = ['git', 'config', 'branch.autosetupmerge']
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000213 cmd4 = ['git', 'config', 'fetch.recurseSubmodules', 'false']
szager@chromium.org987b0612012-07-09 23:41:08 +0000214 kwargs = {'cwd': self.checkout_path,
215 'print_stdout': False,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000216 'nag_timer': self.nag_timer,
217 'nag_max': self.nag_max,
szager@chromium.org987b0612012-07-09 23:41:08 +0000218 'filter_fn': lambda x: None}
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000219 try:
szager@chromium.org987b0612012-07-09 23:41:08 +0000220 gclient_utils.CheckCallAndFilter(cmd, **kwargs)
221 gclient_utils.CheckCallAndFilter(cmd2, **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000222 except subprocess2.CalledProcessError:
223 # Not a fatal error, or even very interesting in a non-git-submodule
224 # world. So just keep it quiet.
225 pass
szager@chromium.org987b0612012-07-09 23:41:08 +0000226 try:
227 gclient_utils.CheckCallAndFilter(cmd3, **kwargs)
228 except subprocess2.CalledProcessError:
229 gclient_utils.CheckCallAndFilter(cmd3 + ['always'], **kwargs)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000230
iannucci@chromium.org08b21bf2013-04-05 03:38:10 +0000231 gclient_utils.CheckCallAndFilter(cmd4, **kwargs)
232
msb@chromium.orge28e4982009-09-25 20:51:45 +0000233 def update(self, options, args, file_list):
234 """Runs git to update or transparently checkout the working copy.
235
236 All updated files will be appended to file_list.
237
238 Raises:
239 Error: if can't get URL for relative path.
240 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000241 if args:
242 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
243
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000244 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000245
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000246 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000247 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000248 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000249 revision = deps_revision
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000250 managed = True
msb@chromium.orge28e4982009-09-25 20:51:45 +0000251 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000252 # Override the revision number.
253 revision = str(options.revision)
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000254 if revision == 'unmanaged':
255 revision = None
256 managed = False
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000257 if not revision:
258 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000259
floitsch@google.comeaab7842011-04-28 09:07:58 +0000260 if gclient_utils.IsDateRevision(revision):
261 # Date-revisions only work on git-repositories if the reflog hasn't
262 # expired yet. Use rev-list to get the corresponding revision.
263 # git rev-list -n 1 --before='time-stamp' branchname
264 if options.transitive:
265 print('Warning: --transitive only works for SVN repositories.')
266 revision = default_rev
267
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000268 rev_str = ' at %s' % revision
269 files = []
270
271 printed_path = False
272 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000273 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000274 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000275 verbose = ['--verbose']
276 printed_path = True
277
278 if revision.startswith('refs/heads/'):
279 rev_type = "branch"
280 elif revision.startswith('origin/'):
281 # For compatability with old naming, translate 'origin' to 'refs/heads'
282 revision = revision.replace('origin/', 'refs/heads/')
283 rev_type = "branch"
284 else:
285 # hash is also a tag, only make a distinction at checkout
286 rev_type = "hash"
287
szager@google.com873e6672012-03-13 18:53:36 +0000288 if not os.path.exists(self.checkout_path) or (
289 os.path.isdir(self.checkout_path) and
290 not os.listdir(self.checkout_path)):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000291 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000292 self._Clone(revision, url, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000293 self.UpdateSubmoduleConfig()
thomasvl@chromium.org858d6452011-03-24 17:59:20 +0000294 files = self._Capture(['ls-files']).splitlines()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000295 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000296 if not verbose:
297 # Make the output a little prettier. It's nice to have some whitespace
298 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000299 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000300 return
301
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000302 if not managed:
mmoss@chromium.org96833fa2013-04-17 03:26:37 +0000303 self._UpdateBranchHeads(options, fetch=False)
szager@chromium.orgf5cc4272012-06-21 22:38:07 +0000304 self.UpdateSubmoduleConfig()
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000305 print ('________ unmanaged solution; skipping %s' % self.relpath)
306 return
307
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000308 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
309 raise gclient_utils.Error('\n____ %s%s\n'
310 '\tPath is not a git repo. No .git dir.\n'
311 '\tTo resolve:\n'
312 '\t\trm -rf %s\n'
313 '\tAnd run gclient sync again\n'
314 % (self.relpath, rev_str, self.relpath))
315
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000316 # See if the url has changed (the unittests use git://foo for the url, let
317 # that through).
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000318 current_url = self._Capture(['config', 'remote.origin.url'])
thomasvl@chromium.orgd6f89d82011-03-25 20:41:58 +0000319 # TODO(maruel): Delete url != 'git://foo' since it's just to make the
320 # unit test pass. (and update the comment above)
ilevy@chromium.org6bb0c6e2013-05-10 20:52:00 +0000321 if (current_url != url and url != 'git://foo' and
322 self._Capture(['config', 'remote.origin.gclient']) != 'getoffmylawn'):
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000323 print('_____ switching %s to a new upstream' % self.relpath)
324 # Make sure it's clean
325 self._CheckClean(rev_str)
326 # Switch over to the new upstream
327 self._Run(['remote', 'set-url', 'origin', url], options)
328 quiet = []
329 if not options.verbose:
330 quiet = ['--quiet']
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000331 self._UpdateBranchHeads(options, fetch=False)
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000332 self._Run(['fetch', 'origin', '--prune'] + quiet, options)
bauerb@chromium.org610060e2012-11-19 14:11:35 +0000333 self._Run(['reset', '--hard', revision] + quiet, options)
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000334 self.UpdateSubmoduleConfig()
thomasvl@chromium.org668667c2011-03-24 18:27:24 +0000335 files = self._Capture(['ls-files']).splitlines()
336 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
337 return
338
msb@chromium.org5bde4852009-12-14 16:47:12 +0000339 cur_branch = self._GetCurrentBranch()
340
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000341 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000342 # 0) HEAD is detached. Probably from our initial clone.
343 # - make sure HEAD is contained by a named ref, then update.
344 # Cases 1-4. HEAD is a branch.
345 # 1) current branch is not tracking a remote branch (could be git-svn)
346 # - try to rebase onto the new hash or branch
347 # 2) current branch is tracking a remote branch with local committed
348 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000349 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000350 # 3) current branch is tracking a remote branch w/or w/out changes,
351 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000352 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000353 # 4) current branch is tracking a remote branch, switches to a different
354 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000355 # - exit
356
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000357 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
358 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000359 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
360 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000361 if cur_branch is None:
362 upstream_branch = None
363 current_type = "detached"
364 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000365 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000366 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
367 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
368 current_type = "hash"
369 logging.debug("Current branch is not tracking an upstream (remote)"
370 " branch.")
371 elif upstream_branch.startswith('refs/remotes'):
372 current_type = "branch"
373 else:
374 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000375
maruel@chromium.org92067382012-06-28 19:58:41 +0000376 if (not re.match(r'^[0-9a-fA-F]{40}$', revision) or
377 not scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=revision)):
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000378 # Update the remotes first so we have all the refs.
379 backoff_time = 5
380 for _ in range(10):
381 try:
382 remote_output = scm.GIT.Capture(
383 ['remote'] + verbose + ['update'],
384 cwd=self.checkout_path)
385 break
386 except subprocess2.CalledProcessError, e:
387 # Hackish but at that point, git is known to work so just checking for
388 # 502 in stderr should be fine.
389 if '502' in e.stderr:
390 print(str(e))
391 print('Sleeping %.1f seconds and retrying...' % backoff_time)
392 time.sleep(backoff_time)
393 backoff_time *= 1.3
394 continue
395 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000396
bauerb@chromium.orgcbd20a42012-06-27 13:49:27 +0000397 if verbose:
398 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000399
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000400 self._UpdateBranchHeads(options, fetch=True)
401
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000402 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000403 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000404 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000405
msb@chromium.org786fb682010-06-02 15:16:23 +0000406 if current_type == 'detached':
407 # case 0
408 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000409 self._CheckDetachedHead(rev_str, options)
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000410 self._Capture(['checkout', '--quiet', '%s' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000411 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000412 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000413 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000414 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000415 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000416 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000417 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000418 newbase=revision, printed_path=printed_path)
419 printed_path = True
420 else:
421 # Can't find a merge-base since we don't know our upstream. That makes
422 # this command VERY likely to produce a rebase failure. For now we
423 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000424 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000425 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000426 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000427 self._AttemptRebase(upstream_branch, files, options,
428 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000429 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000430 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000431 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000432 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000433 newbase=revision, printed_path=printed_path)
434 printed_path = True
435 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
436 # case 4
437 new_base = revision.replace('heads', 'remotes/origin')
438 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000439 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000440 switch_error = ("Switching upstream branch from %s to %s\n"
441 % (upstream_branch, new_base) +
442 "Please merge or rebase manually:\n" +
443 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
444 "OR git checkout -b <some new branch> %s" % new_base)
445 raise gclient_utils.Error(switch_error)
446 else:
447 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000448 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000449 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000450 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000451 try:
bauerb@chromium.org2aad1b22011-07-22 12:00:41 +0000452 merge_args = ['merge']
453 if not options.merge:
454 merge_args.append('--ff-only')
455 merge_args.append(upstream_branch)
456 merge_output = scm.GIT.Capture(merge_args, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000457 except subprocess2.CalledProcessError, e:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000458 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
459 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000460 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000461 printed_path = True
462 while True:
463 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000464 # TODO(maruel): That can't work with --jobs.
maruel@chromium.org90541732011-04-01 17:54:18 +0000465 action = ask_for_data(
466 'Cannot fast-forward merge, attempt to rebase? '
467 '(y)es / (q)uit / (s)kip : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000468 except ValueError:
maruel@chromium.org90541732011-04-01 17:54:18 +0000469 raise gclient_utils.Error('Invalid Character')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000470 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000471 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000472 printed_path=printed_path)
473 printed_path = True
474 break
475 elif re.match(r'quit|q', action, re.I):
476 raise gclient_utils.Error("Can't fast-forward, please merge or "
477 "rebase manually.\n"
478 "cd %s && git " % self.checkout_path
479 + "rebase %s" % upstream_branch)
480 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000481 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000482 return
483 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000484 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000485 elif re.match("error: Your local changes to '.*' would be "
486 "overwritten by merge. Aborting.\nPlease, commit your "
487 "changes or stash them before you can merge.\n",
488 e.stderr):
489 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000490 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000491 printed_path = True
492 raise gclient_utils.Error(e.stderr)
493 else:
494 # Some other problem happened with the merge
495 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000496 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000497 raise
498 else:
499 # Fast-forward merge was successful
500 if not re.match('Already up-to-date.', merge_output) or verbose:
501 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000502 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000503 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000504 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000505 if not verbose:
506 # Make the output a little prettier. It's nice to have some
507 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000508 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000509
szager@chromium.orgd4af6622012-06-04 22:13:55 +0000510 self.UpdateSubmoduleConfig()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000511 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000512
513 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000514 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000515 raise gclient_utils.Error('\n____ %s%s\n'
516 '\nConflict while rebasing this branch.\n'
517 'Fix the conflict and run gclient again.\n'
518 'See man git-rebase for details.\n'
519 % (self.relpath, rev_str))
520
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000521 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000522 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000523
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000524 # If --reset and --delete_unversioned_trees are specified, remove any
525 # untracked directories.
526 if options.reset and options.delete_unversioned_trees:
527 # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
528 # merge-base by default), so doesn't include untracked files. So we use
529 # 'git ls-files --directory --others --exclude-standard' here directly.
530 paths = scm.GIT.Capture(
531 ['ls-files', '--directory', '--others', '--exclude-standard'],
532 self.checkout_path)
533 for path in (p for p in paths.splitlines() if p.endswith('/')):
534 full_path = os.path.join(self.checkout_path, path)
535 if not os.path.islink(full_path):
536 print('\n_____ removing unversioned directory %s' % path)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +0000537 gclient_utils.rmtree(full_path)
steveblock@chromium.org98e69452012-02-16 16:36:43 +0000538
539
msb@chromium.orge28e4982009-09-25 20:51:45 +0000540 def revert(self, options, args, file_list):
541 """Reverts local modifications.
542
543 All reverted files will be appended to file_list.
544 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000545 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000546 # revert won't work if the directory doesn't exist. It needs to
547 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000548 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000549 # Don't reuse the args.
550 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000551
552 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000553 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000554 if not deps_revision:
555 deps_revision = default_rev
556 if deps_revision.startswith('refs/heads/'):
557 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
558
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000559 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000560 self._Run(['reset', '--hard', deps_revision], options)
lliabraa@chromium.orgade83db2012-09-27 14:06:49 +0000561 self._Run(['clean', '-f', '-d'], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000562 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
563
msb@chromium.org0f282062009-11-06 20:14:02 +0000564 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000565 """Returns revision"""
566 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000567
msb@chromium.orge28e4982009-09-25 20:51:45 +0000568 def runhooks(self, options, args, file_list):
569 self.status(options, args, file_list)
570
571 def status(self, options, args, file_list):
572 """Display status information."""
573 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000574 print(('\n________ couldn\'t run status in %s:\n'
575 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000576 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000577 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000578 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000579 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000580 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
581
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000582 def GetUsableRev(self, rev, options):
583 """Finds a useful revision for this repository.
584
585 If SCM is git-svn and the head revision is less than |rev|, git svn fetch
586 will be called on the source."""
587 sha1 = None
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000588 if not os.path.isdir(self.checkout_path):
589 raise gclient_utils.Error(
590 ( 'We could not find a valid hash for safesync_url response "%s".\n'
591 'Safesync URLs with a git checkout currently require the repo to\n'
592 'be cloned without a safesync_url before adding the safesync_url.\n'
593 'For more info, see: '
594 'http://code.google.com/p/chromium/wiki/UsingNewGit'
595 '#Initial_checkout' ) % rev)
596 elif rev.isdigit() and len(rev) < 7:
597 # Handles an SVN rev. As an optimization, only verify an SVN revision as
598 # [0-9]{1,6} for now to avoid making a network request.
599 if scm.GIT.IsGitSvn(cwd=self.checkout_path):
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000600 local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
601 if not local_head or local_head < int(rev):
dbeam@chromium.org2a75fdb2012-02-15 01:32:57 +0000602 try:
603 logging.debug('Looking for git-svn configuration optimizations.')
604 if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
605 cwd=self.checkout_path):
606 scm.GIT.Capture(['fetch'], cwd=self.checkout_path)
607 except subprocess2.CalledProcessError:
608 logging.debug('git config --get svn-remote.svn.fetch failed, '
609 'ignoring possible optimization.')
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000610 if options.verbose:
611 print('Running git svn fetch. This might take a while.\n')
612 scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
szager@google.com312a6a42012-10-11 21:19:42 +0000613 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000614 sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
615 cwd=self.checkout_path, rev=rev)
szager@google.com312a6a42012-10-11 21:19:42 +0000616 except gclient_utils.Error, e:
617 sha1 = e.message
618 print('\nWarning: Could not find a git revision with accurate\n'
619 '.DEPS.git that maps to SVN revision %s. Sync-ing to\n'
620 'the closest sane git revision, which is:\n'
621 ' %s\n' % (rev, e.message))
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000622 if not sha1:
623 raise gclient_utils.Error(
624 ( 'It appears that either your git-svn remote is incorrectly\n'
625 'configured or the revision in your safesync_url is\n'
626 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
627 'corresponding git hash for SVN rev %s.' ) % rev)
iannucci@chromium.org3830a672013-02-19 20:15:14 +0000628 else:
629 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
630 sha1 = rev
631 else:
632 # May exist in origin, but we don't have it yet, so fetch and look
633 # again.
634 scm.GIT.Capture(['fetch', 'origin'], cwd=self.checkout_path)
635 if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
636 sha1 = rev
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000637
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000638 if not sha1:
639 raise gclient_utils.Error(
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000640 ( 'We could not find a valid hash for safesync_url response "%s".\n'
641 'Safesync URLs with a git checkout currently require a git-svn\n'
642 'remote or a safesync_url that provides git sha1s. Please add a\n'
643 'git-svn remote or change your safesync_url. For more info, see:\n'
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000644 'http://code.google.com/p/chromium/wiki/UsingNewGit'
dbeam@chromium.org051c88b2011-12-22 00:23:03 +0000645 '#Initial_checkout' ) % rev)
646
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000647 return sha1
648
msb@chromium.orge6f78352010-01-13 17:05:33 +0000649 def FullUrlForRelativeUrl(self, url):
650 # Strip from last '/'
651 # Equivalent to unix basename
652 base_url = self.url
653 return base_url[:base_url.rfind('/')] + url
654
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000655 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000656 """Clone a git repository from the given URL.
657
msb@chromium.org786fb682010-06-02 15:16:23 +0000658 Once we've cloned the repo, we checkout a working branch if the specified
659 revision is a branch head. If it is a tag or a specific commit, then we
660 leave HEAD detached as it makes future updates simpler -- in this case the
661 user should first create a new branch or switch to an existing branch before
662 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000663 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000664 # git clone doesn't seem to insert a newline properly before printing
665 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000666 print('')
szager@chromium.orgee10d7d2013-04-24 23:18:20 +0000667 clone_cmd = ['clone', '--progress']
msb@chromium.org786fb682010-06-02 15:16:23 +0000668 if revision.startswith('refs/heads/'):
669 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
670 detach_head = False
671 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000672 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000673 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000674 clone_cmd.append('--verbose')
675 clone_cmd.extend([url, self.checkout_path])
676
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000677 # If the parent directory does not exist, Git clone on Windows will not
678 # create it, so we need to do it manually.
679 parent_dir = os.path.dirname(self.checkout_path)
680 if not os.path.exists(parent_dir):
maruel@chromium.org6c48a302011-10-20 23:44:20 +0000681 gclient_utils.safe_makedirs(parent_dir)
nsylvain@chromium.org328c3c72011-06-01 20:50:27 +0000682
szager@google.com85d3e3a2011-10-07 17:12:00 +0000683 percent_re = re.compile('.* ([0-9]{1,2})% .*')
684 def _GitFilter(line):
685 # git uses an escape sequence to clear the line; elide it.
686 esc = line.find(unichr(033))
687 if esc > -1:
688 line = line[:esc]
689 match = percent_re.match(line)
690 if not match or not int(match.group(1)) % 10:
691 print '%s' % line
692
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000693 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000694 try:
szager@google.com85d3e3a2011-10-07 17:12:00 +0000695 self._Run(clone_cmd, options, cwd=self._root_dir, filter_fn=_GitFilter,
696 print_stdout=False)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000697 break
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000698 except subprocess2.CalledProcessError, e:
699 # Too bad we don't have access to the actual output yet.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000700 # We should check for "transfer closed with NNN bytes remaining to
701 # read". In the meantime, just make sure .git exists.
maruel@chromium.org2a5b6a22011-09-09 14:03:12 +0000702 if (e.returncode == 128 and
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000703 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000704 print(str(e))
705 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000706 continue
707 raise e
708
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000709 # Update the "branch-heads" remote-tracking branches, since we might need it
710 # to checkout a specific revision below.
711 self._UpdateBranchHeads(options, fetch=True)
mmoss@chromium.org059cc452013-03-11 15:14:35 +0000712
msb@chromium.org786fb682010-06-02 15:16:23 +0000713 if detach_head:
714 # Squelch git's very verbose detached HEAD warning and use our own
nsylvain@chromium.orgf7826d72011-06-02 18:20:14 +0000715 self._Capture(['checkout', '--quiet', '%s' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000716 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000717 ('Checked out %s to a detached HEAD. Before making any commits\n'
718 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
719 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
720 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000721
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000722 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000723 branch=None, printed_path=False):
724 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000725 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000726 revision = upstream
727 if newbase:
728 revision = newbase
729 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000730 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000731 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000732 printed_path = True
733 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000734 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000735
736 # Build the rebase command here using the args
737 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
738 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000739 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000740 rebase_cmd.append('--verbose')
741 if newbase:
742 rebase_cmd.extend(['--onto', newbase])
743 rebase_cmd.append(upstream)
744 if branch:
745 rebase_cmd.append(branch)
746
747 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000748 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000749 except subprocess2.CalledProcessError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000750 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
751 re.match(r'cannot rebase: your index contains uncommitted changes',
752 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000753 while True:
maruel@chromium.org90541732011-04-01 17:54:18 +0000754 rebase_action = ask_for_data(
755 'Cannot rebase because of unstaged changes.\n'
756 '\'git reset --hard HEAD\' ?\n'
757 'WARNING: destroys any uncommitted work in your current branch!'
758 ' (y)es / (q)uit / (s)how : ')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000759 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000760 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000761 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000762 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000763 break
764 elif re.match(r'quit|q', rebase_action, re.I):
765 raise gclient_utils.Error("Please merge or rebase manually\n"
766 "cd %s && git " % self.checkout_path
767 + "%s" % ' '.join(rebase_cmd))
768 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000769 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000770 continue
771 else:
772 gclient_utils.Error("Input not recognized")
773 continue
774 elif re.search(r'^CONFLICT', e.stdout, re.M):
775 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
776 "Fix the conflict and run gclient again.\n"
777 "See 'man git-rebase' for details.\n")
778 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000779 print(e.stdout.strip())
780 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000781 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
782 "manually.\ncd %s && git " %
783 self.checkout_path
784 + "%s" % ' '.join(rebase_cmd))
785
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000786 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000787 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000788 # Make the output a little prettier. It's nice to have some
789 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000790 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000791
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000792 @staticmethod
793 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000794 (ok, current_version) = scm.GIT.AssertVersion(min_version)
795 if not ok:
796 raise gclient_utils.Error('git version %s < minimum required %s' %
797 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000798
msb@chromium.org786fb682010-06-02 15:16:23 +0000799 def _IsRebasing(self):
800 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
801 # have a plumbing command to determine whether a rebase is in progress, so
802 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
803 g = os.path.join(self.checkout_path, '.git')
804 return (
805 os.path.isdir(os.path.join(g, "rebase-merge")) or
806 os.path.isdir(os.path.join(g, "rebase-apply")))
807
808 def _CheckClean(self, rev_str):
809 # Make sure the tree is clean; see git-rebase.sh for reference
810 try:
811 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000812 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000813 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000814 raise gclient_utils.Error('\n____ %s%s\n'
815 '\tYou have unstaged changes.\n'
816 '\tPlease commit, stash, or reset.\n'
817 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000818 try:
819 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000820 '--ignore-submodules', 'HEAD', '--'],
821 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000822 except subprocess2.CalledProcessError:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000823 raise gclient_utils.Error('\n____ %s%s\n'
824 '\tYour index contains uncommitted changes\n'
825 '\tPlease commit, stash, or reset.\n'
826 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000827
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000828 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000829 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
830 # reference by a commit). If not, error out -- most likely a rebase is
831 # in progress, try to detect so we can give a better error.
832 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000833 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
834 cwd=self.checkout_path)
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000835 except subprocess2.CalledProcessError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000836 # Commit is not contained by any rev. See if the user is rebasing:
837 if self._IsRebasing():
838 # Punt to the user
839 raise gclient_utils.Error('\n____ %s%s\n'
840 '\tAlready in a conflict, i.e. (no branch).\n'
841 '\tFix the conflict and run gclient again.\n'
842 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
843 '\tSee man git-rebase for details.\n'
844 % (self.relpath, rev_str))
845 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000846 name = ('saved-by-gclient-' +
847 self._Capture(['rev-parse', '--short', 'HEAD']))
848 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000849 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000850 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000851
msb@chromium.org5bde4852009-12-14 16:47:12 +0000852 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000853 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000854 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000855 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000856 return None
857 return branch
858
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000859 def _Capture(self, args):
maruel@chromium.orgbffad372011-09-08 17:54:22 +0000860 return subprocess2.check_output(
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000861 ['git'] + args,
862 stderr=subprocess2.PIPE,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000863 nag_timer=self.nag_timer,
864 nag_max=self.nag_max,
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000865 cwd=self.checkout_path).strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000866
mmoss@chromium.orge409df62013-04-16 17:28:57 +0000867 def _UpdateBranchHeads(self, options, fetch=False):
868 """Adds, and optionally fetches, "branch-heads" refspecs if requested."""
869 if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
870 backoff_time = 5
871 for _ in range(3):
872 try:
873 config_cmd = ['config', 'remote.origin.fetch',
874 '+refs/branch-heads/*:refs/remotes/branch-heads/*',
875 '^\\+refs/branch-heads/\\*:.*$']
876 self._Run(config_cmd, options)
877 if fetch:
878 fetch_cmd = ['fetch', 'origin']
879 if options.verbose:
880 fetch_cmd.append('--verbose')
881 self._Run(fetch_cmd, options)
882 break
883 except subprocess2.CalledProcessError, e:
884 print(str(e))
885 print('Retrying in %.1f seconds...' % backoff_time)
886 time.sleep(backoff_time)
887 backoff_time *= 1.3
888
maruel@chromium.org37e89872010-09-07 16:11:33 +0000889 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000890 kwargs.setdefault('cwd', self.checkout_path)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000891 kwargs.setdefault('print_stdout', True)
szager@chromium.org12b07e72013-05-03 22:06:34 +0000892 kwargs.setdefault('nag_timer', self.nag_timer)
893 kwargs.setdefault('nag_max', self.nag_max)
szager@google.com85d3e3a2011-10-07 17:12:00 +0000894 stdout = kwargs.get('stdout', sys.stdout)
895 stdout.write('\n________ running \'git %s\' in \'%s\'\n' % (
896 ' '.join(args), kwargs['cwd']))
897 gclient_utils.CheckCallAndFilter(['git'] + args, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000898
899
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000900class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000901 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000902
mukai@chromium.org9e3e82c2012-04-18 12:55:43 +0000903 @staticmethod
904 def BinaryExists():
905 """Returns true if the command exists."""
906 try:
907 result, version = scm.SVN.AssertVersion('1.4')
908 if not result:
909 raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
910 return result
911 except OSError:
912 return False
913
floitsch@google.comeaab7842011-04-28 09:07:58 +0000914 def GetRevisionDate(self, revision):
915 """Returns the given revision's date in ISO-8601 format (which contains the
916 time zone)."""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000917 date = scm.SVN.Capture(
918 ['propget', '--revprop', 'svn:date', '-r', revision],
919 os.path.join(self.checkout_path, '.'))
floitsch@google.comeaab7842011-04-28 09:07:58 +0000920 return date.strip()
921
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000922 def cleanup(self, options, args, file_list):
923 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000924 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000925
926 def diff(self, options, args, file_list):
927 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000928 if not os.path.isdir(self.checkout_path):
929 raise gclient_utils.Error('Directory %s is not present.' %
930 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000931 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000932
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000933 def pack(self, options, args, file_list):
934 """Generates a patch file which can be applied to the root of the
935 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000936 if not os.path.isdir(self.checkout_path):
937 raise gclient_utils.Error('Directory %s is not present.' %
938 self.checkout_path)
939 gclient_utils.CheckCallAndFilter(
940 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
941 cwd=self.checkout_path,
942 print_stdout=False,
szager@chromium.org12b07e72013-05-03 22:06:34 +0000943 nag_timer=self.nag_timer,
944 nag_max=self.nag_max,
haitao.feng@intel.com306080c2012-05-04 13:11:29 +0000945 filter_fn=SvnDiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000946
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000947 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000948 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000949
950 All updated files will be appended to file_list.
951
952 Raises:
953 Error: if can't get URL for relative path.
954 """
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000955 # Only update if git or hg is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000956 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000957 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000958 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000959 return
960
morrita@chromium.org21dca0e2010-10-05 00:55:12 +0000961 hg_path = os.path.join(self.checkout_path, '.hg')
962 if os.path.exists(hg_path):
963 print('________ found .hg directory; skipping %s' % self.relpath)
964 return
965
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000966 if args:
967 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
968
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000969 # revision is the revision to match. It is None if no revision is specified,
970 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000971 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000972 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000973 base_url = url
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000974 managed = True
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000975 if options.revision:
976 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000977 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000978 if revision:
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +0000979 if revision != 'unmanaged':
980 forced_revision = True
981 # Reconstruct the url.
982 url = '%s@%s' % (url, revision)
983 rev_str = ' at %s' % revision
984 else:
985 managed = False
986 revision = None
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000987 else:
988 forced_revision = False
989 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000990
davidjames@chromium.org13349e22012-11-15 17:11:28 +0000991 # Get the existing scm url and the revision number of the current checkout.
992 exists = os.path.exists(self.checkout_path)
993 if exists and managed:
994 try:
995 from_info = scm.SVN.CaptureLocalInfo(
996 [], os.path.join(self.checkout_path, '.'))
997 except (gclient_utils.Error, subprocess2.CalledProcessError):
998 if options.reset and options.delete_unversioned_trees:
999 print 'Removing troublesome path %s' % self.checkout_path
1000 gclient_utils.rmtree(self.checkout_path)
1001 exists = False
1002 else:
1003 msg = ('Can\'t update/checkout %s if an unversioned directory is '
1004 'present. Delete the directory and try again.')
1005 raise gclient_utils.Error(msg % self.checkout_path)
1006
1007 if not exists:
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001008 gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001009 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001010 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001011 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001012 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001013 return
1014
cmp@chromium.orgeb2756d2011-09-20 20:17:51 +00001015 if not managed:
1016 print ('________ unmanaged solution; skipping %s' % self.relpath)
1017 return
1018
maruel@chromium.org49fcb0c2011-09-23 14:34:38 +00001019 if 'URL' not in from_info:
1020 raise gclient_utils.Error(
1021 ('gclient is confused. Couldn\'t get the url for %s.\n'
1022 'Try using @unmanaged.\n%s') % (
1023 self.checkout_path, from_info))
1024
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001025 # Look for locked directories.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001026 dir_info = scm.SVN.CaptureStatus(
1027 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001028 if any(d[0][2] == 'L' for d in dir_info):
1029 try:
1030 self._Run(['cleanup', self.checkout_path], options)
1031 except subprocess2.CalledProcessError, e:
1032 # Get the status again, svn cleanup may have cleaned up at least
1033 # something.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001034 dir_info = scm.SVN.CaptureStatus(
1035 None, os.path.join(self.checkout_path, '.'))
phajdan.jr@chromium.orgd558c4b2011-09-22 18:56:24 +00001036
1037 # Try to fix the failures by removing troublesome files.
1038 for d in dir_info:
1039 if d[0][2] == 'L':
1040 if d[0][0] == '!' and options.force:
1041 print 'Removing troublesome path %s' % d[1]
1042 gclient_utils.rmtree(d[1])
1043 else:
1044 print 'Not removing troublesome path %s automatically.' % d[1]
1045 if d[0][0] == '!':
1046 print 'You can pass --force to enable automatic removal.'
1047 raise e
maruel@chromium.orge407c9a2010-08-09 19:11:37 +00001048
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001049 # Retrieve the current HEAD version because svn is slow at null updates.
1050 if options.manually_grab_svn_rev and not revision:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001051 from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001052 revision = str(from_info_live['Revision'])
1053 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001054
msb@chromium.orgac915bb2009-11-13 17:03:01 +00001055 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001056 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +00001057 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001058 to_info = scm.SVN.CaptureRemoteInfo(url)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001059 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +00001060 # The url is invalid or the server is not accessible, it's safer to bail
1061 # out right now.
1062 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001063 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1064 and (from_info['UUID'] == to_info['UUID']))
1065 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001066 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001067 # We have different roots, so check if we can switch --relocate.
1068 # Subversion only permits this if the repository UUIDs match.
1069 # Perform the switch --relocate, then rewrite the from_url
1070 # to reflect where we "are now." (This is the same way that
1071 # Subversion itself handles the metadata when switch --relocate
1072 # is used.) This makes the checks below for whether we
1073 # can update to a revision or have to switch to a different
1074 # branch work as expected.
1075 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001076 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001077 from_info['Repository Root'],
1078 to_info['Repository Root'],
1079 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001080 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001081 from_info['URL'] = from_info['URL'].replace(
1082 from_info['Repository Root'],
1083 to_info['Repository Root'])
1084 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +00001085 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001086 # Look for local modifications but ignore unversioned files.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001087 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001088 if status[0][0] != '?':
maruel@chromium.org86f0f952010-08-10 17:17:19 +00001089 raise gclient_utils.Error(
1090 ('Can\'t switch the checkout to %s; UUID don\'t match and '
1091 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001092 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001093 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001094 print('\n_____ switching %s to a new checkout' % self.relpath)
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001095 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001096 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001097 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001098 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001099 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001100 return
1101
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001102 # If the provided url has a revision number that matches the revision
1103 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +00001104 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001105 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001106 print('\n_____ %s%s' % (self.relpath, rev_str))
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001107 else:
1108 command = ['update', self.checkout_path]
1109 command = self._AddAdditionalUpdateFlags(command, options, revision)
1110 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001111
steveblock@chromium.org98e69452012-02-16 16:36:43 +00001112 # If --reset and --delete_unversioned_trees are specified, remove any
1113 # untracked files and directories.
1114 if options.reset and options.delete_unversioned_trees:
1115 for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1116 full_path = os.path.join(self.checkout_path, status[1])
1117 if (status[0][0] == '?'
1118 and os.path.isdir(full_path)
1119 and not os.path.islink(full_path)):
1120 print('\n_____ removing unversioned directory %s' % status[1])
digit@chromium.orgdc112ac2013-04-24 13:00:19 +00001121 gclient_utils.rmtree(full_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001122
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001123 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001124 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +00001125 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001126 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +00001127 # Create an empty checkout and then update the one file we want. Future
1128 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001129 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001130 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001131 if os.path.exists(os.path.join(self.checkout_path, filename)):
1132 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +00001133 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +00001134 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +00001135 # After the initial checkout, we can use update as if it were any other
1136 # dep.
1137 self.update(options, args, file_list)
1138 else:
1139 # If the installed version of SVN doesn't support --depth, fallback to
1140 # just exporting the file. This has the downside that revision
1141 # information is not stored next to the file, so we will have to
1142 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001143 if not os.path.exists(self.checkout_path):
maruel@chromium.org6c48a302011-10-20 23:44:20 +00001144 gclient_utils.safe_makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +00001145 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001146 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001147 command = self._AddAdditionalUpdateFlags(command, options,
1148 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001149 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +00001150
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001151 def revert(self, options, args, file_list):
1152 """Reverts local modifications. Subversion specific.
1153
1154 All reverted files will be appended to file_list, even if Subversion
1155 doesn't know about them.
1156 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001157 if not os.path.isdir(self.checkout_path):
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001158 if os.path.exists(self.checkout_path):
1159 gclient_utils.rmtree(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001160 # svn revert won't work if the directory doesn't exist. It needs to
1161 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001162 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001163 # Don't reuse the args.
1164 return self.update(options, [], file_list)
1165
maruel@chromium.orgc0cc0872011-10-12 17:02:41 +00001166 if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1167 if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1168 print('________ found .git directory; skipping %s' % self.relpath)
1169 return
1170 if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1171 print('________ found .hg directory; skipping %s' % self.relpath)
1172 return
1173 if not options.force:
1174 raise gclient_utils.Error('Invalid checkout path, aborting')
1175 print(
1176 '\n_____ %s is not a valid svn checkout, synching instead' %
1177 self.relpath)
1178 gclient_utils.rmtree(self.checkout_path)
1179 # Don't reuse the args.
1180 return self.update(options, [], file_list)
1181
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001182 def printcb(file_status):
1183 file_list.append(file_status[1])
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001184 if logging.getLogger().isEnabledFor(logging.INFO):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001185 logging.info('%s%s' % (file_status[0], file_status[1]))
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001186 else:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001187 print(os.path.join(self.checkout_path, file_status[1]))
1188 scm.SVN.Revert(self.checkout_path, callback=printcb)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +00001189
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001190 # Revert() may delete the directory altogether.
1191 if not os.path.isdir(self.checkout_path):
1192 # Don't reuse the args.
1193 return self.update(options, [], file_list)
1194
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001195 try:
1196 # svn revert is so broken we don't even use it. Using
1197 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001198 # file_list will contain duplicates.
maruel@chromium.org669600d2010-09-01 19:06:31 +00001199 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1200 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001201 except OSError, e:
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001202 # Maybe the directory disapeared meanwhile. Do not throw an exception.
maruel@chromium.org810a50b2009-10-05 23:03:18 +00001203 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001204
msb@chromium.org0f282062009-11-06 20:14:02 +00001205 def revinfo(self, options, args, file_list):
1206 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +00001207 try:
1208 return scm.SVN.CaptureRevision(self.checkout_path)
maruel@chromium.org31cb48a2011-04-04 18:01:36 +00001209 except (gclient_utils.Error, subprocess2.CalledProcessError):
maruel@chromium.org54019f32010-09-09 13:50:11 +00001210 return None
msb@chromium.org0f282062009-11-06 20:14:02 +00001211
msb@chromium.orgcb5442b2009-09-22 16:51:24 +00001212 def runhooks(self, options, args, file_list):
1213 self.status(options, args, file_list)
1214
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001215 def status(self, options, args, file_list):
1216 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +00001217 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001218 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001219 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001220 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1221 'The directory does not exist.') %
1222 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001223 # There's no file list to retrieve.
1224 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +00001225 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +00001226
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001227 def GetUsableRev(self, rev, options):
1228 """Verifies the validity of the revision for this repository."""
1229 if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1230 raise gclient_utils.Error(
1231 ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1232 'correct.') % rev)
1233 return rev
1234
msb@chromium.orge6f78352010-01-13 17:05:33 +00001235 def FullUrlForRelativeUrl(self, url):
1236 # Find the forth '/' and strip from there. A bit hackish.
1237 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +00001238
maruel@chromium.org669600d2010-09-01 19:06:31 +00001239 def _Run(self, args, options, **kwargs):
1240 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001241 kwargs.setdefault('cwd', self.checkout_path)
szager@chromium.org12b07e72013-05-03 22:06:34 +00001242 kwargs.setdefault('nag_timer', self.nag_timer)
1243 kwargs.setdefault('nag_max', self.nag_max)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001244 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001245 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001246
1247 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1248 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +00001249 cwd = cwd or self.checkout_path
maruel@chromium.orgce117f62011-01-17 20:04:25 +00001250 scm.SVN.RunAndGetFileList(
1251 options.verbose,
1252 args + ['--ignore-externals'],
1253 cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +00001254 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +00001255
maruel@chromium.org6e29d572010-06-04 17:32:20 +00001256 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +00001257 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +00001258 """Add additional flags to command depending on what options are set.
1259 command should be a list of strings that represents an svn command.
1260
1261 This method returns a new list to be used as a command."""
1262 new_command = command[:]
1263 if revision:
1264 new_command.extend(['--revision', str(revision).strip()])
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001265 # We don't want interaction when jobs are used.
1266 if options.jobs > 1:
1267 new_command.append('--non-interactive')
tony@chromium.org99828122010-06-04 01:41:02 +00001268 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001269 # --accept was added to 'svn update' in svn 1.6.
1270 if not scm.SVN.AssertVersion('1.5')[0]:
1271 return new_command
1272
1273 # It's annoying to have it block in the middle of a sync, just sensible
1274 # defaults.
1275 if options.force:
tony@chromium.org99828122010-06-04 01:41:02 +00001276 new_command.append('--force')
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001277 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1278 new_command.extend(('--accept', 'theirs-conflict'))
1279 elif options.manually_grab_svn_rev:
1280 new_command.append('--force')
1281 if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1282 new_command.extend(('--accept', 'postpone'))
1283 elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1284 new_command.extend(('--accept', 'postpone'))
tony@chromium.org99828122010-06-04 01:41:02 +00001285 return new_command