blob: 066f5e79a179093a404eafea6b9b3d0630ab851c [file] [log] [blame]
scherkus@chromium.org95f0f4e2010-05-22 00:55:26 +00001# Copyright (c) 2010 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.org945405e2010-08-18 17:01:49 +000011import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000012import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000013
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000014import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016
17
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000018class DiffFilterer(object):
19 """Simple class which tracks which file is being diffed and
20 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000021 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000022 index_string = "Index: "
23 original_prefix = "--- "
24 working_prefix = "+++ "
25
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000026 def __init__(self, relpath):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000027 # Note that we always use '/' as the path separator to be
28 # consistent with svn's cygwin-style output on Windows
29 self._relpath = relpath.replace("\\", "/")
30 self._current_file = ""
31 self._replacement_file = ""
32
maruel@chromium.org6e29d572010-06-04 17:32:20 +000033 def SetCurrentFile(self, current_file):
34 self._current_file = current_file
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000035 # Note that we always use '/' as the path separator to be
36 # consistent with svn's cygwin-style output on Windows
maruel@chromium.org6e29d572010-06-04 17:32:20 +000037 self._replacement_file = posixpath.join(self._relpath, current_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000038
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000039 def _Replace(self, line):
40 return line.replace(self._current_file, self._replacement_file)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000041
42 def Filter(self, line):
43 if (line.startswith(self.index_string)):
44 self.SetCurrentFile(line[len(self.index_string):])
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000045 line = self._Replace(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000046 else:
47 if (line.startswith(self.original_prefix) or
48 line.startswith(self.working_prefix)):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +000049 line = self._Replace(line)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +000050 print(line)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000051
52
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000053### SCM abstraction layer
54
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000055# Factory Method for SCM wrapper creation
56
maruel@chromium.org9eda4112010-06-11 18:56:10 +000057def GetScmName(url):
58 if url:
59 url, _ = gclient_utils.SplitUrlRevision(url)
60 if (url.startswith('git://') or url.startswith('ssh://') or
61 url.endswith('.git')):
62 return 'git'
maruel@chromium.orgb74dca22010-06-11 20:10:40 +000063 elif (url.startswith('http://') or url.startswith('https://') or
maruel@chromium.org54a07a22010-06-14 19:07:39 +000064 url.startswith('svn://') or url.startswith('svn+ssh://')):
maruel@chromium.org9eda4112010-06-11 18:56:10 +000065 return 'svn'
66 return None
67
68
69def CreateSCM(url, root_dir=None, relpath=None):
70 SCM_MAP = {
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000071 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000072 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000073 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000074
maruel@chromium.org9eda4112010-06-11 18:56:10 +000075 scm_name = GetScmName(url)
76 if not scm_name in SCM_MAP:
77 raise gclient_utils.Error('No SCM found for url %s' % url)
78 return SCM_MAP[scm_name](url, root_dir, relpath)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000079
80
81# SCMWrapper base class
82
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000083class SCMWrapper(object):
84 """Add necessary glue between all the supported SCM.
85
msb@chromium.orgd6504212010-01-13 17:34:31 +000086 This is the abstraction layer to bind to different SCM.
87 """
maruel@chromium.org9eda4112010-06-11 18:56:10 +000088 def __init__(self, url=None, root_dir=None, relpath=None):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000089 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000090 self._root_dir = root_dir
91 if self._root_dir:
92 self._root_dir = self._root_dir.replace('/', os.sep)
93 self.relpath = relpath
94 if self.relpath:
95 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000096 if self.relpath and self._root_dir:
97 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000098
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000099 def RunCommand(self, command, options, args, file_list=None):
100 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +0000101 if file_list is None:
102 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000103
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000104 commands = ['cleanup', 'export', 'update', 'updatesingle', 'revert',
105 'revinfo', 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000106
107 if not command in commands:
108 raise gclient_utils.Error('Unknown command %s' % command)
109
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000110 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000111 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
maruel@chromium.org9eda4112010-06-11 18:56:10 +0000112 command, self.__class__.__name__))
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000113
114 return getattr(self, command)(options, args, file_list)
115
116
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000117class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000118 """Wrapper for Git"""
119
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000120 @staticmethod
121 def cleanup(options, args, file_list):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000122 """'Cleanup' the repo.
123
124 There's no real git equivalent for the svn cleanup command, do a no-op.
125 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000126
127 def diff(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000128 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000129 self._Run(['diff', merge_base], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000130
131 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000132 """Export a clean directory tree into the given path.
133
134 Exports into the specified directory, creating the path if it does
135 already exist.
136 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000137 assert len(args) == 1
138 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
139 if not os.path.exists(export_path):
140 os.makedirs(export_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000141 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
142 options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000143
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000144 def pack(self, options, args, file_list):
145 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000146 repository.
147
148 The patch file is generated from a diff of the merge base of HEAD and
149 its upstream branch.
150 """
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000151 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org17d01792010-09-01 18:07:10 +0000152 gclient_utils.CheckCallAndFilter(
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000153 ['git', 'diff', merge_base],
154 cwd=self.checkout_path,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000155 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000156
msb@chromium.orge28e4982009-09-25 20:51:45 +0000157 def update(self, options, args, file_list):
158 """Runs git to update or transparently checkout the working copy.
159
160 All updated files will be appended to file_list.
161
162 Raises:
163 Error: if can't get URL for relative path.
164 """
msb@chromium.orge28e4982009-09-25 20:51:45 +0000165 if args:
166 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
167
nasser@codeaurora.orgece406f2010-02-23 17:29:15 +0000168 self._CheckMinVersion("1.6.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000169
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000170 default_rev = "refs/heads/master"
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000171 url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000172 rev_str = ""
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000173 revision = deps_revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000174 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000175 # Override the revision number.
176 revision = str(options.revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000177 if not revision:
178 revision = default_rev
msb@chromium.orge28e4982009-09-25 20:51:45 +0000179
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000180 rev_str = ' at %s' % revision
181 files = []
182
183 printed_path = False
184 verbose = []
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000185 if options.verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000186 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000187 verbose = ['--verbose']
188 printed_path = True
189
190 if revision.startswith('refs/heads/'):
191 rev_type = "branch"
192 elif revision.startswith('origin/'):
193 # For compatability with old naming, translate 'origin' to 'refs/heads'
194 revision = revision.replace('origin/', 'refs/heads/')
195 rev_type = "branch"
196 else:
197 # hash is also a tag, only make a distinction at checkout
198 rev_type = "hash"
199
msb@chromium.orge28e4982009-09-25 20:51:45 +0000200 if not os.path.exists(self.checkout_path):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000201 self._Clone(revision, url, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000202 files = self._Capture(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000203 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000204 if not verbose:
205 # Make the output a little prettier. It's nice to have some whitespace
206 # between projects when cloning.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000207 print('')
msb@chromium.orge28e4982009-09-25 20:51:45 +0000208 return
209
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000210 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
211 raise gclient_utils.Error('\n____ %s%s\n'
212 '\tPath is not a git repo. No .git dir.\n'
213 '\tTo resolve:\n'
214 '\t\trm -rf %s\n'
215 '\tAnd run gclient sync again\n'
216 % (self.relpath, rev_str, self.relpath))
217
msb@chromium.org5bde4852009-12-14 16:47:12 +0000218 cur_branch = self._GetCurrentBranch()
219
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000220 # Cases:
msb@chromium.org786fb682010-06-02 15:16:23 +0000221 # 0) HEAD is detached. Probably from our initial clone.
222 # - make sure HEAD is contained by a named ref, then update.
223 # Cases 1-4. HEAD is a branch.
224 # 1) current branch is not tracking a remote branch (could be git-svn)
225 # - try to rebase onto the new hash or branch
226 # 2) current branch is tracking a remote branch with local committed
227 # changes, but the DEPS file switched to point to a hash
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000228 # - rebase those changes on top of the hash
msb@chromium.org786fb682010-06-02 15:16:23 +0000229 # 3) current branch is tracking a remote branch w/or w/out changes,
230 # no switch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000231 # - see if we can FF, if not, prompt the user for rebase, merge, or stop
msb@chromium.org786fb682010-06-02 15:16:23 +0000232 # 4) current branch is tracking a remote branch, switches to a different
233 # remote branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000234 # - exit
235
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000236 # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
237 # a tracking branch
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000238 # or 'master' if not a tracking branch (it's based on a specific rev/hash)
239 # or it returns None if it couldn't find an upstream
msb@chromium.org786fb682010-06-02 15:16:23 +0000240 if cur_branch is None:
241 upstream_branch = None
242 current_type = "detached"
243 logging.debug("Detached HEAD")
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000244 else:
msb@chromium.org786fb682010-06-02 15:16:23 +0000245 upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
246 if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
247 current_type = "hash"
248 logging.debug("Current branch is not tracking an upstream (remote)"
249 " branch.")
250 elif upstream_branch.startswith('refs/remotes'):
251 current_type = "branch"
252 else:
253 raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000254
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000255 # Update the remotes first so we have all the refs.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000256 backoff_time = 5
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000257 for _ in range(10):
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000258 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000259 remote_output = scm.GIT.Capture(
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000260 ['remote'] + verbose + ['update'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000261 cwd=self.checkout_path)
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000262 break
maruel@chromium.org982984e2010-05-11 20:57:49 +0000263 except gclient_utils.CheckCallError, e:
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000264 # Hackish but at that point, git is known to work so just checking for
265 # 502 in stderr should be fine.
266 if '502' in e.stderr:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000267 print(str(e))
268 print('Sleeping %.1f seconds and retrying...' % backoff_time)
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000269 time.sleep(backoff_time)
270 backoff_time *= 1.3
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000271 continue
maruel@chromium.orgfd876172010-04-30 14:01:05 +0000272 raise
maruel@chromium.org0b1c2462010-03-02 00:48:14 +0000273
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000274 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000275 print(remote_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000276
277 # This is a big hammer, debatable if it should even be here...
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000278 if options.force or options.reset:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000279 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000280
msb@chromium.org786fb682010-06-02 15:16:23 +0000281 if current_type == 'detached':
282 # case 0
283 self._CheckClean(rev_str)
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000284 self._CheckDetachedHead(rev_str, options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000285 self._Capture(['checkout', '--quiet', '%s^0' % revision])
msb@chromium.org786fb682010-06-02 15:16:23 +0000286 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000287 print('\n_____ %s%s' % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000288 elif current_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000289 # case 1
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000290 if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000291 # Our git-svn branch (upstream_branch) is our upstream
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000292 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000293 newbase=revision, printed_path=printed_path)
294 printed_path = True
295 else:
296 # Can't find a merge-base since we don't know our upstream. That makes
297 # this command VERY likely to produce a rebase failure. For now we
298 # assume origin is our upstream since that's what the old behavior was.
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000299 upstream_branch = 'origin'
nasser@codeaurora.org7080e942010-03-15 15:06:16 +0000300 if options.revision or deps_revision:
nasser@codeaurora.org3b29de12010-03-08 18:34:28 +0000301 upstream_branch = revision
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000302 self._AttemptRebase(upstream_branch, files, options,
303 printed_path=printed_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000304 printed_path = True
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000305 elif rev_type == 'hash':
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000306 # case 2
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000307 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000308 newbase=revision, printed_path=printed_path)
309 printed_path = True
310 elif revision.replace('heads', 'remotes/origin') != upstream_branch:
311 # case 4
312 new_base = revision.replace('heads', 'remotes/origin')
313 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000314 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000315 switch_error = ("Switching upstream branch from %s to %s\n"
316 % (upstream_branch, new_base) +
317 "Please merge or rebase manually:\n" +
318 "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
319 "OR git checkout -b <some new branch> %s" % new_base)
320 raise gclient_utils.Error(switch_error)
321 else:
322 # case 3 - the default case
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000323 files = self._Capture(['diff', upstream_branch, '--name-only']).split()
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000324 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000325 print('Trying fast-forward merge to branch : %s' % upstream_branch)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000326 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000327 merge_output = scm.GIT.Capture(['merge', '--ff-only', upstream_branch],
328 cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000329 except gclient_utils.CheckCallError, e:
330 if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
331 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000332 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000333 printed_path = True
334 while True:
335 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000336 # TODO(maruel): That can't work with --jobs.
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000337 action = str(raw_input("Cannot fast-forward merge, attempt to "
338 "rebase? (y)es / (q)uit / (s)kip : "))
339 except ValueError:
340 gclient_utils.Error('Invalid Character')
341 continue
342 if re.match(r'yes|y', action, re.I):
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000343 self._AttemptRebase(upstream_branch, files, options,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000344 printed_path=printed_path)
345 printed_path = True
346 break
347 elif re.match(r'quit|q', action, re.I):
348 raise gclient_utils.Error("Can't fast-forward, please merge or "
349 "rebase manually.\n"
350 "cd %s && git " % self.checkout_path
351 + "rebase %s" % upstream_branch)
352 elif re.match(r'skip|s', action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000353 print('Skipping %s' % self.relpath)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000354 return
355 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000356 print('Input not recognized')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000357 elif re.match("error: Your local changes to '.*' would be "
358 "overwritten by merge. Aborting.\nPlease, commit your "
359 "changes or stash them before you can merge.\n",
360 e.stderr):
361 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000362 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000363 printed_path = True
364 raise gclient_utils.Error(e.stderr)
365 else:
366 # Some other problem happened with the merge
367 logging.error("Error during fast-forward merge in %s!" % self.relpath)
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000368 print(e.stderr)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000369 raise
370 else:
371 # Fast-forward merge was successful
372 if not re.match('Already up-to-date.', merge_output) or verbose:
373 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000374 print('\n_____ %s%s' % (self.relpath, rev_str))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000375 printed_path = True
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000376 print(merge_output.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000377 if not verbose:
378 # Make the output a little prettier. It's nice to have some
379 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000380 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000381
382 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.org5bde4852009-12-14 16:47:12 +0000383
384 # If the rebase generated a conflict, abort and ask user to fix
msb@chromium.org786fb682010-06-02 15:16:23 +0000385 if self._IsRebasing():
msb@chromium.org5bde4852009-12-14 16:47:12 +0000386 raise gclient_utils.Error('\n____ %s%s\n'
387 '\nConflict while rebasing this branch.\n'
388 'Fix the conflict and run gclient again.\n'
389 'See man git-rebase for details.\n'
390 % (self.relpath, rev_str))
391
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000392 if verbose:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000393 print('Checked out revision %s' % self.revinfo(options, (), None))
msb@chromium.orge28e4982009-09-25 20:51:45 +0000394
395 def revert(self, options, args, file_list):
396 """Reverts local modifications.
397
398 All reverted files will be appended to file_list.
399 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000400 if not os.path.isdir(self.checkout_path):
msb@chromium.org260c6532009-10-28 03:22:35 +0000401 # revert won't work if the directory doesn't exist. It needs to
402 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000403 print('\n_____ %s is missing, synching instead' % self.relpath)
msb@chromium.org260c6532009-10-28 03:22:35 +0000404 # Don't reuse the args.
405 return self.update(options, [], file_list)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000406
407 default_rev = "refs/heads/master"
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000408 _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
nasser@codeaurora.orgb2b46312010-04-30 20:58:03 +0000409 if not deps_revision:
410 deps_revision = default_rev
411 if deps_revision.startswith('refs/heads/'):
412 deps_revision = deps_revision.replace('refs/heads/', 'origin/')
413
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000414 files = self._Capture(['diff', deps_revision, '--name-only']).split()
maruel@chromium.org37e89872010-09-07 16:11:33 +0000415 self._Run(['reset', '--hard', deps_revision], options)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000416 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
417
msb@chromium.org0f282062009-11-06 20:14:02 +0000418 def revinfo(self, options, args, file_list):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000419 """Returns revision"""
420 return self._Capture(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000421
msb@chromium.orge28e4982009-09-25 20:51:45 +0000422 def runhooks(self, options, args, file_list):
423 self.status(options, args, file_list)
424
425 def status(self, options, args, file_list):
426 """Display status information."""
427 if not os.path.isdir(self.checkout_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000428 print(('\n________ couldn\'t run status in %s:\n'
429 'The directory does not exist.') % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000430 else:
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000431 merge_base = self._Capture(['merge-base', 'HEAD', 'origin'])
maruel@chromium.org37e89872010-09-07 16:11:33 +0000432 self._Run(['diff', '--name-status', merge_base], options)
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000433 files = self._Capture(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000434 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
435
msb@chromium.orge6f78352010-01-13 17:05:33 +0000436 def FullUrlForRelativeUrl(self, url):
437 # Strip from last '/'
438 # Equivalent to unix basename
439 base_url = self.url
440 return base_url[:base_url.rfind('/')] + url
441
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000442 def _Clone(self, revision, url, options):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000443 """Clone a git repository from the given URL.
444
msb@chromium.org786fb682010-06-02 15:16:23 +0000445 Once we've cloned the repo, we checkout a working branch if the specified
446 revision is a branch head. If it is a tag or a specific commit, then we
447 leave HEAD detached as it makes future updates simpler -- in this case the
448 user should first create a new branch or switch to an existing branch before
449 making changes in the repo."""
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000450 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000451 # git clone doesn't seem to insert a newline properly before printing
452 # to stdout
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000453 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000454
455 clone_cmd = ['clone']
msb@chromium.org786fb682010-06-02 15:16:23 +0000456 if revision.startswith('refs/heads/'):
457 clone_cmd.extend(['-b', revision.replace('refs/heads/', '')])
458 detach_head = False
459 else:
460 clone_cmd.append('--no-checkout')
461 detach_head = True
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000462 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000463 clone_cmd.append('--verbose')
464 clone_cmd.extend([url, self.checkout_path])
465
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000466 for _ in range(3):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000467 try:
maruel@chromium.org37e89872010-09-07 16:11:33 +0000468 self._Run(clone_cmd, options, cwd=self._root_dir)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000469 break
470 except gclient_utils.Error, e:
471 # TODO(maruel): Hackish, should be fixed by moving _Run() to
472 # CheckCall().
473 # Too bad we don't have access to the actual output.
474 # We should check for "transfer closed with NNN bytes remaining to
475 # read". In the meantime, just make sure .git exists.
476 if (e.args[0] == 'git command clone returned 128' and
477 os.path.exists(os.path.join(self.checkout_path, '.git'))):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000478 print(str(e))
479 print('Retrying...')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000480 continue
481 raise e
482
msb@chromium.org786fb682010-06-02 15:16:23 +0000483 if detach_head:
484 # Squelch git's very verbose detached HEAD warning and use our own
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000485 self._Capture(['checkout', '--quiet', '%s^0' % revision])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000486 print(
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000487 ('Checked out %s to a detached HEAD. Before making any commits\n'
488 'in this repo, you should use \'git checkout <branch>\' to switch to\n'
489 'an existing branch or use \'git checkout origin -b <branch>\' to\n'
490 'create a new branch for your work.') % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000491
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000492 def _AttemptRebase(self, upstream, files, options, newbase=None,
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000493 branch=None, printed_path=False):
494 """Attempt to rebase onto either upstream or, if specified, newbase."""
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000495 files.extend(self._Capture(['diff', upstream, '--name-only']).split())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000496 revision = upstream
497 if newbase:
498 revision = newbase
499 if not printed_path:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000500 print('\n_____ %s : Attempting rebase onto %s...' % (
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000501 self.relpath, revision))
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000502 printed_path = True
503 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000504 print('Attempting rebase onto %s...' % revision)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000505
506 # Build the rebase command here using the args
507 # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
508 rebase_cmd = ['rebase']
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000509 if options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000510 rebase_cmd.append('--verbose')
511 if newbase:
512 rebase_cmd.extend(['--onto', newbase])
513 rebase_cmd.append(upstream)
514 if branch:
515 rebase_cmd.append(branch)
516
517 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000518 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000519 except gclient_utils.CheckCallError, e:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000520 if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
521 re.match(r'cannot rebase: your index contains uncommitted changes',
522 e.stderr)):
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000523 while True:
524 rebase_action = str(raw_input("Cannot rebase because of unstaged "
525 "changes.\n'git reset --hard HEAD' ?\n"
526 "WARNING: destroys any uncommitted "
527 "work in your current branch!"
528 " (y)es / (q)uit / (s)how : "))
529 if re.match(r'yes|y', rebase_action, re.I):
maruel@chromium.org37e89872010-09-07 16:11:33 +0000530 self._Run(['reset', '--hard', 'HEAD'], options)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000531 # Should this be recursive?
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000532 rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000533 break
534 elif re.match(r'quit|q', rebase_action, re.I):
535 raise gclient_utils.Error("Please merge or rebase manually\n"
536 "cd %s && git " % self.checkout_path
537 + "%s" % ' '.join(rebase_cmd))
538 elif re.match(r'show|s', rebase_action, re.I):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000539 print('\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000540 continue
541 else:
542 gclient_utils.Error("Input not recognized")
543 continue
544 elif re.search(r'^CONFLICT', e.stdout, re.M):
545 raise gclient_utils.Error("Conflict while rebasing this branch.\n"
546 "Fix the conflict and run gclient again.\n"
547 "See 'man git-rebase' for details.\n")
548 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000549 print(e.stdout.strip())
550 print('Rebase produced error output:\n%s' % e.stderr.strip())
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000551 raise gclient_utils.Error("Unrecognized error, please merge or rebase "
552 "manually.\ncd %s && git " %
553 self.checkout_path
554 + "%s" % ' '.join(rebase_cmd))
555
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000556 print(rebase_output.strip())
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000557 if not options.verbose:
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000558 # Make the output a little prettier. It's nice to have some
559 # whitespace between projects when syncing.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000560 print('')
nasser@codeaurora.orgd90ba3f2010-02-23 14:42:57 +0000561
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000562 @staticmethod
563 def _CheckMinVersion(min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000564 (ok, current_version) = scm.GIT.AssertVersion(min_version)
565 if not ok:
566 raise gclient_utils.Error('git version %s < minimum required %s' %
567 (current_version, min_version))
msb@chromium.org923a0372009-12-11 20:42:43 +0000568
msb@chromium.org786fb682010-06-02 15:16:23 +0000569 def _IsRebasing(self):
570 # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
571 # have a plumbing command to determine whether a rebase is in progress, so
572 # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
573 g = os.path.join(self.checkout_path, '.git')
574 return (
575 os.path.isdir(os.path.join(g, "rebase-merge")) or
576 os.path.isdir(os.path.join(g, "rebase-apply")))
577
578 def _CheckClean(self, rev_str):
579 # Make sure the tree is clean; see git-rebase.sh for reference
580 try:
581 scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000582 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000583 except gclient_utils.CheckCallError:
584 raise gclient_utils.Error('\n____ %s%s\n'
585 '\tYou have unstaged changes.\n'
586 '\tPlease commit, stash, or reset.\n'
587 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000588 try:
589 scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000590 '--ignore-submodules', 'HEAD', '--'],
591 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000592 except gclient_utils.CheckCallError:
593 raise gclient_utils.Error('\n____ %s%s\n'
594 '\tYour index contains uncommitted changes\n'
595 '\tPlease commit, stash, or reset.\n'
596 % (self.relpath, rev_str))
msb@chromium.org786fb682010-06-02 15:16:23 +0000597
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000598 def _CheckDetachedHead(self, rev_str, options):
msb@chromium.org786fb682010-06-02 15:16:23 +0000599 # HEAD is detached. Make sure it is safe to move away from (i.e., it is
600 # reference by a commit). If not, error out -- most likely a rebase is
601 # in progress, try to detect so we can give a better error.
602 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000603 scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
604 cwd=self.checkout_path)
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000605 except gclient_utils.CheckCallError:
msb@chromium.org786fb682010-06-02 15:16:23 +0000606 # Commit is not contained by any rev. See if the user is rebasing:
607 if self._IsRebasing():
608 # Punt to the user
609 raise gclient_utils.Error('\n____ %s%s\n'
610 '\tAlready in a conflict, i.e. (no branch).\n'
611 '\tFix the conflict and run gclient again.\n'
612 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
613 '\tSee man git-rebase for details.\n'
614 % (self.relpath, rev_str))
615 # Let's just save off the commit so we can proceed.
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000616 name = ('saved-by-gclient-' +
617 self._Capture(['rev-parse', '--short', 'HEAD']))
618 self._Capture(['branch', name])
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000619 print('\n_____ found an unreferenced commit and saved it as \'%s\'' %
maruel@chromium.orgf5d37bf2010-09-02 00:50:34 +0000620 name)
msb@chromium.org786fb682010-06-02 15:16:23 +0000621
msb@chromium.org5bde4852009-12-14 16:47:12 +0000622 def _GetCurrentBranch(self):
msb@chromium.org786fb682010-06-02 15:16:23 +0000623 # Returns name of current branch or None for detached HEAD
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000624 branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
msb@chromium.org786fb682010-06-02 15:16:23 +0000625 if branch == 'HEAD':
msb@chromium.org5bde4852009-12-14 16:47:12 +0000626 return None
627 return branch
628
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000629 def _Capture(self, args):
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000630 return gclient_utils.CheckCall(
631 ['git'] + args, cwd=self.checkout_path, print_error=False)[0].strip()
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000632
maruel@chromium.org37e89872010-09-07 16:11:33 +0000633 def _Run(self, args, options, **kwargs):
maruel@chromium.org6cafa132010-09-07 14:17:26 +0000634 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org37e89872010-09-07 16:11:33 +0000635 gclient_utils.CheckCallAndFilterAndHeader(['git'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000636 always=options.verbose, **kwargs)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000637
638
maruel@chromium.org55e724e2010-03-11 19:36:49 +0000639class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000640 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000641
642 def cleanup(self, options, args, file_list):
643 """Cleanup working copy."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000644 self._Run(['cleanup'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000645
646 def diff(self, options, args, file_list):
647 # NOTE: This function does not currently modify file_list.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000648 if not os.path.isdir(self.checkout_path):
649 raise gclient_utils.Error('Directory %s is not present.' %
650 self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000651 self._Run(['diff'] + args, options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000652
653 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000654 """Export a clean directory tree into the given path."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000655 assert len(args) == 1
656 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
657 try:
658 os.makedirs(export_path)
659 except OSError:
660 pass
661 assert os.path.exists(export_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000662 self._Run(['export', '--force', '.', export_path], options)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000663
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000664 def pack(self, options, args, file_list):
665 """Generates a patch file which can be applied to the root of the
666 repository."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000667 if not os.path.isdir(self.checkout_path):
668 raise gclient_utils.Error('Directory %s is not present.' %
669 self.checkout_path)
670 gclient_utils.CheckCallAndFilter(
671 ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
672 cwd=self.checkout_path,
673 print_stdout=False,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000674 filter_fn=DiffFilterer(self.relpath).Filter)
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000675
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000676 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000677 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000678
679 All updated files will be appended to file_list.
680
681 Raises:
682 Error: if can't get URL for relative path.
683 """
684 # Only update if git is not controlling the directory.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000685 git_path = os.path.join(self.checkout_path, '.git')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000686 if os.path.exists(git_path):
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000687 print('________ found .git directory; skipping %s' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000688 return
689
690 if args:
691 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
692
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000693 # revision is the revision to match. It is None if no revision is specified,
694 # i.e. the 'deps ain't pinned'.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000695 url, revision = gclient_utils.SplitUrlRevision(self.url)
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000696 # Keep the original unpinned url for reference in case the repo is switched.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000697 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000698 if options.revision:
699 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000700 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000701 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000702 forced_revision = True
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000703 # Reconstruct the url.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000704 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000705 rev_str = ' at %s' % revision
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000706 else:
707 forced_revision = False
708 rev_str = ''
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000709
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000710 if not os.path.exists(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000711 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000712 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000713 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000714 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000715 return
716
717 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000718 try:
719 from_info = scm.SVN.CaptureInfo(os.path.join(self.checkout_path, '.'))
720 except gclient_utils.Error:
721 raise gclient_utils.Error(
722 ('Can\'t update/checkout %s if an unversioned directory is present. '
723 'Delete the directory and try again.') % self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000724
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000725 # Look for locked directories.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000726 dir_info = scm.SVN.CaptureStatus(os.path.join(self.checkout_path, '.'))
727 if [True for d in dir_info
728 if d[0][2] == 'L' and d[1] == self.checkout_path]:
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000729 # The current directory is locked, clean it up.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000730 self._Run(['cleanup'], options)
maruel@chromium.orge407c9a2010-08-09 19:11:37 +0000731
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000732 # Retrieve the current HEAD version because svn is slow at null updates.
733 if options.manually_grab_svn_rev and not revision:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000734 from_info_live = scm.SVN.CaptureInfo(from_info['URL'])
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000735 revision = str(from_info_live['Revision'])
736 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000737
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000738 if from_info['URL'] != base_url:
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000739 # The repository url changed, need to switch.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000740 try:
741 to_info = scm.SVN.CaptureInfo(url)
742 except gclient_utils.Error:
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000743 # The url is invalid or the server is not accessible, it's safer to bail
744 # out right now.
745 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000746 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
747 and (from_info['UUID'] == to_info['UUID']))
748 if can_switch:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000749 print('\n_____ relocating %s to a new checkout' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000750 # We have different roots, so check if we can switch --relocate.
751 # Subversion only permits this if the repository UUIDs match.
752 # Perform the switch --relocate, then rewrite the from_url
753 # to reflect where we "are now." (This is the same way that
754 # Subversion itself handles the metadata when switch --relocate
755 # is used.) This makes the checks below for whether we
756 # can update to a revision or have to switch to a different
757 # branch work as expected.
758 # TODO(maruel): TEST ME !
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000759 command = ['switch', '--relocate',
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000760 from_info['Repository Root'],
761 to_info['Repository Root'],
762 self.relpath]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000763 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000764 from_info['URL'] = from_info['URL'].replace(
765 from_info['Repository Root'],
766 to_info['Repository Root'])
767 else:
maruel@chromium.org3294f522010-08-18 19:54:57 +0000768 if not options.force and not options.reset:
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000769 # Look for local modifications but ignore unversioned files.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000770 for status in scm.SVN.CaptureStatus(self.checkout_path):
maruel@chromium.org86f0f952010-08-10 17:17:19 +0000771 if status[0] != '?':
772 raise gclient_utils.Error(
773 ('Can\'t switch the checkout to %s; UUID don\'t match and '
774 'there is local changes in %s. Delete the directory and '
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000775 'try again.') % (url, self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000776 # Ok delete it.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000777 print('\n_____ switching %s to a new checkout' % self.relpath)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000778 gclient_utils.RemoveDirectory(self.checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000779 # We need to checkout.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000780 command = ['checkout', url, self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000781 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000782 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000783 return
784
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000785 # If the provided url has a revision number that matches the revision
786 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000787 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000788 if options.verbose or not forced_revision:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000789 print('\n_____ %s%s' % (self.relpath, rev_str))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000790 return
791
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000792 command = ['update', self.checkout_path]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000793 command = self._AddAdditionalUpdateFlags(command, options, revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000794 self._RunAndGetFileList(command, options, file_list, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000795
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000796 def updatesingle(self, options, args, file_list):
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000797 filename = args.pop()
tony@chromium.org57564662010-04-14 02:35:12 +0000798 if scm.SVN.AssertVersion("1.5")[0]:
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000799 if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
tony@chromium.org57564662010-04-14 02:35:12 +0000800 # Create an empty checkout and then update the one file we want. Future
801 # operations will only apply to the one file we checked out.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000802 command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000803 self._Run(command, options, cwd=self._root_dir)
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000804 if os.path.exists(os.path.join(self.checkout_path, filename)):
805 os.remove(os.path.join(self.checkout_path, filename))
tony@chromium.org57564662010-04-14 02:35:12 +0000806 command = ["update", filename]
maruel@chromium.org669600d2010-09-01 19:06:31 +0000807 self._RunAndGetFileList(command, options, file_list)
tony@chromium.org57564662010-04-14 02:35:12 +0000808 # After the initial checkout, we can use update as if it were any other
809 # dep.
810 self.update(options, args, file_list)
811 else:
812 # If the installed version of SVN doesn't support --depth, fallback to
813 # just exporting the file. This has the downside that revision
814 # information is not stored next to the file, so we will have to
815 # re-export the file every time we sync.
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000816 if not os.path.exists(self.checkout_path):
817 os.makedirs(self.checkout_path)
tony@chromium.org57564662010-04-14 02:35:12 +0000818 command = ["export", os.path.join(self.url, filename),
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000819 os.path.join(self.checkout_path, filename)]
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000820 command = self._AddAdditionalUpdateFlags(command, options,
821 options.revision)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000822 self._Run(command, options, cwd=self._root_dir)
tony@chromium.org4b5b1772010-04-08 01:52:56 +0000823
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000824 def revert(self, options, args, file_list):
825 """Reverts local modifications. Subversion specific.
826
827 All reverted files will be appended to file_list, even if Subversion
828 doesn't know about them.
829 """
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000830 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000831 # svn revert won't work if the directory doesn't exist. It needs to
832 # checkout instead.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000833 print('\n_____ %s is missing, synching instead' % self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000834 # Don't reuse the args.
835 return self.update(options, [], file_list)
836
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000837 for file_status in scm.SVN.CaptureStatus(self.checkout_path):
838 file_path = os.path.join(self.checkout_path, file_status[1])
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000839 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000840 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000841 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000842 continue
843
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000844 if logging.getLogger().isEnabledFor(logging.INFO):
845 logging.info('%s%s' % (file[0], file[1]))
846 else:
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000847 print(file_path)
maruel@chromium.org945405e2010-08-18 17:01:49 +0000848
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000849 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000850 logging.error('No idea what is the status of %s.\n'
851 'You just found a bug in gclient, please ping '
852 'maruel@chromium.org ASAP!' % file_path)
853 # svn revert is really stupid. It fails on inconsistent line-endings,
854 # on switched directories, etc. So take no chance and delete everything!
855 try:
856 if not os.path.exists(file_path):
857 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000858 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000859 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000860 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000861 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000862 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000863 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000864 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000865 logging.error('no idea what is %s.\nYou just found a bug in gclient'
866 ', please ping maruel@chromium.org ASAP!' % file_path)
867 except EnvironmentError:
868 logging.error('Failed to remove %s.' % file_path)
869
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000870 try:
871 # svn revert is so broken we don't even use it. Using
872 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org669600d2010-09-01 19:06:31 +0000873 self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
874 file_list)
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000875 except OSError, e:
876 # Maybe the directory disapeared meanwhile. We don't want it to throw an
877 # exception.
878 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000879
msb@chromium.org0f282062009-11-06 20:14:02 +0000880 def revinfo(self, options, args, file_list):
881 """Display revision"""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000882 try:
883 return scm.SVN.CaptureRevision(self.checkout_path)
884 except gclient_utils.Error:
885 return None
msb@chromium.org0f282062009-11-06 20:14:02 +0000886
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000887 def runhooks(self, options, args, file_list):
888 self.status(options, args, file_list)
889
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000890 def status(self, options, args, file_list):
891 """Display status information."""
maruel@chromium.org669600d2010-09-01 19:06:31 +0000892 command = ['status'] + args
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000893 if not os.path.isdir(self.checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000894 # svn status won't work if the directory doesn't exist.
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000895 print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
896 'The directory does not exist.') %
897 (' '.join(command), self.checkout_path))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000898 # There's no file list to retrieve.
899 else:
maruel@chromium.org669600d2010-09-01 19:06:31 +0000900 self._RunAndGetFileList(command, options, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000901
902 def FullUrlForRelativeUrl(self, url):
903 # Find the forth '/' and strip from there. A bit hackish.
904 return '/'.join(self.url.split('/')[:4]) + url
tony@chromium.org99828122010-06-04 01:41:02 +0000905
maruel@chromium.org669600d2010-09-01 19:06:31 +0000906 def _Run(self, args, options, **kwargs):
907 """Runs a commands that goes to stdout."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000908 kwargs.setdefault('cwd', self.checkout_path)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000909 gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000910 always=options.verbose, **kwargs)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000911
912 def _RunAndGetFileList(self, args, options, file_list, cwd=None):
913 """Runs a commands that goes to stdout and grabs the file listed."""
maruel@chromium.org8469bf92010-09-03 19:03:15 +0000914 cwd = cwd or self.checkout_path
maruel@chromium.org669600d2010-09-01 19:06:31 +0000915 scm.SVN.RunAndGetFileList(options.verbose, args, cwd=cwd,
maruel@chromium.org77e4eca2010-09-21 13:23:07 +0000916 file_list=file_list)
maruel@chromium.org669600d2010-09-01 19:06:31 +0000917
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000918 @staticmethod
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000919 def _AddAdditionalUpdateFlags(command, options, revision):
tony@chromium.org99828122010-06-04 01:41:02 +0000920 """Add additional flags to command depending on what options are set.
921 command should be a list of strings that represents an svn command.
922
923 This method returns a new list to be used as a command."""
924 new_command = command[:]
925 if revision:
926 new_command.extend(['--revision', str(revision).strip()])
927 # --force was added to 'svn update' in svn 1.5.
maruel@chromium.org8e0e9262010-08-17 19:20:27 +0000928 if ((options.force or options.manually_grab_svn_rev) and
929 scm.SVN.AssertVersion("1.5")[0]):
tony@chromium.org99828122010-06-04 01:41:02 +0000930 new_command.append('--force')
931 return new_command