blob: bacbb6557626f872eadf440f19f77af9116bf7a3 [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):
msb@chromium.orgd8a63782010-01-25 17:47:05 +0000117 """'Cleanup' the repo.
118
119 There's no real git equivalent for the svn cleanup command, do a no-op.
120 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000121 __pychecker__ = 'unusednames=options,args,file_list'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000122
123 def diff(self, options, args, file_list):
msb@chromium.org3904caa2010-01-25 17:37:46 +0000124 __pychecker__ = 'unusednames=options,args,file_list'
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 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000134 __pychecker__ = 'unusednames=options,file_list'
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 """
msb@chromium.org3904caa2010-01-25 17:37:46 +0000149 __pychecker__ = 'unusednames=options,file_list'
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000150 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.orgeafef3b2010-01-25 17:42:27 +0000216 if options.force:
217 self._Run(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orgf2370632009-11-25 00:22:11 +0000218 self._Run(['rebase', '-v', '--onto', new_base, merge_base, cur_branch],
msb@chromium.org5bde4852009-12-14 16:47:12 +0000219 redirect_stdout=False, checkrc=False)
220
221 # If the rebase generated a conflict, abort and ask user to fix
222 if self._GetCurrentBranch() is None:
223 raise gclient_utils.Error('\n____ %s%s\n'
224 '\nConflict while rebasing this branch.\n'
225 'Fix the conflict and run gclient again.\n'
226 'See man git-rebase for details.\n'
227 % (self.relpath, rev_str))
228
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000229 print "Checked out revision %s." % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000230
231 def revert(self, options, args, file_list):
232 """Reverts local modifications.
233
234 All reverted files will be appended to file_list.
235 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000236 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000237 path = os.path.join(self._root_dir, self.relpath)
238 if not os.path.isdir(path):
239 # revert won't work if the directory doesn't exist. It needs to
240 # checkout instead.
241 print("\n_____ %s is missing, synching instead" % self.relpath)
242 # Don't reuse the args.
243 return self.update(options, [], file_list)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000244 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
245 files = self._Run(['diff', merge_base, '--name-only']).split()
246 self._Run(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000247 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
248
msb@chromium.org0f282062009-11-06 20:14:02 +0000249 def revinfo(self, options, args, file_list):
250 """Display revision"""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000251 __pychecker__ = 'unusednames=options,args,file_list'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000252 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000253
msb@chromium.orge28e4982009-09-25 20:51:45 +0000254 def runhooks(self, options, args, file_list):
255 self.status(options, args, file_list)
256
257 def status(self, options, args, file_list):
258 """Display status information."""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000259 __pychecker__ = 'unusednames=options,args'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000260 if not os.path.isdir(self.checkout_path):
261 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000262 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000263 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000264 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
265 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
266 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000267 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
268
msb@chromium.orge6f78352010-01-13 17:05:33 +0000269 def FullUrlForRelativeUrl(self, url):
270 # Strip from last '/'
271 # Equivalent to unix basename
272 base_url = self.url
273 return base_url[:base_url.rfind('/')] + url
274
msb@chromium.org923a0372009-12-11 20:42:43 +0000275 def _CheckMinVersion(self, min_version):
msb@chromium.org83376f22009-12-11 22:25:31 +0000276 def only_int(val):
277 if val.isdigit():
278 return int(val)
279 else:
280 return 0
msb@chromium.orgba9b2392009-12-11 23:30:13 +0000281 version = self._Run(['--version'], cwd='.').split()[-1]
msb@chromium.org83376f22009-12-11 22:25:31 +0000282 version_list = map(only_int, version.split('.'))
msb@chromium.org923a0372009-12-11 20:42:43 +0000283 min_version_list = map(int, min_version.split('.'))
284 for min_ver in min_version_list:
285 ver = version_list.pop(0)
286 if min_ver > ver:
287 raise gclient_utils.Error('git version %s < minimum required %s' %
288 (version, min_version))
289 elif min_ver < ver:
290 return
291
msb@chromium.org5bde4852009-12-14 16:47:12 +0000292 def _GetCurrentBranch(self):
293 # Returns name of current branch
294 # Returns None if inside a (no branch)
295 tokens = self._Run(['branch']).split()
296 branch = tokens[tokens.index('*') + 1]
297 if branch == '(no':
298 return None
299 return branch
300
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000301 def _Run(self, args, cwd=None, checkrc=True, redirect_stdout=True):
302 # TODO(maruel): Merge with Capture?
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000303 if cwd is None:
304 cwd = self.checkout_path
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000305 stdout=None
306 if redirect_stdout:
307 stdout=subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000308 if cwd == None:
309 cwd = self.checkout_path
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000310 cmd = [self.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000311 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000312 logging.debug(cmd)
313 try:
314 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
315 output = sp.communicate()[0]
316 except OSError:
317 raise gclient_utils.Error("git command '%s' failed to run." %
318 ' '.join(cmd) + "\nCheck that you have git installed.")
msb@chromium.orge28e4982009-09-25 20:51:45 +0000319 if checkrc and sp.returncode:
320 raise gclient_utils.Error('git command %s returned %d' %
321 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000322 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000323 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000324
325
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000326class SVNWrapper(SCMWrapper, scm.SVN):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000327 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000328
329 def cleanup(self, options, args, file_list):
330 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000331 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000332 command = ['cleanup']
333 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000334 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000335
336 def diff(self, options, args, file_list):
337 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000338 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000339 command = ['diff']
340 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000341 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000342
343 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000344 """Export a clean directory tree into the given path."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000345 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000346 assert len(args) == 1
347 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
348 try:
349 os.makedirs(export_path)
350 except OSError:
351 pass
352 assert os.path.exists(export_path)
353 command = ['export', '--force', '.']
354 command.append(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000355 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000356
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000357 def pack(self, options, args, file_list):
358 """Generates a patch file which can be applied to the root of the
359 repository."""
360 __pychecker__ = 'unusednames=file_list,options'
361 path = os.path.join(self._root_dir, self.relpath)
362 command = ['diff']
363 command.extend(args)
364
365 filterer = DiffFilterer(self.relpath)
366 self.RunAndFilterOutput(command, path, False, False, filterer.Filter)
367
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000368 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000369 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000370
371 All updated files will be appended to file_list.
372
373 Raises:
374 Error: if can't get URL for relative path.
375 """
376 # Only update if git is not controlling the directory.
377 checkout_path = os.path.join(self._root_dir, self.relpath)
378 git_path = os.path.join(self._root_dir, self.relpath, '.git')
379 if os.path.exists(git_path):
380 print("________ found .git directory; skipping %s" % self.relpath)
381 return
382
383 if args:
384 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
385
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000386 url, revision = gclient_utils.SplitUrlRevision(self.url)
387 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000388 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000389 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000390 if options.revision:
391 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000392 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000393 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000394 forced_revision = True
395 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000396 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000397
398 if not os.path.exists(checkout_path):
399 # We need to checkout.
400 command = ['checkout', url, checkout_path]
401 if revision:
402 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000403 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000404 return
405
406 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000407 from_info = self.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000408 if not from_info:
409 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
410 "directory is present. Delete the directory "
411 "and try again." %
412 checkout_path)
413
maruel@chromium.org7753d242009-10-07 17:40:24 +0000414 if options.manually_grab_svn_rev:
415 # Retrieve the current HEAD version because svn is slow at null updates.
416 if not revision:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000417 from_info_live = self.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000418 revision = str(from_info_live['Revision'])
419 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000420
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000421 if from_info['URL'] != base_url:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000422 to_info = self.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000423 if not to_info.get('Repository Root') or not to_info.get('UUID'):
424 # The url is invalid or the server is not accessible, it's safer to bail
425 # out right now.
426 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000427 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
428 and (from_info['UUID'] == to_info['UUID']))
429 if can_switch:
430 print("\n_____ relocating %s to a new checkout" % self.relpath)
431 # We have different roots, so check if we can switch --relocate.
432 # Subversion only permits this if the repository UUIDs match.
433 # Perform the switch --relocate, then rewrite the from_url
434 # to reflect where we "are now." (This is the same way that
435 # Subversion itself handles the metadata when switch --relocate
436 # is used.) This makes the checks below for whether we
437 # can update to a revision or have to switch to a different
438 # branch work as expected.
439 # TODO(maruel): TEST ME !
440 command = ["switch", "--relocate",
441 from_info['Repository Root'],
442 to_info['Repository Root'],
443 self.relpath]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000444 self.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000445 from_info['URL'] = from_info['URL'].replace(
446 from_info['Repository Root'],
447 to_info['Repository Root'])
448 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000449 if self.CaptureStatus(checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000450 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
451 "don't match and there is local changes "
452 "in %s. Delete the directory and "
453 "try again." % (url, checkout_path))
454 # Ok delete it.
455 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000456 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000457 # We need to checkout.
458 command = ['checkout', url, checkout_path]
459 if revision:
460 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000461 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000462 return
463
464
465 # If the provided url has a revision number that matches the revision
466 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000467 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000468 if options.verbose or not forced_revision:
469 print("\n_____ %s%s" % (self.relpath, rev_str))
470 return
471
472 command = ["update", checkout_path]
473 if revision:
474 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000475 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000476
477 def revert(self, options, args, file_list):
478 """Reverts local modifications. Subversion specific.
479
480 All reverted files will be appended to file_list, even if Subversion
481 doesn't know about them.
482 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000483 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000484 path = os.path.join(self._root_dir, self.relpath)
485 if not os.path.isdir(path):
486 # svn revert won't work if the directory doesn't exist. It needs to
487 # checkout instead.
488 print("\n_____ %s is missing, synching instead" % self.relpath)
489 # Don't reuse the args.
490 return self.update(options, [], file_list)
491
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000492 for file_status in self.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000493 file_path = os.path.join(path, file_status[1])
494 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000495 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000496 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000497 continue
498
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000499 if logging.getLogger().isEnabledFor(logging.INFO):
500 logging.info('%s%s' % (file[0], file[1]))
501 else:
502 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000503 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000504 logging.error('No idea what is the status of %s.\n'
505 'You just found a bug in gclient, please ping '
506 'maruel@chromium.org ASAP!' % file_path)
507 # svn revert is really stupid. It fails on inconsistent line-endings,
508 # on switched directories, etc. So take no chance and delete everything!
509 try:
510 if not os.path.exists(file_path):
511 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000512 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000513 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000514 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000515 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000516 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000517 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000518 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000519 logging.error('no idea what is %s.\nYou just found a bug in gclient'
520 ', please ping maruel@chromium.org ASAP!' % file_path)
521 except EnvironmentError:
522 logging.error('Failed to remove %s.' % file_path)
523
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000524 try:
525 # svn revert is so broken we don't even use it. Using
526 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000527 self.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000528 file_list)
529 except OSError, e:
530 # Maybe the directory disapeared meanwhile. We don't want it to throw an
531 # exception.
532 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000533
msb@chromium.org0f282062009-11-06 20:14:02 +0000534 def revinfo(self, options, args, file_list):
535 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000536 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000537 return self.CaptureHeadRevision(self.url)
msb@chromium.org0f282062009-11-06 20:14:02 +0000538
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000539 def runhooks(self, options, args, file_list):
540 self.status(options, args, file_list)
541
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000542 def status(self, options, args, file_list):
543 """Display status information."""
544 path = os.path.join(self._root_dir, self.relpath)
545 command = ['status']
546 command.extend(args)
547 if not os.path.isdir(path):
548 # svn status won't work if the directory doesn't exist.
549 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
550 "does not exist."
551 % (' '.join(command), path))
552 # There's no file list to retrieve.
553 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000554 self.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000555
556 def FullUrlForRelativeUrl(self, url):
557 # Find the forth '/' and strip from there. A bit hackish.
558 return '/'.join(self.url.split('/')[:4]) + url