blob: a9c537b9c2baf0b283f230815cfdeb1d5282cb54 [file] [log] [blame]
maruel@chromium.org261eeb52009-11-16 18:25:45 +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.
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000014
maruel@chromium.orgd5800f12009-11-12 20:03:43 +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
maruel@chromium.org261eeb52009-11-16 18:25:45 +000021import sys
22import xml.dom.minidom
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000023
24import gclient_utils
maruel@chromium.org261eeb52009-11-16 18:25:45 +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
maruel@chromium.org261eeb52009-11-16 18:25:45 +000033
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
maruel@chromium.org261eeb52009-11-16 18:25:45 +000096class GitWrapper(SCMWrapper):
msb@chromium.orge28e4982009-09-25 20:51:45 +000097 """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'
maruel@chromium.org261eeb52009-11-16 18:25:45 +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'
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000108 merge_base = self._RunGit(['merge-base', 'HEAD', 'origin'])
109 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)
maruel@chromium.org261eeb52009-11-16 18:25:45 +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.orgac915bb2009-11-13 17:03:01 +0000132 url, revision = gclient_utils.SplitUrlRevision(self.url)
133 rev_str = ""
msb@chromium.orge28e4982009-09-25 20:51:45 +0000134 if options.revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000135 # Override the revision number.
136 revision = str(options.revision)
137 if revision:
138 url = '%s@%s' % (url, revision)
139 rev_str = ' at %s' % revision
msb@chromium.orge28e4982009-09-25 20:51:45 +0000140
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000141 if options.verbose:
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000142 print("\n_____ %s%s" % (self.relpath, rev_str))
143
msb@chromium.orge28e4982009-09-25 20:51:45 +0000144 if not os.path.exists(self.checkout_path):
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000145 self._RunGit(['clone', url, self.checkout_path],
146 cwd=self._root_dir, redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000147 if revision:
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000148 self._RunGit(['reset', '--hard', revision], redirect_stdout=False)
149 files = self._RunGit(['ls-files']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000150 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
151 return
152
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000153 self._RunGit(['remote', 'update'], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000154 new_base = 'origin'
155 if revision:
156 new_base = revision
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000157 files = self._RunGit(['diff', new_base, '--name-only']).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000158 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000159 self._RunGit(['rebase', '-v', new_base], redirect_stdout=False)
msb@chromium.orgb1a22bf2009-11-07 02:33:50 +0000160 print "Checked out revision %s." % self.revinfo(options, (), None)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000161
162 def revert(self, options, args, file_list):
163 """Reverts local modifications.
164
165 All reverted files will be appended to file_list.
166 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000167 __pychecker__ = 'unusednames=args'
msb@chromium.org260c6532009-10-28 03:22:35 +0000168 path = os.path.join(self._root_dir, self.relpath)
169 if not os.path.isdir(path):
170 # revert won't work if the directory doesn't exist. It needs to
171 # checkout instead.
172 print("\n_____ %s is missing, synching instead" % self.relpath)
173 # Don't reuse the args.
174 return self.update(options, [], file_list)
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000175 merge_base = self._RunGit(['merge-base', 'HEAD', 'origin'])
176 files = self._RunGit(['diff', merge_base, '--name-only']).split()
177 self._RunGit(['reset', '--hard', merge_base], redirect_stdout=False)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000178 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
179
msb@chromium.org0f282062009-11-06 20:14:02 +0000180 def revinfo(self, options, args, file_list):
181 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000182 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000183 return self._RunGit(['rev-parse', 'HEAD'])
msb@chromium.org0f282062009-11-06 20:14:02 +0000184
msb@chromium.orge28e4982009-09-25 20:51:45 +0000185 def runhooks(self, options, args, file_list):
186 self.status(options, args, file_list)
187
188 def status(self, options, args, file_list):
189 """Display status information."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000190 __pychecker__ = 'unusednames=args,options'
msb@chromium.orge28e4982009-09-25 20:51:45 +0000191 if not os.path.isdir(self.checkout_path):
192 print('\n________ couldn\'t run status in %s:\nThe directory '
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000193 'does not exist.' % self.checkout_path)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000194 else:
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000195 merge_base = self._RunGit(['merge-base', 'HEAD', 'origin'])
196 self._RunGit(['diff', '--name-status', merge_base], redirect_stdout=False)
197 files = self._RunGit(['diff', '--name-only', merge_base]).split()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000198 file_list.extend([os.path.join(self.checkout_path, f) for f in files])
199
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000200 def _RunGit(self, args, cwd=None, checkrc=True, redirect_stdout=True):
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000201 stdout=None
202 if redirect_stdout:
203 stdout=subprocess.PIPE
msb@chromium.orge28e4982009-09-25 20:51:45 +0000204 if cwd == None:
205 cwd = self.checkout_path
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000206 cmd = ['git']
msb@chromium.orge28e4982009-09-25 20:51:45 +0000207 cmd.extend(args)
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000208 sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout)
msb@chromium.orge28e4982009-09-25 20:51:45 +0000209 if checkrc and sp.returncode:
210 raise gclient_utils.Error('git command %s returned %d' %
211 (args[0], sp.returncode))
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000212 output = sp.communicate()[0]
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000213 if output != None:
msb@chromium.orge8e60e52009-11-02 21:50:56 +0000214 return output.strip()
msb@chromium.orge28e4982009-09-25 20:51:45 +0000215
216
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000217class SVNWrapper(SCMWrapper):
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000218 """ Wrapper for SVN """
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000219
220 def cleanup(self, options, args, file_list):
221 """Cleanup working copy."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000222 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000223 command = ['cleanup']
224 command.extend(args)
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000225 RunSVN(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000226
227 def diff(self, options, args, file_list):
228 # NOTE: This function does not currently modify file_list.
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000229 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000230 command = ['diff']
231 command.extend(args)
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000232 RunSVN(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000233
234 def export(self, options, args, file_list):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000235 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000236 assert len(args) == 1
237 export_path = os.path.abspath(os.path.join(args[0], self.relpath))
238 try:
239 os.makedirs(export_path)
240 except OSError:
241 pass
242 assert os.path.exists(export_path)
243 command = ['export', '--force', '.']
244 command.append(export_path)
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000245 RunSVN(command, os.path.join(self._root_dir, self.relpath))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000246
247 def update(self, options, args, file_list):
248 """Runs SCM to update or transparently checkout the working copy.
249
250 All updated files will be appended to file_list.
251
252 Raises:
253 Error: if can't get URL for relative path.
254 """
255 # Only update if git is not controlling the directory.
256 checkout_path = os.path.join(self._root_dir, self.relpath)
257 git_path = os.path.join(self._root_dir, self.relpath, '.git')
258 if os.path.exists(git_path):
259 print("________ found .git directory; skipping %s" % self.relpath)
260 return
261
262 if args:
263 raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
264
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000265 url, revision = gclient_utils.SplitUrlRevision(self.url)
266 base_url = url
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000267 forced_revision = False
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000268 rev_str = ""
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000269 if options.revision:
270 # Override the revision number.
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000271 revision = str(options.revision)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000272 if revision:
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000273 forced_revision = True
274 url = '%s@%s' % (url, revision)
msb@chromium.org770ff9e2009-09-23 17:18:18 +0000275 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000276
277 if not os.path.exists(checkout_path):
278 # We need to checkout.
279 command = ['checkout', url, checkout_path]
280 if revision:
281 command.extend(['--revision', str(revision)])
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000282 RunSVNAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000283 return
284
285 # Get the existing scm url and the revision number of the current checkout.
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000286 from_info = CaptureSVNInfo(os.path.join(checkout_path, '.'), '.')
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000287 if not from_info:
288 raise gclient_utils.Error("Can't update/checkout %r if an unversioned "
289 "directory is present. Delete the directory "
290 "and try again." %
291 checkout_path)
292
maruel@chromium.org7753d242009-10-07 17:40:24 +0000293 if options.manually_grab_svn_rev:
294 # Retrieve the current HEAD version because svn is slow at null updates.
295 if not revision:
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000296 from_info_live = CaptureSVNInfo(from_info['URL'], '.')
maruel@chromium.org7753d242009-10-07 17:40:24 +0000297 revision = str(from_info_live['Revision'])
298 rev_str = ' at %s' % revision
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000299
msb@chromium.orgac915bb2009-11-13 17:03:01 +0000300 if from_info['URL'] != base_url:
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000301 to_info = CaptureSVNInfo(url, '.')
maruel@chromium.orge2ce0c72009-09-23 16:14:18 +0000302 if not to_info.get('Repository Root') or not to_info.get('UUID'):
303 # The url is invalid or the server is not accessible, it's safer to bail
304 # out right now.
305 raise gclient_utils.Error('This url is unreachable: %s' % url)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000306 can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
307 and (from_info['UUID'] == to_info['UUID']))
308 if can_switch:
309 print("\n_____ relocating %s to a new checkout" % self.relpath)
310 # We have different roots, so check if we can switch --relocate.
311 # Subversion only permits this if the repository UUIDs match.
312 # Perform the switch --relocate, then rewrite the from_url
313 # to reflect where we "are now." (This is the same way that
314 # Subversion itself handles the metadata when switch --relocate
315 # is used.) This makes the checks below for whether we
316 # can update to a revision or have to switch to a different
317 # branch work as expected.
318 # TODO(maruel): TEST ME !
319 command = ["switch", "--relocate",
320 from_info['Repository Root'],
321 to_info['Repository Root'],
322 self.relpath]
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000323 RunSVN(command, self._root_dir)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000324 from_info['URL'] = from_info['URL'].replace(
325 from_info['Repository Root'],
326 to_info['Repository Root'])
327 else:
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000328 if CaptureSVNStatus(checkout_path):
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000329 raise gclient_utils.Error("Can't switch the checkout to %s; UUID "
330 "don't match and there is local changes "
331 "in %s. Delete the directory and "
332 "try again." % (url, checkout_path))
333 # Ok delete it.
334 print("\n_____ switching %s to a new checkout" % self.relpath)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000335 gclient_utils.RemoveDirectory(checkout_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000336 # We need to checkout.
337 command = ['checkout', url, checkout_path]
338 if revision:
339 command.extend(['--revision', str(revision)])
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000340 RunSVNAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000341 return
342
343
344 # If the provided url has a revision number that matches the revision
345 # number of the existing directory, then we don't need to bother updating.
maruel@chromium.org2e0c6852009-09-24 00:02:07 +0000346 if not options.force and str(from_info['Revision']) == revision:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000347 if options.verbose or not forced_revision:
348 print("\n_____ %s%s" % (self.relpath, rev_str))
349 return
350
351 command = ["update", checkout_path]
352 if revision:
353 command.extend(['--revision', str(revision)])
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000354 RunSVNAndGetFileList(options, command, self._root_dir, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000355
356 def revert(self, options, args, file_list):
357 """Reverts local modifications. Subversion specific.
358
359 All reverted files will be appended to file_list, even if Subversion
360 doesn't know about them.
361 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000362 __pychecker__ = 'unusednames=args'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000363 path = os.path.join(self._root_dir, self.relpath)
364 if not os.path.isdir(path):
365 # svn revert won't work if the directory doesn't exist. It needs to
366 # checkout instead.
367 print("\n_____ %s is missing, synching instead" % self.relpath)
368 # Don't reuse the args.
369 return self.update(options, [], file_list)
370
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000371 for file_status in CaptureSVNStatus(path):
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000372 file_path = os.path.join(path, file_status[1])
373 if file_status[0][0] == 'X':
maruel@chromium.org754960e2009-09-21 12:31:05 +0000374 # Ignore externals.
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000375 logging.info('Ignoring external %s' % file_path)
maruel@chromium.org754960e2009-09-21 12:31:05 +0000376 continue
377
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000378 if logging.getLogger().isEnabledFor(logging.INFO):
379 logging.info('%s%s' % (file[0], file[1]))
380 else:
381 print(file_path)
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000382 if file_status[0].isspace():
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000383 logging.error('No idea what is the status of %s.\n'
384 'You just found a bug in gclient, please ping '
385 'maruel@chromium.org ASAP!' % file_path)
386 # svn revert is really stupid. It fails on inconsistent line-endings,
387 # on switched directories, etc. So take no chance and delete everything!
388 try:
389 if not os.path.exists(file_path):
390 pass
391 elif os.path.isfile(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000392 logging.info('os.remove(%s)' % file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000393 os.remove(file_path)
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000394 elif os.path.isdir(file_path):
maruel@chromium.org754960e2009-09-21 12:31:05 +0000395 logging.info('gclient_utils.RemoveDirectory(%s)' % file_path)
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +0000396 gclient_utils.RemoveDirectory(file_path)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000397 else:
maruel@chromium.orgaa3dd472009-09-21 19:02:48 +0000398 logging.error('no idea what is %s.\nYou just found a bug in gclient'
399 ', please ping maruel@chromium.org ASAP!' % file_path)
400 except EnvironmentError:
401 logging.error('Failed to remove %s.' % file_path)
402
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000403 try:
404 # svn revert is so broken we don't even use it. Using
405 # "svn up --revision BASE" achieve the same effect.
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000406 RunSVNAndGetFileList(options, ['update', '--revision', 'BASE'], path,
maruel@chromium.org810a50b2009-10-05 23:03:18 +0000407 file_list)
408 except OSError, e:
409 # Maybe the directory disapeared meanwhile. We don't want it to throw an
410 # exception.
411 logging.error('Failed to update:\n%s' % str(e))
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000412
msb@chromium.org0f282062009-11-06 20:14:02 +0000413 def revinfo(self, options, args, file_list):
414 """Display revision"""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000415 __pychecker__ = 'unusednames=args,file_list,options'
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000416 return CaptureSVNHeadRevision(self.url)
msb@chromium.org0f282062009-11-06 20:14:02 +0000417
msb@chromium.orgcb5442b2009-09-22 16:51:24 +0000418 def runhooks(self, options, args, file_list):
419 self.status(options, args, file_list)
420
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000421 def status(self, options, args, file_list):
422 """Display status information."""
423 path = os.path.join(self._root_dir, self.relpath)
424 command = ['status']
425 command.extend(args)
426 if not os.path.isdir(path):
427 # svn status won't work if the directory doesn't exist.
428 print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory "
429 "does not exist."
430 % (' '.join(command), path))
431 # There's no file list to retrieve.
432 else:
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000433 RunSVNAndGetFileList(options, command, path, file_list)
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000434
435 def pack(self, options, args, file_list):
436 """Generates a patch file which can be applied to the root of the
437 repository."""
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000438 __pychecker__ = 'unusednames=file_list,options'
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000439 path = os.path.join(self._root_dir, self.relpath)
440 command = ['diff']
441 command.extend(args)
442 # Simple class which tracks which file is being diffed and
443 # replaces instances of its file name in the original and
444 # working copy lines of the svn diff output.
445 class DiffFilterer(object):
446 index_string = "Index: "
447 original_prefix = "--- "
448 working_prefix = "+++ "
449
450 def __init__(self, relpath):
451 # Note that we always use '/' as the path separator to be
452 # consistent with svn's cygwin-style output on Windows
453 self._relpath = relpath.replace("\\", "/")
454 self._current_file = ""
455 self._replacement_file = ""
456
457 def SetCurrentFile(self, file):
458 self._current_file = file
459 # Note that we always use '/' as the path separator to be
460 # consistent with svn's cygwin-style output on Windows
461 self._replacement_file = self._relpath + '/' + file
462
463 def ReplaceAndPrint(self, line):
464 print(line.replace(self._current_file, self._replacement_file))
465
466 def Filter(self, line):
467 if (line.startswith(self.index_string)):
468 self.SetCurrentFile(line[len(self.index_string):])
469 self.ReplaceAndPrint(line)
470 else:
471 if (line.startswith(self.original_prefix) or
472 line.startswith(self.working_prefix)):
473 self.ReplaceAndPrint(line)
474 else:
475 print line
476
477 filterer = DiffFilterer(self.relpath)
maruel@chromium.org261eeb52009-11-16 18:25:45 +0000478 RunSVNAndFilterOutput(command, path, False, False, filterer.Filter)