blob: 010c45d183709586cdd42e2eec31aa585e050ca0 [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.orge4af1ab2010-01-13 21:26:09 +0000190 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
191 raise gclient_utils.Error('\n____ %s%s\n'
192 '\tPath is not a git repo. No .git dir.\n'
193 '\tTo resolve:\n'
194 '\t\trm -rf %s\n'
195 '\tAnd run gclient sync again\n'
196 % (self.relpath, rev_str, self.relpath))
197
msb@chromium.orge28e4982009-09-25 20:51:45 +0000198 new_base = 'origin'
199 if revision:
200 new_base = revision
msb@chromium.org5bde4852009-12-14 16:47:12 +0000201 cur_branch = self._GetCurrentBranch()
202
203 # Check if we are in a rebase conflict
204 if cur_branch is None:
205 raise gclient_utils.Error('\n____ %s%s\n'
206 '\tAlready in a conflict, i.e. (no branch).\n'
207 '\tFix the conflict and run gclient again.\n'
208 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
209 '\tSee man git-rebase for details.\n'
210 % (self.relpath, rev_str))
211
msb@chromium.orgf2370632009-11-25 00:22:11 +0000212 merge_base = self._Run(['merge-base', 'HEAD', new_base])
213 self._Run(['remote', 'update'], redirect_stdout=False)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000214 files = self._Run(['diff', new_base, '--name-only']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000215 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orgf2370632009-11-25 00:22:11 +0000216 self._Run(['rebase', '-v', '--onto', new_base, merge_base, cur_branch],
msb@chromium.org5bde4852009-12-14 16:47:12 +0000217 redirect_stdout=False, checkrc=False)
218
219 # If the rebase generated a conflict, abort and ask user to fix
220 if self._GetCurrentBranch() is None:
221 raise gclient_utils.Error('\n____ %s%s\n'
222 '\nConflict while rebasing this branch.\n'
223 'Fix the conflict and run gclient again.\n'
224 'See man git-rebase for details.\n'
225 % (self.relpath, rev_str))
226
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000227 print "Checked out revision %s." % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000228
229 def revert(self, options, args, file_list):
230 """Reverts local modifications.
231
232 All reverted files will be appended to file_list.
233 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000234 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000235 path = os.path.join(self._root_dir, self.relpath)
236 if not os.path.isdir(path):
237 # revert won't work if the directory doesn't exist. It needs to
238 # checkout instead.
239 print("\n_____ %s is missing, synching instead" % self.relpath)
240 # Don't reuse the args.
241 return self.update(options, [], file_list)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000242 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
243 files = self._Run(['diff', merge_base, '--name-only']).split()
244 self._Run(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000245 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
246
msb@chromium.org0f282062009-11-06 20:14:02 +0000247 def revinfo(self, options, args, file_list):
248 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000249 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000250 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000251
msb@chromium.orge28e4982009-09-25 20:51:45 +0000252 def runhooks(self, options, args, file_list):
253 self.status(options, args, file_list)
254
255 def status(self, options, args, file_list):
256 """Display status information."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000257 __pychecker__ = 'unusednames=args,options'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000258 if not os.path.isdir(self.checkout_path):
259 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000260 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000261 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000262 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
263 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
264 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000265 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
266
msb@chromium.orge6f78352010-01-13 17:05:33 +0000267 def FullUrlForRelativeUrl(self, url):
268 # Strip from last '/'
269 # Equivalent to unix basename
270 base_url = self.url
271 return base_url[:base_url.rfind('/')] + url
272
msb@chromium.org923a0372009-12-11 20:42:43 +0000273 def _CheckMinVersion(self, min_version):
msb@chromium.org83376f22009-12-11 22:25:31 +0000274 def only_int(val):
275 if val.isdigit():
276 return int(val)
277 else:
278 return 0
msb@chromium.orgba9b2392009-12-11 23:30:13 +0000279 version = self._Run(['--version'], cwd='.').split()[-1]
msb@chromium.org83376f22009-12-11 22:25:31 +0000280 version_list = map(only_int, version.split('.'))
msb@chromium.org923a0372009-12-11 20:42:43 +0000281 min_version_list = map(int, min_version.split('.'))
282 for min_ver in min_version_list:
283 ver = version_list.pop(0)
284 if min_ver > ver:
285 raise gclient_utils.Error('git version %s < minimum required %s' %
286 (version, min_version))
287 elif min_ver < ver:
288 return
289
msb@chromium.org5bde4852009-12-14 16:47:12 +0000290 def _GetCurrentBranch(self):
291 # Returns name of current branch
292 # Returns None if inside a (no branch)
293 tokens = self._Run(['branch']).split()
294 branch = tokens[tokens.index('*') + 1]
295 if branch == '(no':
296 return None
297 return branch
298
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000299 def _Run(self, args, cwd=None, checkrc=True, redirect_stdout=True):
300 # TODO(maruel): Merge with Capture?
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000301 if cwd is None:
302 cwd = self.checkout_path
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000303 stdout=None
304 if redirect_stdout:
305 stdout=subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000306 if cwd == None:
307 cwd = self.checkout_path
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000308 cmd = [self.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000309 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000310 logging.debug(cmd)
311 try:
312 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
313 output = sp.communicate()[0]
314 except OSError:
315 raise gclient_utils.Error("git command '%s' failed to run." %
316 ' '.join(cmd) + "\nCheck that you have git installed.")
msb@chromium.orge28e4982009-09-25 20:51:45 +0000317 if checkrc and sp.returncode:
318 raise gclient_utils.Error('git command %s returned %d' %
319 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000320 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000321 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000322
323
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000324class SVNWrapper(SCMWrapper, scm.SVN):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000325 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000326
327 def cleanup(self, options, args, file_list):
328 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000329 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000330 command = ['cleanup']
331 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000332 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000333
334 def diff(self, options, args, file_list):
335 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000336 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000337 command = ['diff']
338 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000339 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000340
341 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000342 """Export a clean directory tree into the given path."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000343 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000344 assert len(args) == 1
345 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
346 try:
347 os.makedirs(export_path)
348 except OSError:
349 pass
350 assert os.path.exists(export_path)
351 command = ['export', '--force', '.']
352 command.append(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000353 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000354
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000355 def pack(self, options, args, file_list):
356 """Generates a patch file which can be applied to the root of the
357 repository."""
358 __pychecker__ = 'unusednames=file_list,options'
359 path = os.path.join(self._root_dir, self.relpath)
360 command = ['diff']
361 command.extend(args)
362
363 filterer = DiffFilterer(self.relpath)
364 self.RunAndFilterOutput(command, path, False, False, filterer.Filter)
365
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000366 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000367 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000368
369 All updated files will be appended to file_list.
370
371 Raises:
372 Error: if can't get URL for relative path.
373 """
374 # Only update if git is not controlling the directory.
375 checkout_path = os.path.join(self._root_dir, self.relpath)
376 git_path = os.path.join(self._root_dir, self.relpath, '.git')
377 if os.path.exists(git_path):
378 print("________ found .git directory; skipping %s" % self.relpath)
379 return
380
381 if args:
382 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
383
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000384 url, revision = gclient_utils.SplitUrlRevision(self.url)
385 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000386 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000387 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000388 if options.revision:
389 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000390 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000391 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000392 forced_revision = True
393 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000394 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000395
396 if not os.path.exists(checkout_path):
397 # We need to checkout.
398 command = ['checkout', url, checkout_path]
399 if revision:
400 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000401 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000402 return
403
404 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000405 from_info = self.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000406 if not from_info:
407 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
408 "directory is present. Delete the directory "
409 "and try again." %
410 checkout_path)
411
maruel@chromium.org7753d242009-10-07 17:40:24 +0000412 if options.manually_grab_svn_rev:
413 # Retrieve the current HEAD version because svn is slow at null updates.
414 if not revision:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000415 from_info_live = self.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000416 revision = str(from_info_live['Revision'])
417 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000418
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000419 if from_info['URL'] != base_url:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000420 to_info = self.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000421 if not to_info.get('Repository Root') or not to_info.get('UUID'):
422 # The url is invalid or the server is not accessible, it's safer to bail
423 # out right now.
424 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000425 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
426 and (from_info['UUID'] == to_info['UUID']))
427 if can_switch:
428 print("\n_____ relocating %s to a new checkout" % self.relpath)
429 # We have different roots, so check if we can switch --relocate.
430 # Subversion only permits this if the repository UUIDs match.
431 # Perform the switch --relocate, then rewrite the from_url
432 # to reflect where we "are now." (This is the same way that
433 # Subversion itself handles the metadata when switch --relocate
434 # is used.) This makes the checks below for whether we
435 # can update to a revision or have to switch to a different
436 # branch work as expected.
437 # TODO(maruel): TEST ME !
438 command = ["switch", "--relocate",
439 from_info['Repository Root'],
440 to_info['Repository Root'],
441 self.relpath]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000442 self.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000443 from_info['URL'] = from_info['URL'].replace(
444 from_info['Repository Root'],
445 to_info['Repository Root'])
446 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000447 if self.CaptureStatus(checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000448 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
449 "don't match and there is local changes "
450 "in %s. Delete the directory and "
451 "try again." % (url, checkout_path))
452 # Ok delete it.
453 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000454 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000455 # We need to checkout.
456 command = ['checkout', url, checkout_path]
457 if revision:
458 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000459 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000460 return
461
462
463 # If the provided url has a revision number that matches the revision
464 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000465 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000466 if options.verbose or not forced_revision:
467 print("\n_____ %s%s" % (self.relpath, rev_str))
468 return
469
470 command = ["update", checkout_path]
471 if revision:
472 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000473 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000474
475 def revert(self, options, args, file_list):
476 """Reverts local modifications. Subversion specific.
477
478 All reverted files will be appended to file_list, even if Subversion
479 doesn't know about them.
480 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000481 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000482 path = os.path.join(self._root_dir, self.relpath)
483 if not os.path.isdir(path):
484 # svn revert won't work if the directory doesn't exist. It needs to
485 # checkout instead.
486 print("\n_____ %s is missing, synching instead" % self.relpath)
487 # Don't reuse the args.
488 return self.update(options, [], file_list)
489
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000490 for file_status in self.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000491 file_path = os.path.join(path, file_status[1])
492 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000493 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000494 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000495 continue
496
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000497 if logging.getLogger().isEnabledFor(logging.INFO):
498 logging.info('%s%s' % (file[0], file[1]))
499 else:
500 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000501 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000502 logging.error('No idea what is the status of %s.\n'
503 'You just found a bug in gclient, please ping '
504 'maruel@chromium.org ASAP!' % file_path)
505 # svn revert is really stupid. It fails on inconsistent line-endings,
506 # on switched directories, etc. So take no chance and delete everything!
507 try:
508 if not os.path.exists(file_path):
509 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000510 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000511 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000512 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000513 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000514 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000515 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000516 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000517 logging.error('no idea what is %s.\nYou just found a bug in gclient'
518 ', please ping maruel@chromium.org ASAP!' % file_path)
519 except EnvironmentError:
520 logging.error('Failed to remove %s.' % file_path)
521
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000522 try:
523 # svn revert is so broken we don't even use it. Using
524 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000525 self.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000526 file_list)
527 except OSError, e:
528 # Maybe the directory disapeared meanwhile. We don't want it to throw an
529 # exception.
530 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000531
msb@chromium.org0f282062009-11-06 20:14:02 +0000532 def revinfo(self, options, args, file_list):
533 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000534 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000535 return self.CaptureHeadRevision(self.url)
msb@chromium.org0f282062009-11-06 20:14:02 +0000536
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000537 def runhooks(self, options, args, file_list):
538 self.status(options, args, file_list)
539
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000540 def status(self, options, args, file_list):
541 """Display status information."""
542 path = os.path.join(self._root_dir, self.relpath)
543 command = ['status']
544 command.extend(args)
545 if not os.path.isdir(path):
546 # svn status won't work if the directory doesn't exist.
547 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
548 "does not exist."
549 % (' '.join(command), path))
550 # There's no file list to retrieve.
551 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000552 self.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000553
554 def FullUrlForRelativeUrl(self, url):
555 # Find the forth '/' and strip from there. A bit hackish.
556 return '/'.join(self.url.split('/')[:4]) + url