blob: 23a5108570e1376ae1fb995cf0b2ddf701826244 [file] [log] [blame]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00001# Copyright (c) 2009 The Chromium Authors. All rights reserved.
2# 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
11import subprocess
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000012
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000013import scm
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000014import gclient_utils
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000015
16
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000017class DiffFilterer(object):
18 """Simple class which tracks which file is being diffed and
19 replaces instances of its file name in the original and
msb@chromium.orgd6504212010-01-13 17:34:31 +000020 working copy lines of the svn/git diff output."""
maruel@chromium.orgee4071d2009-12-22 22:25:37 +000021 index_string = "Index: "
22 original_prefix = "--- "
23 working_prefix = "+++ "
24
25 def __init__(self, relpath):
26 # Note that we always use '/' as the path separator to be
27 # consistent with svn's cygwin-style output on Windows
28 self._relpath = relpath.replace("\\", "/")
29 self._current_file = ""
30 self._replacement_file = ""
31
32 def SetCurrentFile(self, file):
33 self._current_file = file
34 # Note that we always use '/' as the path separator to be
35 # consistent with svn's cygwin-style output on Windows
36 self._replacement_file = posixpath.join(self._relpath, file)
37
38 def ReplaceAndPrint(self, line):
39 print(line.replace(self._current_file, self._replacement_file))
40
41 def Filter(self, line):
42 if (line.startswith(self.index_string)):
43 self.SetCurrentFile(line[len(self.index_string):])
44 self.ReplaceAndPrint(line)
45 else:
46 if (line.startswith(self.original_prefix) or
47 line.startswith(self.working_prefix)):
48 self.ReplaceAndPrint(line)
49 else:
50 print line
51
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
57def CreateSCM(url=None, root_dir=None, relpath=None, scm_name='svn'):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000058 scm_map = {
59 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000060 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000061 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000062
msb@chromium.org1b8779a2009-11-19 18:11:39 +000063 orig_url = url
64
65 if url:
66 url, _ = gclient_utils.SplitUrlRevision(url)
67 if url.startswith('git:') or url.startswith('ssh:') or url.endswith('.git'):
68 scm_name = 'git'
msb@chromium.orge28e4982009-09-25 20:51:45 +000069
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000070 if not scm_name in scm_map:
71 raise gclient_utils.Error('Unsupported scm %s' % scm_name)
msb@chromium.org1b8779a2009-11-19 18:11:39 +000072 return scm_map[scm_name](orig_url, root_dir, relpath, scm_name)
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000073
74
75# SCMWrapper base class
76
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000077class SCMWrapper(object):
78 """Add necessary glue between all the supported SCM.
79
msb@chromium.orgd6504212010-01-13 17:34:31 +000080 This is the abstraction layer to bind to different SCM.
81 """
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000082 def __init__(self, url=None, root_dir=None, relpath=None,
83 scm_name='svn'):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000084 self.scm_name = scm_name
85 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000086 self._root_dir = root_dir
87 if self._root_dir:
88 self._root_dir = self._root_dir.replace('/', os.sep)
89 self.relpath = relpath
90 if self.relpath:
91 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000092 if self.relpath and self._root_dir:
93 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000094
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000095 def RunCommand(self, command, options, args, file_list=None):
96 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +000097 if file_list is None:
98 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000099
msb@chromium.org0f282062009-11-06 20:14:02 +0000100 commands = ['cleanup', 'export', 'update', 'revert', 'revinfo',
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000101 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000102
103 if not command in commands:
104 raise gclient_utils.Error('Unknown command %s' % command)
105
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000106 if not command in dir(self):
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000107 raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000108 command, self.scm_name))
109
110 return getattr(self, command)(options, args, file_list)
111
112
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000113class GitWrapper(SCMWrapper, scm.GIT):
msb@chromium.orge28e4982009-09-25 20:51:45 +0000114 """Wrapper for Git"""
115
116 def cleanup(self, options, args, file_list):
117 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000118 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000119 self._Run(['prune'], redirect_stdout=False)
120 self._Run(['fsck'], redirect_stdout=False)
121 self._Run(['gc'], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000122
123 def diff(self, options, args, file_list):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000124 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000125 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
126 self._Run(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000127
128 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000129 """Export a clean directory tree into the given path.
130
131 Exports into the specified directory, creating the path if it does
132 already exist.
133 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000134 __pychecker__ = 'unusednames=file_list,options'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000135 assert len(args) == 1
136 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
137 if not os.path.exists(export_path):
138 os.makedirs(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000139 self._Run(['checkout-index', '-a', '--prefix=%s/' % export_path],
140 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000141
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000142 def pack(self, options, args, file_list):
143 """Generates a patch file which can be applied to the root of the
msb@chromium.orgd6504212010-01-13 17:34:31 +0000144 repository.
145
146 The patch file is generated from a diff of the merge base of HEAD and
147 its upstream branch.
148 """
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000149 __pychecker__ = 'unusednames=file_list,options'
150 path = os.path.join(self._root_dir, self.relpath)
151 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
152 command = ['diff', merge_base]
153 filterer = DiffFilterer(self.relpath)
154 self.RunAndFilterOutput(command, path, False, False, filterer.Filter)
155
msb@chromium.orge28e4982009-09-25 20:51:45 +0000156 def update(self, options, args, file_list):
157 """Runs git to update or transparently checkout the working copy.
158
159 All updated files will be appended to file_list.
160
161 Raises:
162 Error: if can't get URL for relative path.
163 """
164
165 if args:
166 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
167
msb@chromium.org83376f22009-12-11 22:25:31 +0000168 self._CheckMinVersion("1.6")
msb@chromium.org923a0372009-12-11 20:42:43 +0000169
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000170 url, revision = gclient_utils.SplitUrlRevision(self.url)
171 rev_str = ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000172 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000173 # Override the revision number.
174 revision = str(options.revision)
175 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000176 rev_str = ' at %s' % revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000177
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000178 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000179 print("\n_____ %s%s" % (self.relpath, rev_str))
180
msb@chromium.orge28e4982009-09-25 20:51:45 +0000181 if not os.path.exists(self.checkout_path):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000182 self._Run(['clone', url, self.checkout_path],
183 cwd=self._root_dir, redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000184 if revision:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000185 self._Run(['reset', '--hard', revision], redirect_stdout=False)
186 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000187 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
188 return
189
msb@chromium.orge28e4982009-09-25 20:51:45 +0000190 new_base = 'origin'
191 if revision:
192 new_base = revision
msb@chromium.org5bde4852009-12-14 16:47:12 +0000193 cur_branch = self._GetCurrentBranch()
194
195 # Check if we are in a rebase conflict
196 if cur_branch is None:
197 raise gclient_utils.Error('\n____ %s%s\n'
198 '\tAlready in a conflict, i.e. (no branch).\n'
199 '\tFix the conflict and run gclient again.\n'
200 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
201 '\tSee man git-rebase for details.\n'
202 % (self.relpath, rev_str))
203
msb@chromium.orgf2370632009-11-25 00:22:11 +0000204 merge_base = self._Run(['merge-base', 'HEAD', new_base])
205 self._Run(['remote', 'update'], redirect_stdout=False)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000206 files = self._Run(['diff', new_base, '--name-only']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000207 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orgf2370632009-11-25 00:22:11 +0000208 self._Run(['rebase', '-v', '--onto', new_base, merge_base, cur_branch],
msb@chromium.org5bde4852009-12-14 16:47:12 +0000209 redirect_stdout=False, checkrc=False)
210
211 # If the rebase generated a conflict, abort and ask user to fix
212 if self._GetCurrentBranch() is None:
213 raise gclient_utils.Error('\n____ %s%s\n'
214 '\nConflict while rebasing this branch.\n'
215 'Fix the conflict and run gclient again.\n'
216 'See man git-rebase for details.\n'
217 % (self.relpath, rev_str))
218
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000219 print "Checked out revision %s." % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000220
221 def revert(self, options, args, file_list):
222 """Reverts local modifications.
223
224 All reverted files will be appended to file_list.
225 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000226 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000227 path = os.path.join(self._root_dir, self.relpath)
228 if not os.path.isdir(path):
229 # revert won't work if the directory doesn't exist. It needs to
230 # checkout instead.
231 print("\n_____ %s is missing, synching instead" % self.relpath)
232 # Don't reuse the args.
233 return self.update(options, [], file_list)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000234 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
235 files = self._Run(['diff', merge_base, '--name-only']).split()
236 self._Run(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000237 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
238
msb@chromium.org0f282062009-11-06 20:14:02 +0000239 def revinfo(self, options, args, file_list):
240 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000241 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000242 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000243
msb@chromium.orge28e4982009-09-25 20:51:45 +0000244 def runhooks(self, options, args, file_list):
245 self.status(options, args, file_list)
246
247 def status(self, options, args, file_list):
248 """Display status information."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000249 __pychecker__ = 'unusednames=args,options'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000250 if not os.path.isdir(self.checkout_path):
251 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000252 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000253 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000254 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
255 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
256 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000257 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
258
msb@chromium.orge6f78352010-01-13 17:05:33 +0000259 def FullUrlForRelativeUrl(self, url):
260 # Strip from last '/'
261 # Equivalent to unix basename
262 base_url = self.url
263 return base_url[:base_url.rfind('/')] + url
264
msb@chromium.org923a0372009-12-11 20:42:43 +0000265 def _CheckMinVersion(self, min_version):
msb@chromium.org83376f22009-12-11 22:25:31 +0000266 def only_int(val):
267 if val.isdigit():
268 return int(val)
269 else:
270 return 0
msb@chromium.orgba9b2392009-12-11 23:30:13 +0000271 version = self._Run(['--version'], cwd='.').split()[-1]
msb@chromium.org83376f22009-12-11 22:25:31 +0000272 version_list = map(only_int, version.split('.'))
msb@chromium.org923a0372009-12-11 20:42:43 +0000273 min_version_list = map(int, min_version.split('.'))
274 for min_ver in min_version_list:
275 ver = version_list.pop(0)
276 if min_ver > ver:
277 raise gclient_utils.Error('git version %s < minimum required %s' %
278 (version, min_version))
279 elif min_ver < ver:
280 return
281
msb@chromium.org5bde4852009-12-14 16:47:12 +0000282 def _GetCurrentBranch(self):
283 # Returns name of current branch
284 # Returns None if inside a (no branch)
285 tokens = self._Run(['branch']).split()
286 branch = tokens[tokens.index('*') + 1]
287 if branch == '(no':
288 return None
289 return branch
290
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000291 def _Run(self, args, cwd=None, checkrc=True, redirect_stdout=True):
292 # TODO(maruel): Merge with Capture?
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000293 if cwd is None:
294 cwd = self.checkout_path
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000295 stdout=None
296 if redirect_stdout:
297 stdout=subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000298 if cwd == None:
299 cwd = self.checkout_path
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000300 cmd = [self.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000301 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000302 logging.debug(cmd)
303 try:
304 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
305 output = sp.communicate()[0]
306 except OSError:
307 raise gclient_utils.Error("git command '%s' failed to run." %
308 ' '.join(cmd) + "\nCheck that you have git installed.")
msb@chromium.orge28e4982009-09-25 20:51:45 +0000309 if checkrc and sp.returncode:
310 raise gclient_utils.Error('git command %s returned %d' %
311 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000312 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000313 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000314
315
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000316class SVNWrapper(SCMWrapper, scm.SVN):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000317 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000318
319 def cleanup(self, options, args, file_list):
320 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000321 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000322 command = ['cleanup']
323 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000324 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000325
326 def diff(self, options, args, file_list):
327 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000328 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000329 command = ['diff']
330 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000331 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000332
333 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000334 """Export a clean directory tree into the given path."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000335 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000336 assert len(args) == 1
337 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
338 try:
339 os.makedirs(export_path)
340 except OSError:
341 pass
342 assert os.path.exists(export_path)
343 command = ['export', '--force', '.']
344 command.append(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000345 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000346
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000347 def pack(self, options, args, file_list):
348 """Generates a patch file which can be applied to the root of the
349 repository."""
350 __pychecker__ = 'unusednames=file_list,options'
351 path = os.path.join(self._root_dir, self.relpath)
352 command = ['diff']
353 command.extend(args)
354
355 filterer = DiffFilterer(self.relpath)
356 self.RunAndFilterOutput(command, path, False, False, filterer.Filter)
357
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000358 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000359 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000360
361 All updated files will be appended to file_list.
362
363 Raises:
364 Error: if can't get URL for relative path.
365 """
366 # Only update if git is not controlling the directory.
367 checkout_path = os.path.join(self._root_dir, self.relpath)
368 git_path = os.path.join(self._root_dir, self.relpath, '.git')
369 if os.path.exists(git_path):
370 print("________ found .git directory; skipping %s" % self.relpath)
371 return
372
373 if args:
374 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
375
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000376 url, revision = gclient_utils.SplitUrlRevision(self.url)
377 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000378 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000379 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000380 if options.revision:
381 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000382 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000383 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000384 forced_revision = True
385 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000386 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000387
388 if not os.path.exists(checkout_path):
389 # We need to checkout.
390 command = ['checkout', url, checkout_path]
391 if revision:
392 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000393 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000394 return
395
396 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000397 from_info = self.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000398 if not from_info:
399 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
400 "directory is present. Delete the directory "
401 "and try again." %
402 checkout_path)
403
maruel@chromium.org7753d242009-10-07 17:40:24 +0000404 if options.manually_grab_svn_rev:
405 # Retrieve the current HEAD version because svn is slow at null updates.
406 if not revision:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000407 from_info_live = self.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000408 revision = str(from_info_live['Revision'])
409 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000410
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000411 if from_info['URL'] != base_url:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000412 to_info = self.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000413 if not to_info.get('Repository Root') or not to_info.get('UUID'):
414 # The url is invalid or the server is not accessible, it's safer to bail
415 # out right now.
416 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000417 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
418 and (from_info['UUID'] == to_info['UUID']))
419 if can_switch:
420 print("\n_____ relocating %s to a new checkout" % self.relpath)
421 # We have different roots, so check if we can switch --relocate.
422 # Subversion only permits this if the repository UUIDs match.
423 # Perform the switch --relocate, then rewrite the from_url
424 # to reflect where we "are now." (This is the same way that
425 # Subversion itself handles the metadata when switch --relocate
426 # is used.) This makes the checks below for whether we
427 # can update to a revision or have to switch to a different
428 # branch work as expected.
429 # TODO(maruel): TEST ME !
430 command = ["switch", "--relocate",
431 from_info['Repository Root'],
432 to_info['Repository Root'],
433 self.relpath]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000434 self.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000435 from_info['URL'] = from_info['URL'].replace(
436 from_info['Repository Root'],
437 to_info['Repository Root'])
438 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000439 if self.CaptureStatus(checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000440 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
441 "don't match and there is local changes "
442 "in %s. Delete the directory and "
443 "try again." % (url, checkout_path))
444 # Ok delete it.
445 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000446 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000447 # We need to checkout.
448 command = ['checkout', url, checkout_path]
449 if revision:
450 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000451 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000452 return
453
454
455 # If the provided url has a revision number that matches the revision
456 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000457 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000458 if options.verbose or not forced_revision:
459 print("\n_____ %s%s" % (self.relpath, rev_str))
460 return
461
462 command = ["update", checkout_path]
463 if revision:
464 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000465 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000466
467 def revert(self, options, args, file_list):
468 """Reverts local modifications. Subversion specific.
469
470 All reverted files will be appended to file_list, even if Subversion
471 doesn't know about them.
472 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000473 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000474 path = os.path.join(self._root_dir, self.relpath)
475 if not os.path.isdir(path):
476 # svn revert won't work if the directory doesn't exist. It needs to
477 # checkout instead.
478 print("\n_____ %s is missing, synching instead" % self.relpath)
479 # Don't reuse the args.
480 return self.update(options, [], file_list)
481
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000482 for file_status in self.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000483 file_path = os.path.join(path, file_status[1])
484 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000485 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000486 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000487 continue
488
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000489 if logging.getLogger().isEnabledFor(logging.INFO):
490 logging.info('%s%s' % (file[0], file[1]))
491 else:
492 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000493 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000494 logging.error('No idea what is the status of %s.\n'
495 'You just found a bug in gclient, please ping '
496 'maruel@chromium.org ASAP!' % file_path)
497 # svn revert is really stupid. It fails on inconsistent line-endings,
498 # on switched directories, etc. So take no chance and delete everything!
499 try:
500 if not os.path.exists(file_path):
501 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000502 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000503 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000504 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000505 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000506 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000507 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000508 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000509 logging.error('no idea what is %s.\nYou just found a bug in gclient'
510 ', please ping maruel@chromium.org ASAP!' % file_path)
511 except EnvironmentError:
512 logging.error('Failed to remove %s.' % file_path)
513
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000514 try:
515 # svn revert is so broken we don't even use it. Using
516 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000517 self.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000518 file_list)
519 except OSError, e:
520 # Maybe the directory disapeared meanwhile. We don't want it to throw an
521 # exception.
522 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000523
msb@chromium.org0f282062009-11-06 20:14:02 +0000524 def revinfo(self, options, args, file_list):
525 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000526 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000527 return self.CaptureHeadRevision(self.url)
msb@chromium.org0f282062009-11-06 20:14:02 +0000528
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000529 def runhooks(self, options, args, file_list):
530 self.status(options, args, file_list)
531
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000532 def status(self, options, args, file_list):
533 """Display status information."""
534 path = os.path.join(self._root_dir, self.relpath)
535 command = ['status']
536 command.extend(args)
537 if not os.path.isdir(path):
538 # svn status won't work if the directory doesn't exist.
539 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
540 "does not exist."
541 % (' '.join(command), path))
542 # There's no file list to retrieve.
543 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000544 self.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000545
546 def FullUrlForRelativeUrl(self, url):
547 # Find the forth '/' and strip from there. A bit hackish.
548 return '/'.join(self.url.split('/')[:4]) + url