blob: 1f76910d2eeae86740814918470cfd98361a7158 [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.org2de10252010-02-08 01:10:39 +0000182 # Cloning
183 for i in range(3):
184 try:
185 self._Run(['clone', url, self.checkout_path],
186 cwd=self._root_dir, redirect_stdout=False)
187 break
188 except gclient_utils.Error, e:
189 # TODO(maruel): Hackish, should be fixed by moving _Run() to
190 # CheckCall().
191 # Too bad we don't have access to the actual output.
192 # We should check for "transfer closed with NNN bytes remaining to
193 # read". In the meantime, just make sure .git exists.
194 if (e.args[0] == 'git command clone returned 128' and
195 os.path.exists(os.path.join(self.checkout_path, '.git'))):
196 print str(e)
197 print "Retrying..."
198 continue
199 raise e
200
msb@chromium.orge28e4982009-09-25 20:51:45 +0000201 if revision:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000202 self._Run(['reset', '--hard', revision], redirect_stdout=False)
203 files = self._Run(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000204 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
205 return
206
msb@chromium.orge4af1ab2010-01-13 21:26:09 +0000207 if not os.path.exists(os.path.join(self.checkout_path, '.git')):
208 raise gclient_utils.Error('\n____ %s%s\n'
209 '\tPath is not a git repo. No .git dir.\n'
210 '\tTo resolve:\n'
211 '\t\trm -rf %s\n'
212 '\tAnd run gclient sync again\n'
213 % (self.relpath, rev_str, self.relpath))
214
msb@chromium.orge28e4982009-09-25 20:51:45 +0000215 new_base = 'origin'
216 if revision:
217 new_base = revision
msb@chromium.org5bde4852009-12-14 16:47:12 +0000218 cur_branch = self._GetCurrentBranch()
219
220 # Check if we are in a rebase conflict
221 if cur_branch is None:
222 raise gclient_utils.Error('\n____ %s%s\n'
223 '\tAlready in a conflict, i.e. (no branch).\n'
224 '\tFix the conflict and run gclient again.\n'
225 '\tOr to abort run:\n\t\tgit-rebase --abort\n'
226 '\tSee man git-rebase for details.\n'
227 % (self.relpath, rev_str))
228
maruel@chromium.org2de10252010-02-08 01:10:39 +0000229 # TODO(maruel): Do we need to do an automatic retry here? Probably overkill
msb@chromium.orgf2370632009-11-25 00:22:11 +0000230 merge_base = self._Run(['merge-base', 'HEAD', new_base])
231 self._Run(['remote', 'update'], redirect_stdout=False)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000232 files = self._Run(['diff', new_base, '--name-only']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000233 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
davemoore@chromium.org793796d2010-02-19 17:27:41 +0000234 if options.force or options.reset:
msb@chromium.orgeafef3b2010-01-25 17:42:27 +0000235 self._Run(['reset', '--hard', merge_base], redirect_stdout=False)
maruel@chromium.org2de10252010-02-08 01:10:39 +0000236 try:
237 self._Run(['rebase', '-v', '--onto', new_base, merge_base, cur_branch],
238 redirect_stdout=False)
239 except gclient_utils.Error:
240 pass
msb@chromium.org5bde4852009-12-14 16:47:12 +0000241
242 # If the rebase generated a conflict, abort and ask user to fix
243 if self._GetCurrentBranch() is None:
244 raise gclient_utils.Error('\n____ %s%s\n'
245 '\nConflict while rebasing this branch.\n'
246 'Fix the conflict and run gclient again.\n'
247 'See man git-rebase for details.\n'
248 % (self.relpath, rev_str))
249
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000250 print "Checked out revision %s." % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000251
252 def revert(self, options, args, file_list):
253 """Reverts local modifications.
254
255 All reverted files will be appended to file_list.
256 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000257 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000258 path = os.path.join(self._root_dir, self.relpath)
259 if not os.path.isdir(path):
260 # revert won't work if the directory doesn't exist. It needs to
261 # checkout instead.
262 print("\n_____ %s is missing, synching instead" % self.relpath)
263 # Don't reuse the args.
264 return self.update(options, [], file_list)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000265 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
266 files = self._Run(['diff', merge_base, '--name-only']).split()
267 self._Run(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000268 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
269
msb@chromium.org0f282062009-11-06 20:14:02 +0000270 def revinfo(self, options, args, file_list):
271 """Display revision"""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000272 __pychecker__ = 'unusednames=options,args,file_list'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000273 return self._Run(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000274
msb@chromium.orge28e4982009-09-25 20:51:45 +0000275 def runhooks(self, options, args, file_list):
276 self.status(options, args, file_list)
277
278 def status(self, options, args, file_list):
279 """Display status information."""
msb@chromium.org3904caa2010-01-25 17:37:46 +0000280 __pychecker__ = 'unusednames=options,args'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000281 if not os.path.isdir(self.checkout_path):
282 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000283 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000284 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000285 merge_base = self._Run(['merge-base', 'HEAD', 'origin'])
286 self._Run(['diff', '--name-status', merge_base], redirect_stdout=False)
287 files = self._Run(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000288 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
289
msb@chromium.orge6f78352010-01-13 17:05:33 +0000290 def FullUrlForRelativeUrl(self, url):
291 # Strip from last '/'
292 # Equivalent to unix basename
293 base_url = self.url
294 return base_url[:base_url.rfind('/')] + url
295
msb@chromium.org923a0372009-12-11 20:42:43 +0000296 def _CheckMinVersion(self, min_version):
msb@chromium.org83376f22009-12-11 22:25:31 +0000297 def only_int(val):
298 if val.isdigit():
299 return int(val)
300 else:
301 return 0
msb@chromium.orgba9b2392009-12-11 23:30:13 +0000302 version = self._Run(['--version'], cwd='.').split()[-1]
msb@chromium.org83376f22009-12-11 22:25:31 +0000303 version_list = map(only_int, version.split('.'))
msb@chromium.org923a0372009-12-11 20:42:43 +0000304 min_version_list = map(int, min_version.split('.'))
305 for min_ver in min_version_list:
306 ver = version_list.pop(0)
307 if min_ver > ver:
308 raise gclient_utils.Error('git version %s < minimum required %s' %
309 (version, min_version))
310 elif min_ver < ver:
311 return
312
msb@chromium.org5bde4852009-12-14 16:47:12 +0000313 def _GetCurrentBranch(self):
314 # Returns name of current branch
315 # Returns None if inside a (no branch)
316 tokens = self._Run(['branch']).split()
317 branch = tokens[tokens.index('*') + 1]
318 if branch == '(no':
319 return None
320 return branch
321
maruel@chromium.org2de10252010-02-08 01:10:39 +0000322 def _Run(self, args, cwd=None, redirect_stdout=True):
323 # TODO(maruel): Merge with Capture or better gclient_utils.CheckCall().
maruel@chromium.orgffe96f02009-12-09 18:39:15 +0000324 if cwd is None:
325 cwd = self.checkout_path
maruel@chromium.org2de10252010-02-08 01:10:39 +0000326 stdout = None
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000327 if redirect_stdout:
maruel@chromium.org2de10252010-02-08 01:10:39 +0000328 stdout = subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000329 if cwd == None:
330 cwd = self.checkout_path
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000331 cmd = [self.COMMAND]
msb@chromium.orge28e4982009-09-25 20:51:45 +0000332 cmd.extend(args)
maruel@chromium.orgf3909bf2010-01-08 01:14:51 +0000333 logging.debug(cmd)
334 try:
335 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
336 output = sp.communicate()[0]
337 except OSError:
338 raise gclient_utils.Error("git command '%s' failed to run." %
339 ' '.join(cmd) + "\nCheck that you have git installed.")
maruel@chromium.org2de10252010-02-08 01:10:39 +0000340 if sp.returncode:
msb@chromium.orge28e4982009-09-25 20:51:45 +0000341 raise gclient_utils.Error('git command %s returned %d' %
342 (args[0], sp.returncode))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000343 if output is not None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000344 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000345
346
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000347class SVNWrapper(SCMWrapper, scm.SVN):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000348 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000349
350 def cleanup(self, options, args, file_list):
351 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000352 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000353 command = ['cleanup']
354 command.extend(args)
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
357 def diff(self, options, args, file_list):
358 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000359 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000360 command = ['diff']
361 command.extend(args)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000362 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000363
364 def export(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000365 """Export a clean directory tree into the given path."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000366 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000367 assert len(args) == 1
368 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
369 try:
370 os.makedirs(export_path)
371 except OSError:
372 pass
373 assert os.path.exists(export_path)
374 command = ['export', '--force', '.']
375 command.append(export_path)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000376 self.Run(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000377
maruel@chromium.orgee4071d2009-12-22 22:25:37 +0000378 def pack(self, options, args, file_list):
379 """Generates a patch file which can be applied to the root of the
380 repository."""
381 __pychecker__ = 'unusednames=file_list,options'
382 path = os.path.join(self._root_dir, self.relpath)
383 command = ['diff']
384 command.extend(args)
385
386 filterer = DiffFilterer(self.relpath)
387 self.RunAndFilterOutput(command, path, False, False, filterer.Filter)
388
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000389 def update(self, options, args, file_list):
msb@chromium.orgd6504212010-01-13 17:34:31 +0000390 """Runs svn to update or transparently checkout the working copy.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000391
392 All updated files will be appended to file_list.
393
394 Raises:
395 Error: if can't get URL for relative path.
396 """
397 # Only update if git is not controlling the directory.
398 checkout_path = os.path.join(self._root_dir, self.relpath)
399 git_path = os.path.join(self._root_dir, self.relpath, '.git')
400 if os.path.exists(git_path):
401 print("________ found .git directory; skipping %s" % self.relpath)
402 return
403
404 if args:
405 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
406
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000407 url, revision = gclient_utils.SplitUrlRevision(self.url)
408 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000409 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000410 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000411 if options.revision:
412 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000413 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000414 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000415 forced_revision = True
416 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000417 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000418
419 if not os.path.exists(checkout_path):
420 # We need to checkout.
421 command = ['checkout', url, checkout_path]
422 if revision:
423 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000424 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000425 return
426
427 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000428 from_info = self.CaptureInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000429 if not from_info:
430 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
431 "directory is present. Delete the directory "
432 "and try again." %
433 checkout_path)
434
maruel@chromium.org7753d242009-10-07 17:40:24 +0000435 if options.manually_grab_svn_rev:
436 # Retrieve the current HEAD version because svn is slow at null updates.
437 if not revision:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000438 from_info_live = self.CaptureInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000439 revision = str(from_info_live['Revision'])
440 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000441
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000442 if from_info['URL'] != base_url:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000443 to_info = self.CaptureInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000444 if not to_info.get('Repository Root') or not to_info.get('UUID'):
445 # The url is invalid or the server is not accessible, it's safer to bail
446 # out right now.
447 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000448 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
449 and (from_info['UUID'] == to_info['UUID']))
450 if can_switch:
451 print("\n_____ relocating %s to a new checkout" % self.relpath)
452 # We have different roots, so check if we can switch --relocate.
453 # Subversion only permits this if the repository UUIDs match.
454 # Perform the switch --relocate, then rewrite the from_url
455 # to reflect where we "are now." (This is the same way that
456 # Subversion itself handles the metadata when switch --relocate
457 # is used.) This makes the checks below for whether we
458 # can update to a revision or have to switch to a different
459 # branch work as expected.
460 # TODO(maruel): TEST ME !
461 command = ["switch", "--relocate",
462 from_info['Repository Root'],
463 to_info['Repository Root'],
464 self.relpath]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000465 self.Run(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000466 from_info['URL'] = from_info['URL'].replace(
467 from_info['Repository Root'],
468 to_info['Repository Root'])
469 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000470 if self.CaptureStatus(checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000471 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
472 "don't match and there is local changes "
473 "in %s. Delete the directory and "
474 "try again." % (url, checkout_path))
475 # Ok delete it.
476 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000477 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000478 # We need to checkout.
479 command = ['checkout', url, checkout_path]
480 if revision:
481 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000482 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000483 return
484
485
486 # If the provided url has a revision number that matches the revision
487 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000488 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000489 if options.verbose or not forced_revision:
490 print("\n_____ %s%s" % (self.relpath, rev_str))
491 return
492
493 command = ["update", checkout_path]
494 if revision:
495 command.extend(['--revision', str(revision)])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000496 self.RunAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000497
498 def revert(self, options, args, file_list):
499 """Reverts local modifications. Subversion specific.
500
501 All reverted files will be appended to file_list, even if Subversion
502 doesn't know about them.
503 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000504 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000505 path = os.path.join(self._root_dir, self.relpath)
506 if not os.path.isdir(path):
507 # svn revert won't work if the directory doesn't exist. It needs to
508 # checkout instead.
509 print("\n_____ %s is missing, synching instead" % self.relpath)
510 # Don't reuse the args.
511 return self.update(options, [], file_list)
512
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000513 for file_status in self.CaptureStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000514 file_path = os.path.join(path, file_status[1])
515 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000516 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000517 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000518 continue
519
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000520 if logging.getLogger().isEnabledFor(logging.INFO):
521 logging.info('%s%s' % (file[0], file[1]))
522 else:
523 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000524 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000525 logging.error('No idea what is the status of %s.\n'
526 'You just found a bug in gclient, please ping '
527 'maruel@chromium.org ASAP!' % file_path)
528 # svn revert is really stupid. It fails on inconsistent line-endings,
529 # on switched directories, etc. So take no chance and delete everything!
530 try:
531 if not os.path.exists(file_path):
532 pass
maruel@chromium.orgd2e78ff2010-01-11 20:37:19 +0000533 elif os.path.isfile(file_path) or os.path.islink(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000534 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000535 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000536 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000537 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000538 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000539 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000540 logging.error('no idea what is %s.\nYou just found a bug in gclient'
541 ', please ping maruel@chromium.org ASAP!' % file_path)
542 except EnvironmentError:
543 logging.error('Failed to remove %s.' % file_path)
544
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000545 try:
546 # svn revert is so broken we don't even use it. Using
547 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000548 self.RunAndGetFileList(options, ['update', '--revision', 'BASE'], path,
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000549 file_list)
550 except OSError, e:
551 # Maybe the directory disapeared meanwhile. We don't want it to throw an
552 # exception.
553 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000554
msb@chromium.org0f282062009-11-06 20:14:02 +0000555 def revinfo(self, options, args, file_list):
556 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000557 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000558 return self.CaptureHeadRevision(self.url)
msb@chromium.org0f282062009-11-06 20:14:02 +0000559
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000560 def runhooks(self, options, args, file_list):
561 self.status(options, args, file_list)
562
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000563 def status(self, options, args, file_list):
564 """Display status information."""
565 path = os.path.join(self._root_dir, self.relpath)
566 command = ['status']
567 command.extend(args)
568 if not os.path.isdir(path):
569 # svn status won't work if the directory doesn't exist.
570 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
571 "does not exist."
572 % (' '.join(command), path))
573 # There's no file list to retrieve.
574 else:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000575 self.RunAndGetFileList(options, command, path, file_list)
msb@chromium.orge6f78352010-01-13 17:05:33 +0000576
577 def FullUrlForRelativeUrl(self, url):
578 # Find the forth '/' and strip from there. A bit hackish.
579 return '/'.join(self.url.split('/')[:4]) + url