blob: e2459d91a2afa7eb8a75bddeaafce5f263536ebf [file] [log] [blame]
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001# Copyright 2009 Google Inc. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
maruel@chromium.org8ce0a132009-11-12 19:17:32 +000015"""Gclient-specific SCM-specific operations."""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016
maruel@chromium.org754960e2009-09-21 12:31:05 +000017import logging
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000018import os
19import re
20import subprocess
21import sys
22import xml.dom.minidom
23
24import gclient_utils
maruel@chromium.org8ce0a132009-11-12 19:17:32 +000025# TODO(maruel): Temporary.
26from scm import CaptureGit, CaptureGitStatus, CaptureSVN,
27from scm import CaptureSVNHeadRevision, CaptureSVNInfo, CaptureSVNStatus,
28from scm import RunSVN, RunSVNAndFilterOutput, RunSVNAndGetFileList
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000029
30
31### SCM abstraction layer
32
33
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000034# Factory Method for SCM wrapper creation
35
36def CreateSCM(url=None, root_dir=None, relpath=None, scm_name='svn'):
37 # TODO(maruel): Deduce the SCM from the url.
38 scm_map = {
39 'svn' : SVNWrapper,
msb@chromium.orge28e4982009-09-25 20:51:45 +000040 'git' : GitWrapper,
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000041 }
msb@chromium.orge28e4982009-09-25 20:51:45 +000042
43 if url and (url.startswith('git:') or
44 url.startswith('ssh:') or
45 url.endswith('.git')):
46 scm_name = 'git'
47
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000048 if not scm_name in scm_map:
49 raise gclient_utils.Error('Unsupported scm %s' % scm_name)
50 return scm_map[scm_name](url, root_dir, relpath, scm_name)
51
52
53# SCMWrapper base class
54
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000055class SCMWrapper(object):
56 """Add necessary glue between all the supported SCM.
57
58 This is the abstraction layer to bind to different SCM. Since currently only
59 subversion is supported, a lot of subersionism remains. This can be sorted out
60 once another SCM is supported."""
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000061 def __init__(self, url=None, root_dir=None, relpath=None,
62 scm_name='svn'):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000063 self.scm_name = scm_name
64 self.url = url
maruel@chromium.org5e73b0c2009-09-18 19:47:48 +000065 self._root_dir = root_dir
66 if self._root_dir:
67 self._root_dir = self._root_dir.replace('/', os.sep)
68 self.relpath = relpath
69 if self.relpath:
70 self.relpath = self.relpath.replace('/', os.sep)
msb@chromium.orge28e4982009-09-25 20:51:45 +000071 if self.relpath and self._root_dir:
72 self.checkout_path = os.path.join(self._root_dir, self.relpath)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000073
74 def FullUrlForRelativeUrl(self, url):
75 # Find the forth '/' and strip from there. A bit hackish.
76 return '/'.join(self.url.split('/')[:4]) + url
77
78 def RunCommand(self, command, options, args, file_list=None):
79 # file_list will have all files that are modified appended to it.
maruel@chromium.orgde754ac2009-09-17 18:04:50 +000080 if file_list is None:
81 file_list = []
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000082
msb@chromium.org0f282062009-11-06 20:14:02 +000083 commands = ['cleanup', 'export', 'update', 'revert', 'revinfo',
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000084 'status', 'diff', 'pack', 'runhooks']
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000085
86 if not command in commands:
87 raise gclient_utils.Error('Unknown command %s' % command)
88
msb@chromium.orgcb5442b2009-09-22 16:51:24 +000089 if not command in dir(self):
90 raise gclient_utils.Error('Command %s not implemnted in %s wrapper' % (
91 command, self.scm_name))
92
93 return getattr(self, command)(options, args, file_list)
94
95
msb@chromium.orge28e4982009-09-25 20:51:45 +000096class GitWrapper(SCMWrapper):
97 """Wrapper for Git"""
98
99 def cleanup(self, options, args, file_list):
100 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000101 __pychecker__ = 'unusednames=args,file_list,options'
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000102 self._RunGit(['prune'], redirect_stdout=False)
103 self._RunGit(['fsck'], redirect_stdout=False)
104 self._RunGit(['gc'], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000105
106 def diff(self, options, args, file_list):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000107 __pychecker__ = 'unusednames=args,file_list,options'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000108 merge_base = self._RunGit(['merge-base', 'HEAD', 'origin'])
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000109 self._RunGit(['diff', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000110
111 def export(self, options, args, file_list):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000112 __pychecker__ = 'unusednames=file_list,options'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000113 assert len(args) == 1
114 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
115 if not os.path.exists(export_path):
116 os.makedirs(export_path)
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000117 self._RunGit(['checkout-index', '-a', '--prefix=%s/' % export_path],
118 redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000119
120 def update(self, options, args, file_list):
121 """Runs git to update or transparently checkout the working copy.
122
123 All updated files will be appended to file_list.
124
125 Raises:
126 Error: if can't get URL for relative path.
127 """
128
129 if args:
130 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
131
msb@chromium.org7780c282009-11-09 17:54:17 +0000132 if self.url.startswith('ssh:'):
133 # Make sure ssh://test@example.com/test.git@stable works
134 regex = r"(ssh://(?:[\w]+@)?[-\w:\.]+/[-\w\.]+)(?:@([\w/]+))?"
135 components = re.search(regex, self.url).groups()
136 else:
137 components = self.url.split("@")
msb@chromium.orge28e4982009-09-25 20:51:45 +0000138 url = components[0]
139 revision = None
140 if options.revision:
141 revision = options.revision
142 elif len(components) == 2:
143 revision = components[1]
144
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000145 if options.verbose:
146 rev_str = ""
147 if revision:
148 rev_str = ' at %s' % revision
149 print("\n_____ %s%s" % (self.relpath, rev_str))
150
msb@chromium.orge28e4982009-09-25 20:51:45 +0000151 if not os.path.exists(self.checkout_path):
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000152 self._RunGit(['clone', url, self.checkout_path],
153 cwd=self._root_dir, redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000154 if revision:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000155 self._RunGit(['reset', '--hard', revision], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000156 files = self._RunGit(['ls-files']).split()
157 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
158 return
159
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000160 self._RunGit(['remote', 'update'], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000161 new_base = 'origin'
162 if revision:
163 new_base = revision
164 files = self._RunGit(['diff', new_base, '--name-only']).split()
165 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000166 self._RunGit(['rebase', '-v', new_base], redirect_stdout=False)
167 print "Checked out revision %s." % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000168
169 def revert(self, options, args, file_list):
170 """Reverts local modifications.
171
172 All reverted files will be appended to file_list.
173 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000174 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000175 path = os.path.join(self._root_dir, self.relpath)
176 if not os.path.isdir(path):
177 # revert won't work if the directory doesn't exist. It needs to
178 # checkout instead.
179 print("\n_____ %s is missing, synching instead" % self.relpath)
180 # Don't reuse the args.
181 return self.update(options, [], file_list)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000182 merge_base = self._RunGit(['merge-base', 'HEAD', 'origin'])
183 files = self._RunGit(['diff', merge_base, '--name-only']).split()
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000184 self._RunGit(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000185 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
186
msb@chromium.org0f282062009-11-06 20:14:02 +0000187 def revinfo(self, options, args, file_list):
188 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000189 __pychecker__ = 'unusednames=args,file_list,options'
msb@chromium.org0f282062009-11-06 20:14:02 +0000190 return self._RunGit(['rev-parse', 'HEAD'])
191
msb@chromium.orge28e4982009-09-25 20:51:45 +0000192 def runhooks(self, options, args, file_list):
193 self.status(options, args, file_list)
194
195 def status(self, options, args, file_list):
196 """Display status information."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000197 __pychecker__ = 'unusednames=args,options'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000198 if not os.path.isdir(self.checkout_path):
199 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000200 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000201 else:
202 merge_base = self._RunGit(['merge-base', 'HEAD', 'origin'])
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000203 self._RunGit(['diff', '--name-status', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000204 files = self._RunGit(['diff', '--name-only', merge_base]).split()
205 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
206
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000207 def _RunGit(self, args, cwd=None, checkrc=True, redirect_stdout=True):
208 stdout=None
209 if redirect_stdout:
210 stdout=subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000211 if cwd == None:
212 cwd = self.checkout_path
213 cmd = ['git']
214 cmd.extend(args)
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000215 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000216 if checkrc and sp.returncode:
217 raise gclient_utils.Error('git command %s returned %d' %
218 (args[0], sp.returncode))
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000219 output = sp.communicate()[0]
220 if output != None:
221 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000222
223
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000224class SVNWrapper(SCMWrapper):
225 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000226
227 def cleanup(self, options, args, file_list):
228 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000229 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000230 command = ['cleanup']
231 command.extend(args)
232 RunSVN(command, os.path.join(self._root_dir, self.relpath))
233
234 def diff(self, options, args, file_list):
235 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000236 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000237 command = ['diff']
238 command.extend(args)
239 RunSVN(command, os.path.join(self._root_dir, self.relpath))
240
241 def export(self, options, args, file_list):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000242 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000243 assert len(args) == 1
244 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
245 try:
246 os.makedirs(export_path)
247 except OSError:
248 pass
249 assert os.path.exists(export_path)
250 command = ['export', '--force', '.']
251 command.append(export_path)
252 RunSVN(command, os.path.join(self._root_dir, self.relpath))
253
254 def update(self, options, args, file_list):
255 """Runs SCM to update or transparently checkout the working copy.
256
257 All updated files will be appended to file_list.
258
259 Raises:
260 Error: if can't get URL for relative path.
261 """
262 # Only update if git is not controlling the directory.
263 checkout_path = os.path.join(self._root_dir, self.relpath)
264 git_path = os.path.join(self._root_dir, self.relpath, '.git')
265 if os.path.exists(git_path):
266 print("________ found .git directory; skipping %s" % self.relpath)
267 return
268
269 if args:
270 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
271
272 url = self.url
273 components = url.split("@")
274 revision = None
275 forced_revision = False
276 if options.revision:
277 # Override the revision number.
278 url = '%s@%s' % (components[0], str(options.revision))
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000279 revision = options.revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000280 forced_revision = True
281 elif len(components) == 2:
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000282 revision = components[1]
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000283 forced_revision = True
284
285 rev_str = ""
286 if revision:
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000287 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000288
289 if not os.path.exists(checkout_path):
290 # We need to checkout.
291 command = ['checkout', url, checkout_path]
292 if revision:
293 command.extend(['--revision', str(revision)])
dpranke@google.com22e29d42009-10-28 00:48:26 +0000294 RunSVNAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000295 return
296
297 # Get the existing scm url and the revision number of the current checkout.
298 from_info = CaptureSVNInfo(os.path.join(checkout_path, '.'), '.')
299 if not from_info:
300 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
301 "directory is present. Delete the directory "
302 "and try again." %
303 checkout_path)
304
maruel@chromium.org7753d242009-10-07 17:40:24 +0000305 if options.manually_grab_svn_rev:
306 # Retrieve the current HEAD version because svn is slow at null updates.
307 if not revision:
308 from_info_live = CaptureSVNInfo(from_info['URL'], '.')
309 revision = str(from_info_live['Revision'])
310 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000311
312 if from_info['URL'] != components[0]:
313 to_info = CaptureSVNInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000314 if not to_info.get('Repository Root') or not to_info.get('UUID'):
315 # The url is invalid or the server is not accessible, it's safer to bail
316 # out right now.
317 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000318 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
319 and (from_info['UUID'] == to_info['UUID']))
320 if can_switch:
321 print("\n_____ relocating %s to a new checkout" % self.relpath)
322 # We have different roots, so check if we can switch --relocate.
323 # Subversion only permits this if the repository UUIDs match.
324 # Perform the switch --relocate, then rewrite the from_url
325 # to reflect where we "are now." (This is the same way that
326 # Subversion itself handles the metadata when switch --relocate
327 # is used.) This makes the checks below for whether we
328 # can update to a revision or have to switch to a different
329 # branch work as expected.
330 # TODO(maruel): TEST ME !
331 command = ["switch", "--relocate",
332 from_info['Repository Root'],
333 to_info['Repository Root'],
334 self.relpath]
335 RunSVN(command, self._root_dir)
336 from_info['URL'] = from_info['URL'].replace(
337 from_info['Repository Root'],
338 to_info['Repository Root'])
339 else:
340 if CaptureSVNStatus(checkout_path):
341 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
342 "don't match and there is local changes "
343 "in %s. Delete the directory and "
344 "try again." % (url, checkout_path))
345 # Ok delete it.
346 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000347 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000348 # We need to checkout.
349 command = ['checkout', url, checkout_path]
350 if revision:
351 command.extend(['--revision', str(revision)])
dpranke@google.com22e29d42009-10-28 00:48:26 +0000352 RunSVNAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000353 return
354
355
356 # If the provided url has a revision number that matches the revision
357 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000358 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000359 if options.verbose or not forced_revision:
360 print("\n_____ %s%s" % (self.relpath, rev_str))
361 return
362
363 command = ["update", checkout_path]
364 if revision:
365 command.extend(['--revision', str(revision)])
dpranke@google.com22e29d42009-10-28 00:48:26 +0000366 RunSVNAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000367
368 def revert(self, options, args, file_list):
369 """Reverts local modifications. Subversion specific.
370
371 All reverted files will be appended to file_list, even if Subversion
372 doesn't know about them.
373 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000374 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000375 path = os.path.join(self._root_dir, self.relpath)
376 if not os.path.isdir(path):
377 # svn revert won't work if the directory doesn't exist. It needs to
378 # checkout instead.
379 print("\n_____ %s is missing, synching instead" % self.relpath)
380 # Don't reuse the args.
381 return self.update(options, [], file_list)
382
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000383 for file_status in CaptureSVNStatus(path):
384 file_path = os.path.join(path, file_status[1])
385 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000386 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000387 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000388 continue
389
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000390 if logging.getLogger().isEnabledFor(logging.INFO):
391 logging.info('%s%s' % (file[0], file[1]))
392 else:
393 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000394 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000395 logging.error('No idea what is the status of %s.\n'
396 'You just found a bug in gclient, please ping '
397 'maruel@chromium.org ASAP!' % file_path)
398 # svn revert is really stupid. It fails on inconsistent line-endings,
399 # on switched directories, etc. So take no chance and delete everything!
400 try:
401 if not os.path.exists(file_path):
402 pass
403 elif os.path.isfile(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000404 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000405 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000406 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000407 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000408 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000409 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000410 logging.error('no idea what is %s.\nYou just found a bug in gclient'
411 ', please ping maruel@chromium.org ASAP!' % file_path)
412 except EnvironmentError:
413 logging.error('Failed to remove %s.' % file_path)
414
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000415 try:
416 # svn revert is so broken we don't even use it. Using
417 # "svn up --revision BASE" achieve the same effect.
dpranke@google.com22e29d42009-10-28 00:48:26 +0000418 RunSVNAndGetFileList(options, ['update', '--revision', 'BASE'], path,
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000419 file_list)
420 except OSError, e:
421 # Maybe the directory disapeared meanwhile. We don't want it to throw an
422 # exception.
423 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000424
msb@chromium.org0f282062009-11-06 20:14:02 +0000425 def revinfo(self, options, args, file_list):
426 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000427 __pychecker__ = 'unusednames=args,file_list,options'
msb@chromium.org0f282062009-11-06 20:14:02 +0000428 return CaptureSVNHeadRevision(self.url)
429
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000430 def runhooks(self, options, args, file_list):
431 self.status(options, args, file_list)
432
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000433 def status(self, options, args, file_list):
434 """Display status information."""
435 path = os.path.join(self._root_dir, self.relpath)
436 command = ['status']
437 command.extend(args)
438 if not os.path.isdir(path):
439 # svn status won't work if the directory doesn't exist.
440 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
441 "does not exist."
442 % (' '.join(command), path))
443 # There's no file list to retrieve.
444 else:
dpranke@google.com22e29d42009-10-28 00:48:26 +0000445 RunSVNAndGetFileList(options, command, path, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000446
447 def pack(self, options, args, file_list):
448 """Generates a patch file which can be applied to the root of the
449 repository."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000450 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000451 path = os.path.join(self._root_dir, self.relpath)
452 command = ['diff']
453 command.extend(args)
454 # Simple class which tracks which file is being diffed and
455 # replaces instances of its file name in the original and
456 # working copy lines of the svn diff output.
457 class DiffFilterer(object):
458 index_string = "Index: "
459 original_prefix = "--- "
460 working_prefix = "+++ "
461
462 def __init__(self, relpath):
463 # Note that we always use '/' as the path separator to be
464 # consistent with svn's cygwin-style output on Windows
465 self._relpath = relpath.replace("\\", "/")
466 self._current_file = ""
467 self._replacement_file = ""
468
469 def SetCurrentFile(self, file):
470 self._current_file = file
471 # Note that we always use '/' as the path separator to be
472 # consistent with svn's cygwin-style output on Windows
473 self._replacement_file = self._relpath + '/' + file
474
475 def ReplaceAndPrint(self, line):
476 print(line.replace(self._current_file, self._replacement_file))
477
478 def Filter(self, line):
479 if (line.startswith(self.index_string)):
480 self.SetCurrentFile(line[len(self.index_string):])
481 self.ReplaceAndPrint(line)
482 else:
483 if (line.startswith(self.original_prefix) or
484 line.startswith(self.working_prefix)):
485 self.ReplaceAndPrint(line)
486 else:
487 print line
488
489 filterer = DiffFilterer(self.relpath)
490 RunSVNAndFilterOutput(command, path, False, False, filterer.Filter)