[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 1 | # coding=utf8 |
[email protected] | 9799a07 | 2012-01-11 00:26:25 | [diff] [blame] | 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | """Manages a project checkout. |
| 6 | |
| 7 | Includes support for svn, git-svn and git. |
| 8 | """ |
| 9 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 10 | import ConfigParser |
| 11 | import fnmatch |
| 12 | import logging |
| 13 | import os |
| 14 | import re |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 15 | import shutil |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 16 | import subprocess |
| 17 | import sys |
| 18 | import tempfile |
| 19 | |
| 20 | import patch |
| 21 | import scm |
| 22 | import subprocess2 |
| 23 | |
| 24 | |
| 25 | def get_code_review_setting(path, key, |
| 26 | codereview_settings_file='codereview.settings'): |
| 27 | """Parses codereview.settings and return the value for the key if present. |
| 28 | |
| 29 | Don't cache the values in case the file is changed.""" |
| 30 | # TODO(maruel): Do not duplicate code. |
| 31 | settings = {} |
| 32 | try: |
| 33 | settings_file = open(os.path.join(path, codereview_settings_file), 'r') |
| 34 | try: |
| 35 | for line in settings_file.readlines(): |
| 36 | if not line or line.startswith('#'): |
| 37 | continue |
| 38 | if not ':' in line: |
| 39 | # Invalid file. |
| 40 | return None |
| 41 | k, v = line.split(':', 1) |
| 42 | settings[k.strip()] = v.strip() |
| 43 | finally: |
| 44 | settings_file.close() |
[email protected] | 004fb71 | 2011-06-21 20:02:16 | [diff] [blame] | 45 | except IOError: |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 46 | return None |
| 47 | return settings.get(key, None) |
| 48 | |
| 49 | |
| 50 | class PatchApplicationFailed(Exception): |
| 51 | """Patch failed to be applied.""" |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 52 | def __init__(self, p, status): |
| 53 | super(PatchApplicationFailed, self).__init__(p, status) |
| 54 | self.patch = p |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 55 | self.status = status |
| 56 | |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 57 | @property |
| 58 | def filename(self): |
| 59 | if self.patch: |
| 60 | return self.patch.filename |
| 61 | |
| 62 | def __str__(self): |
| 63 | out = [] |
| 64 | if self.filename: |
| 65 | out.append('Failed to apply patch for %s:' % self.filename) |
| 66 | if self.status: |
| 67 | out.append(self.status) |
| 68 | return '\n'.join(out) |
| 69 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 70 | |
| 71 | class CheckoutBase(object): |
| 72 | # Set to None to have verbose output. |
| 73 | VOID = subprocess2.VOID |
| 74 | |
[email protected] | 6ed8b50 | 2011-06-12 01:05:35 | [diff] [blame] | 75 | def __init__(self, root_dir, project_name, post_processors): |
| 76 | """ |
| 77 | Args: |
| 78 | post_processor: list of lambda(checkout, patches) to call on each of the |
| 79 | modified files. |
| 80 | """ |
[email protected] | a5129fb | 2011-06-20 18:36:25 | [diff] [blame] | 81 | super(CheckoutBase, self).__init__() |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 82 | self.root_dir = root_dir |
| 83 | self.project_name = project_name |
[email protected] | 3cdb7f3 | 2011-05-05 16:37:24 | [diff] [blame] | 84 | if self.project_name is None: |
| 85 | self.project_path = self.root_dir |
| 86 | else: |
| 87 | self.project_path = os.path.join(self.root_dir, self.project_name) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 88 | # Only used for logging purposes. |
| 89 | self._last_seen_revision = None |
[email protected] | a5129fb | 2011-06-20 18:36:25 | [diff] [blame] | 90 | self.post_processors = post_processors |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 91 | assert self.root_dir |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 92 | assert self.project_path |
| 93 | |
| 94 | def get_settings(self, key): |
| 95 | return get_code_review_setting(self.project_path, key) |
| 96 | |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 97 | def prepare(self, revision): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 98 | """Checks out a clean copy of the tree and removes any local modification. |
| 99 | |
| 100 | This function shouldn't throw unless the remote repository is inaccessible, |
| 101 | there is no free disk space or hard issues like that. |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 102 | |
| 103 | Args: |
| 104 | revision: The revision it should sync to, SCM specific. |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 105 | """ |
| 106 | raise NotImplementedError() |
| 107 | |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 108 | def apply_patch(self, patches, post_processors=None): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 109 | """Applies a patch and returns the list of modified files. |
| 110 | |
| 111 | This function should throw patch.UnsupportedPatchFormat or |
| 112 | PatchApplicationFailed when relevant. |
[email protected] | 8a1396c | 2011-04-22 00:14:24 | [diff] [blame] | 113 | |
| 114 | Args: |
| 115 | patches: patch.PatchSet object. |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 116 | """ |
| 117 | raise NotImplementedError() |
| 118 | |
| 119 | def commit(self, commit_message, user): |
| 120 | """Commits the patch upstream, while impersonating 'user'.""" |
| 121 | raise NotImplementedError() |
| 122 | |
[email protected] | bc32ad1 | 2012-07-26 13:22:47 | [diff] [blame] | 123 | def revisions(self, rev1, rev2): |
| 124 | """Returns the count of revisions from rev1 to rev2, e.g. len(]rev1, rev2]). |
| 125 | |
| 126 | If rev2 is None, it means 'HEAD'. |
| 127 | |
| 128 | Returns None if there is no link between the two. |
| 129 | """ |
| 130 | raise NotImplementedError() |
| 131 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 132 | |
| 133 | class RawCheckout(CheckoutBase): |
| 134 | """Used to apply a patch locally without any intent to commit it. |
| 135 | |
| 136 | To be used by the try server. |
| 137 | """ |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 138 | def prepare(self, revision): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 139 | """Stubbed out.""" |
| 140 | pass |
| 141 | |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 142 | def apply_patch(self, patches, post_processors=None): |
[email protected] | 8a1396c | 2011-04-22 00:14:24 | [diff] [blame] | 143 | """Ignores svn properties.""" |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 144 | post_processors = post_processors or self.post_processors or [] |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 145 | for p in patches: |
[email protected] | de800ff | 2012-09-12 19:25:24 | [diff] [blame] | 146 | logging.debug('Applying %s' % p.filename) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 147 | try: |
| 148 | stdout = '' |
| 149 | filename = os.path.join(self.project_path, p.filename) |
| 150 | if p.is_delete: |
| 151 | os.remove(filename) |
| 152 | else: |
| 153 | dirname = os.path.dirname(p.filename) |
| 154 | full_dir = os.path.join(self.project_path, dirname) |
| 155 | if dirname and not os.path.isdir(full_dir): |
| 156 | os.makedirs(full_dir) |
[email protected] | 4869bcf | 2011-06-04 01:14:32 | [diff] [blame] | 157 | |
| 158 | filepath = os.path.join(self.project_path, p.filename) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 159 | if p.is_binary: |
[email protected] | 4869bcf | 2011-06-04 01:14:32 | [diff] [blame] | 160 | with open(filepath, 'wb') as f: |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 161 | f.write(p.get()) |
| 162 | else: |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 163 | if p.source_filename: |
| 164 | if not p.is_new: |
| 165 | raise PatchApplicationFailed( |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 166 | p, |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 167 | 'File has a source filename specified but is not new') |
| 168 | # Copy the file first. |
| 169 | if os.path.isfile(filepath): |
| 170 | raise PatchApplicationFailed( |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 171 | p, 'File exist but was about to be overwriten') |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 172 | shutil.copy2( |
| 173 | os.path.join(self.project_path, p.source_filename), filepath) |
[email protected] | 58fe662 | 2011-06-03 20:59:27 | [diff] [blame] | 174 | if p.diff_hunks: |
| 175 | stdout = subprocess2.check_output( |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 176 | ['patch', '-u', '--binary', '-p%s' % p.patchlevel], |
| 177 | stdin=p.get(False), |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 178 | stderr=subprocess2.STDOUT, |
[email protected] | 58fe662 | 2011-06-03 20:59:27 | [diff] [blame] | 179 | cwd=self.project_path) |
[email protected] | 4869bcf | 2011-06-04 01:14:32 | [diff] [blame] | 180 | elif p.is_new and not os.path.exists(filepath): |
[email protected] | 58fe662 | 2011-06-03 20:59:27 | [diff] [blame] | 181 | # There is only a header. Just create the file. |
[email protected] | 4869bcf | 2011-06-04 01:14:32 | [diff] [blame] | 182 | open(filepath, 'w').close() |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 183 | for post in post_processors: |
[email protected] | 8a1396c | 2011-04-22 00:14:24 | [diff] [blame] | 184 | post(self, p) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 185 | except OSError, e: |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 186 | raise PatchApplicationFailed(p, '%s%s' % (stdout, e)) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 187 | except subprocess.CalledProcessError, e: |
| 188 | raise PatchApplicationFailed( |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 189 | p, '%s%s' % (stdout, getattr(e, 'stdout', None))) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 190 | |
| 191 | def commit(self, commit_message, user): |
| 192 | """Stubbed out.""" |
| 193 | raise NotImplementedError('RawCheckout can\'t commit') |
| 194 | |
[email protected] | bc32ad1 | 2012-07-26 13:22:47 | [diff] [blame] | 195 | def revisions(self, _rev1, _rev2): |
| 196 | return None |
| 197 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 198 | |
| 199 | class SvnConfig(object): |
| 200 | """Parses a svn configuration file.""" |
| 201 | def __init__(self, svn_config_dir=None): |
[email protected] | a5129fb | 2011-06-20 18:36:25 | [diff] [blame] | 202 | super(SvnConfig, self).__init__() |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 203 | self.svn_config_dir = svn_config_dir |
| 204 | self.default = not bool(self.svn_config_dir) |
| 205 | if not self.svn_config_dir: |
| 206 | if sys.platform == 'win32': |
| 207 | self.svn_config_dir = os.path.join(os.environ['APPDATA'], 'Subversion') |
| 208 | else: |
| 209 | self.svn_config_dir = os.path.join(os.environ['HOME'], '.subversion') |
| 210 | svn_config_file = os.path.join(self.svn_config_dir, 'config') |
| 211 | parser = ConfigParser.SafeConfigParser() |
| 212 | if os.path.isfile(svn_config_file): |
| 213 | parser.read(svn_config_file) |
| 214 | else: |
| 215 | parser.add_section('auto-props') |
| 216 | self.auto_props = dict(parser.items('auto-props')) |
| 217 | |
| 218 | |
| 219 | class SvnMixIn(object): |
| 220 | """MixIn class to add svn commands common to both svn and git-svn clients.""" |
| 221 | # These members need to be set by the subclass. |
| 222 | commit_user = None |
| 223 | commit_pwd = None |
| 224 | svn_url = None |
| 225 | project_path = None |
| 226 | # Override at class level when necessary. If used, --non-interactive is |
| 227 | # implied. |
| 228 | svn_config = SvnConfig() |
| 229 | # Set to True when non-interactivity is necessary but a custom subversion |
| 230 | # configuration directory is not necessary. |
| 231 | non_interactive = False |
| 232 | |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 233 | def _add_svn_flags(self, args, non_interactive, credentials=True): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 234 | args = ['svn'] + args |
| 235 | if not self.svn_config.default: |
| 236 | args.extend(['--config-dir', self.svn_config.svn_config_dir]) |
| 237 | if not self.svn_config.default or self.non_interactive or non_interactive: |
| 238 | args.append('--non-interactive') |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 239 | if credentials: |
| 240 | if self.commit_user: |
| 241 | args.extend(['--username', self.commit_user]) |
| 242 | if self.commit_pwd: |
| 243 | args.extend(['--password', self.commit_pwd]) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 244 | return args |
| 245 | |
| 246 | def _check_call_svn(self, args, **kwargs): |
| 247 | """Runs svn and throws an exception if the command failed.""" |
| 248 | kwargs.setdefault('cwd', self.project_path) |
| 249 | kwargs.setdefault('stdout', self.VOID) |
[email protected] | 0bcd1d3 | 2011-04-26 15:55:49 | [diff] [blame] | 250 | return subprocess2.check_call_out( |
| 251 | self._add_svn_flags(args, False), **kwargs) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 252 | |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 253 | def _check_output_svn(self, args, credentials=True, **kwargs): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 254 | """Runs svn and throws an exception if the command failed. |
| 255 | |
| 256 | Returns the output. |
| 257 | """ |
| 258 | kwargs.setdefault('cwd', self.project_path) |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 259 | return subprocess2.check_output( |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 260 | self._add_svn_flags(args, True, credentials), |
| 261 | stderr=subprocess2.STDOUT, |
| 262 | **kwargs) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 263 | |
| 264 | @staticmethod |
| 265 | def _parse_svn_info(output, key): |
| 266 | """Returns value for key from svn info output. |
| 267 | |
| 268 | Case insensitive. |
| 269 | """ |
| 270 | values = {} |
| 271 | key = key.lower() |
| 272 | for line in output.splitlines(False): |
| 273 | if not line: |
| 274 | continue |
| 275 | k, v = line.split(':', 1) |
| 276 | k = k.strip().lower() |
| 277 | v = v.strip() |
| 278 | assert not k in values |
| 279 | values[k] = v |
| 280 | return values.get(key, None) |
| 281 | |
| 282 | |
| 283 | class SvnCheckout(CheckoutBase, SvnMixIn): |
| 284 | """Manages a subversion checkout.""" |
[email protected] | 6ed8b50 | 2011-06-12 01:05:35 | [diff] [blame] | 285 | def __init__(self, root_dir, project_name, commit_user, commit_pwd, svn_url, |
| 286 | post_processors=None): |
[email protected] | a5129fb | 2011-06-20 18:36:25 | [diff] [blame] | 287 | CheckoutBase.__init__(self, root_dir, project_name, post_processors) |
| 288 | SvnMixIn.__init__(self) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 289 | self.commit_user = commit_user |
| 290 | self.commit_pwd = commit_pwd |
| 291 | self.svn_url = svn_url |
| 292 | assert bool(self.commit_user) >= bool(self.commit_pwd) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 293 | |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 294 | def prepare(self, revision): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 295 | # Will checkout if the directory is not present. |
[email protected] | 3cdb7f3 | 2011-05-05 16:37:24 | [diff] [blame] | 296 | assert self.svn_url |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 297 | if not os.path.isdir(self.project_path): |
| 298 | logging.info('Checking out %s in %s' % |
| 299 | (self.project_name, self.project_path)) |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 300 | return self._revert(revision) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 301 | |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 302 | def apply_patch(self, patches, post_processors=None): |
| 303 | post_processors = post_processors or self.post_processors or [] |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 304 | for p in patches: |
[email protected] | de800ff | 2012-09-12 19:25:24 | [diff] [blame] | 305 | logging.debug('Applying %s' % p.filename) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 306 | try: |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 307 | # It is important to use credentials=False otherwise credentials could |
| 308 | # leak in the error message. Credentials are not necessary here for the |
| 309 | # following commands anyway. |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 310 | stdout = '' |
| 311 | if p.is_delete: |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 312 | stdout += self._check_output_svn( |
| 313 | ['delete', p.filename, '--force'], credentials=False) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 314 | else: |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 315 | # svn add while creating directories otherwise svn add on the |
| 316 | # contained files will silently fail. |
| 317 | # First, find the root directory that exists. |
| 318 | dirname = os.path.dirname(p.filename) |
| 319 | dirs_to_create = [] |
| 320 | while (dirname and |
| 321 | not os.path.isdir(os.path.join(self.project_path, dirname))): |
| 322 | dirs_to_create.append(dirname) |
| 323 | dirname = os.path.dirname(dirname) |
| 324 | for dir_to_create in reversed(dirs_to_create): |
| 325 | os.mkdir(os.path.join(self.project_path, dir_to_create)) |
| 326 | stdout += self._check_output_svn( |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 327 | ['add', dir_to_create, '--force'], credentials=False) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 328 | |
[email protected] | 4869bcf | 2011-06-04 01:14:32 | [diff] [blame] | 329 | filepath = os.path.join(self.project_path, p.filename) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 330 | if p.is_binary: |
[email protected] | 4869bcf | 2011-06-04 01:14:32 | [diff] [blame] | 331 | with open(filepath, 'wb') as f: |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 332 | f.write(p.get()) |
| 333 | else: |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 334 | if p.source_filename: |
| 335 | if not p.is_new: |
| 336 | raise PatchApplicationFailed( |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 337 | p, |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 338 | 'File has a source filename specified but is not new') |
| 339 | # Copy the file first. |
| 340 | if os.path.isfile(filepath): |
| 341 | raise PatchApplicationFailed( |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 342 | p, 'File exist but was about to be overwriten') |
[email protected] | 3da8317 | 2012-05-07 16:17:20 | [diff] [blame] | 343 | self._check_output_svn( |
[email protected] | b0f852f | 2012-09-15 01:37:21 | [diff] [blame] | 344 | ['copy', p.source_filename, p.filename]) |
[email protected] | 58fe662 | 2011-06-03 20:59:27 | [diff] [blame] | 345 | if p.diff_hunks: |
| 346 | cmd = ['patch', '-p%s' % p.patchlevel, '--forward', '--force'] |
| 347 | stdout += subprocess2.check_output( |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 348 | cmd, stdin=p.get(False), cwd=self.project_path) |
[email protected] | 4869bcf | 2011-06-04 01:14:32 | [diff] [blame] | 349 | elif p.is_new and not os.path.exists(filepath): |
| 350 | # There is only a header. Just create the file if it doesn't |
| 351 | # exist. |
| 352 | open(filepath, 'w').close() |
[email protected] | 3da8317 | 2012-05-07 16:17:20 | [diff] [blame] | 353 | if p.is_new and not p.source_filename: |
| 354 | # Do not run it if p.source_filename is defined, since svn copy was |
| 355 | # using above. |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 356 | stdout += self._check_output_svn( |
| 357 | ['add', p.filename, '--force'], credentials=False) |
[email protected] | d7ca616 | 2012-08-29 17:22:22 | [diff] [blame] | 358 | for name, value in p.svn_properties: |
| 359 | if value is None: |
| 360 | stdout += self._check_output_svn( |
| 361 | ['propdel', '--quiet', name, p.filename], credentials=False) |
| 362 | else: |
| 363 | stdout += self._check_output_svn( |
| 364 | ['propset', name, value, p.filename], credentials=False) |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 365 | for prop, values in self.svn_config.auto_props.iteritems(): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 366 | if fnmatch.fnmatch(p.filename, prop): |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 367 | for value in values.split(';'): |
| 368 | if '=' not in value: |
| 369 | params = [value, '*'] |
| 370 | else: |
| 371 | params = value.split('=', 1) |
| 372 | stdout += self._check_output_svn( |
| 373 | ['propset'] + params + [p.filename], credentials=False) |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 374 | for post in post_processors: |
[email protected] | 8a1396c | 2011-04-22 00:14:24 | [diff] [blame] | 375 | post(self, p) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 376 | except OSError, e: |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 377 | raise PatchApplicationFailed(p, '%s%s' % (stdout, e)) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 378 | except subprocess.CalledProcessError, e: |
| 379 | raise PatchApplicationFailed( |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 380 | p, |
[email protected] | 9842a0c | 2011-05-30 20:41:54 | [diff] [blame] | 381 | 'While running %s;\n%s%s' % ( |
| 382 | ' '.join(e.cmd), stdout, getattr(e, 'stdout', ''))) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 383 | |
| 384 | def commit(self, commit_message, user): |
| 385 | logging.info('Committing patch for %s' % user) |
| 386 | assert self.commit_user |
[email protected] | 1bf5097 | 2011-05-05 19:57:21 | [diff] [blame] | 387 | assert isinstance(commit_message, unicode) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 388 | handle, commit_filename = tempfile.mkstemp(text=True) |
| 389 | try: |
[email protected] | 1bf5097 | 2011-05-05 19:57:21 | [diff] [blame] | 390 | # Shouldn't assume default encoding is UTF-8. But really, if you are using |
| 391 | # anything else, you are living in another world. |
| 392 | os.write(handle, commit_message.encode('utf-8')) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 393 | os.close(handle) |
| 394 | # When committing, svn won't update the Revision metadata of the checkout, |
| 395 | # so if svn commit returns "Committed revision 3.", svn info will still |
| 396 | # return "Revision: 2". Since running svn update right after svn commit |
| 397 | # creates a race condition with other committers, this code _must_ parse |
| 398 | # the output of svn commit and use a regexp to grab the revision number. |
| 399 | # Note that "Committed revision N." is localized but subprocess2 forces |
| 400 | # LANGUAGE=en. |
| 401 | args = ['commit', '--file', commit_filename] |
| 402 | # realauthor is parsed by a server-side hook. |
| 403 | if user and user != self.commit_user: |
| 404 | args.extend(['--with-revprop', 'realauthor=%s' % user]) |
| 405 | out = self._check_output_svn(args) |
| 406 | finally: |
| 407 | os.remove(commit_filename) |
| 408 | lines = filter(None, out.splitlines()) |
| 409 | match = re.match(r'^Committed revision (\d+).$', lines[-1]) |
| 410 | if not match: |
| 411 | raise PatchApplicationFailed( |
| 412 | None, |
| 413 | 'Couldn\'t make sense out of svn commit message:\n' + out) |
| 414 | return int(match.group(1)) |
| 415 | |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 416 | def _revert(self, revision): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 417 | """Reverts local modifications or checks out if the directory is not |
| 418 | present. Use depot_tools's functionality to do this. |
| 419 | """ |
| 420 | flags = ['--ignore-externals'] |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 421 | if revision: |
| 422 | flags.extend(['--revision', str(revision)]) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 423 | if not os.path.isdir(self.project_path): |
| 424 | logging.info( |
| 425 | 'Directory %s is not present, checking it out.' % self.project_path) |
| 426 | self._check_call_svn( |
| 427 | ['checkout', self.svn_url, self.project_path] + flags, cwd=None) |
| 428 | else: |
[email protected] | ea15cb7 | 2012-05-04 14:16:31 | [diff] [blame] | 429 | scm.SVN.Revert(self.project_path, no_ignore=True) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 430 | # Revive files that were deleted in scm.SVN.Revert(). |
| 431 | self._check_call_svn(['update', '--force'] + flags) |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 432 | return self._get_revision() |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 433 | |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 434 | def _get_revision(self): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 435 | out = self._check_output_svn(['info', '.']) |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 436 | revision = int(self._parse_svn_info(out, 'revision')) |
| 437 | if revision != self._last_seen_revision: |
| 438 | logging.info('Updated to revision %d' % revision) |
| 439 | self._last_seen_revision = revision |
| 440 | return revision |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 441 | |
[email protected] | bc32ad1 | 2012-07-26 13:22:47 | [diff] [blame] | 442 | def revisions(self, rev1, rev2): |
| 443 | """Returns the number of actual commits, not just the difference between |
| 444 | numbers. |
| 445 | """ |
| 446 | rev2 = rev2 or 'HEAD' |
| 447 | # Revision range is inclusive and ordering doesn't matter, they'll appear in |
| 448 | # the order specified. |
| 449 | try: |
| 450 | out = self._check_output_svn( |
| 451 | ['log', '-q', self.svn_url, '-r', '%s:%s' % (rev1, rev2)]) |
| 452 | except subprocess.CalledProcessError: |
| 453 | return None |
| 454 | # Ignore the '----' lines. |
| 455 | return len([l for l in out.splitlines() if l.startswith('r')]) - 1 |
| 456 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 457 | |
| 458 | class GitCheckoutBase(CheckoutBase): |
| 459 | """Base class for git checkout. Not to be used as-is.""" |
[email protected] | 6ed8b50 | 2011-06-12 01:05:35 | [diff] [blame] | 460 | def __init__(self, root_dir, project_name, remote_branch, |
| 461 | post_processors=None): |
| 462 | super(GitCheckoutBase, self).__init__( |
| 463 | root_dir, project_name, post_processors) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 464 | # There is no reason to not hardcode it. |
| 465 | self.remote = 'origin' |
| 466 | self.remote_branch = remote_branch |
| 467 | self.working_branch = 'working_branch' |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 468 | |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 469 | def prepare(self, revision): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 470 | """Resets the git repository in a clean state. |
| 471 | |
| 472 | Checks it out if not present and deletes the working branch. |
| 473 | """ |
[email protected] | 3cdb7f3 | 2011-05-05 16:37:24 | [diff] [blame] | 474 | assert self.remote_branch |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 475 | assert os.path.isdir(self.project_path) |
| 476 | self._check_call_git(['reset', '--hard', '--quiet']) |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 477 | if revision: |
| 478 | try: |
| 479 | revision = self._check_output_git(['rev-parse', revision]) |
| 480 | except subprocess.CalledProcessError: |
| 481 | self._check_call_git( |
| 482 | ['fetch', self.remote, self.remote_branch, '--quiet']) |
| 483 | revision = self._check_output_git(['rev-parse', revision]) |
| 484 | self._check_call_git(['checkout', '--force', '--quiet', revision]) |
| 485 | else: |
| 486 | branches, active = self._branches() |
| 487 | if active != 'master': |
| 488 | self._check_call_git(['checkout', '--force', '--quiet', 'master']) |
| 489 | self._check_call_git(['pull', self.remote, self.remote_branch, '--quiet']) |
| 490 | if self.working_branch in branches: |
| 491 | self._call_git(['branch', '-D', self.working_branch]) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 492 | |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 493 | def apply_patch(self, patches, post_processors=None): |
[email protected] | 8a1396c | 2011-04-22 00:14:24 | [diff] [blame] | 494 | """Applies a patch on 'working_branch' and switch to it. |
| 495 | |
| 496 | Also commits the changes on the local branch. |
| 497 | |
| 498 | Ignores svn properties and raise an exception on unexpected ones. |
| 499 | """ |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 500 | post_processors = post_processors or self.post_processors or [] |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 501 | # It this throws, the checkout is corrupted. Maybe worth deleting it and |
| 502 | # trying again? |
[email protected] | 3cdb7f3 | 2011-05-05 16:37:24 | [diff] [blame] | 503 | if self.remote_branch: |
| 504 | self._check_call_git( |
| 505 | ['checkout', '-b', self.working_branch, |
| 506 | '%s/%s' % (self.remote, self.remote_branch), '--quiet']) |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 507 | for index, p in enumerate(patches): |
[email protected] | de800ff | 2012-09-12 19:25:24 | [diff] [blame] | 508 | logging.debug('Applying %s' % p.filename) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 509 | try: |
| 510 | stdout = '' |
| 511 | if p.is_delete: |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 512 | if (not os.path.exists(p.filename) and |
| 513 | any(p1.source_filename == p.filename for p1 in patches[0:index])): |
| 514 | # The file could already be deleted if a prior patch with file |
| 515 | # rename was already processed. To be sure, look at all the previous |
| 516 | # patches to see if they were a file rename. |
| 517 | pass |
| 518 | else: |
| 519 | stdout += self._check_output_git(['rm', p.filename]) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 520 | else: |
| 521 | dirname = os.path.dirname(p.filename) |
| 522 | full_dir = os.path.join(self.project_path, dirname) |
| 523 | if dirname and not os.path.isdir(full_dir): |
| 524 | os.makedirs(full_dir) |
| 525 | if p.is_binary: |
| 526 | with open(os.path.join(self.project_path, p.filename), 'wb') as f: |
| 527 | f.write(p.get()) |
| 528 | stdout += self._check_output_git(['add', p.filename]) |
| 529 | else: |
[email protected] | 58fe662 | 2011-06-03 20:59:27 | [diff] [blame] | 530 | # No need to do anything special with p.is_new or if not |
| 531 | # p.diff_hunks. git apply manages all that already. |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 532 | stdout += self._check_output_git( |
[email protected] | 5e97563 | 2011-09-29 18:07:06 | [diff] [blame] | 533 | ['apply', '--index', '-p%s' % p.patchlevel], stdin=p.get(True)) |
[email protected] | d7ca616 | 2012-08-29 17:22:22 | [diff] [blame] | 534 | for name, _ in p.svn_properties: |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 535 | # Ignore some known auto-props flags through .subversion/config, |
| 536 | # bails out on the other ones. |
| 537 | # TODO(maruel): Read ~/.subversion/config and detect the rules that |
| 538 | # applies here to figure out if the property will be correctly |
| 539 | # handled. |
[email protected] | d7ca616 | 2012-08-29 17:22:22 | [diff] [blame] | 540 | if not name in ( |
[email protected] | 9799a07 | 2012-01-11 00:26:25 | [diff] [blame] | 541 | 'svn:eol-style', 'svn:executable', 'svn:mime-type'): |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 542 | raise patch.UnsupportedPatchFormat( |
| 543 | p.filename, |
| 544 | 'Cannot apply svn property %s to file %s.' % ( |
[email protected] | d7ca616 | 2012-08-29 17:22:22 | [diff] [blame] | 545 | name, p.filename)) |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 546 | for post in post_processors: |
[email protected] | 8a1396c | 2011-04-22 00:14:24 | [diff] [blame] | 547 | post(self, p) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 548 | except OSError, e: |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 549 | raise PatchApplicationFailed(p, '%s%s' % (stdout, e)) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 550 | except subprocess.CalledProcessError, e: |
| 551 | raise PatchApplicationFailed( |
[email protected] | 34f6855 | 2012-05-09 19:18:36 | [diff] [blame] | 552 | p, '%s%s' % (stdout, getattr(e, 'stdout', None))) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 553 | # Once all the patches are processed and added to the index, commit the |
| 554 | # index. |
| 555 | self._check_call_git(['commit', '-m', 'Committed patch']) |
| 556 | # TODO(maruel): Weirdly enough they don't match, need to investigate. |
| 557 | #found_files = self._check_output_git( |
| 558 | # ['diff', 'master', '--name-only']).splitlines(False) |
| 559 | #assert sorted(patches.filenames) == sorted(found_files), ( |
| 560 | # sorted(out), sorted(found_files)) |
| 561 | |
| 562 | def commit(self, commit_message, user): |
| 563 | """Updates the commit message. |
| 564 | |
| 565 | Subclass needs to dcommit or push. |
| 566 | """ |
[email protected] | 1bf5097 | 2011-05-05 19:57:21 | [diff] [blame] | 567 | assert isinstance(commit_message, unicode) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 568 | self._check_call_git(['commit', '--amend', '-m', commit_message]) |
| 569 | return self._check_output_git(['rev-parse', 'HEAD']).strip() |
| 570 | |
| 571 | def _check_call_git(self, args, **kwargs): |
| 572 | kwargs.setdefault('cwd', self.project_path) |
| 573 | kwargs.setdefault('stdout', self.VOID) |
[email protected] | 0bcd1d3 | 2011-04-26 15:55:49 | [diff] [blame] | 574 | return subprocess2.check_call_out(['git'] + args, **kwargs) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 575 | |
| 576 | def _call_git(self, args, **kwargs): |
| 577 | """Like check_call but doesn't throw on failure.""" |
| 578 | kwargs.setdefault('cwd', self.project_path) |
| 579 | kwargs.setdefault('stdout', self.VOID) |
| 580 | return subprocess2.call(['git'] + args, **kwargs) |
| 581 | |
| 582 | def _check_output_git(self, args, **kwargs): |
| 583 | kwargs.setdefault('cwd', self.project_path) |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 584 | return subprocess2.check_output( |
| 585 | ['git'] + args, stderr=subprocess2.STDOUT, **kwargs) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 586 | |
| 587 | def _branches(self): |
| 588 | """Returns the list of branches and the active one.""" |
| 589 | out = self._check_output_git(['branch']).splitlines(False) |
| 590 | branches = [l[2:] for l in out] |
| 591 | active = None |
| 592 | for l in out: |
| 593 | if l.startswith('*'): |
| 594 | active = l[2:] |
| 595 | break |
| 596 | return branches, active |
| 597 | |
[email protected] | bc32ad1 | 2012-07-26 13:22:47 | [diff] [blame] | 598 | def revisions(self, rev1, rev2): |
| 599 | """Returns the number of actual commits between both hash.""" |
| 600 | self._fetch_remote() |
| 601 | |
| 602 | rev2 = rev2 or '%s/%s' % (self.remote, self.remote_branch) |
| 603 | # Revision range is ]rev1, rev2] and ordering matters. |
| 604 | try: |
| 605 | out = self._check_output_git( |
| 606 | ['log', '--format="%H"' , '%s..%s' % (rev1, rev2)]) |
| 607 | except subprocess.CalledProcessError: |
| 608 | return None |
| 609 | return len(out.splitlines()) |
| 610 | |
| 611 | def _fetch_remote(self): |
| 612 | """Fetches the remote without rebasing.""" |
| 613 | raise NotImplementedError() |
| 614 | |
| 615 | |
| 616 | class GitCheckout(GitCheckoutBase): |
| 617 | """Git checkout implementation.""" |
| 618 | def _fetch_remote(self): |
| 619 | # git fetch is always verbose even with -q -q so redirect its output. |
| 620 | self._check_output_git(['fetch', self.remote, self.remote_branch]) |
| 621 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 622 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 623 | class ReadOnlyCheckout(object): |
| 624 | """Converts a checkout into a read-only one.""" |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 625 | def __init__(self, checkout, post_processors=None): |
[email protected] | a5129fb | 2011-06-20 18:36:25 | [diff] [blame] | 626 | super(ReadOnlyCheckout, self).__init__() |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 627 | self.checkout = checkout |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 628 | self.post_processors = (post_processors or []) + ( |
| 629 | self.checkout.post_processors or []) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 630 | |
[email protected] | 5191977 | 2011-06-12 01:27:42 | [diff] [blame] | 631 | def prepare(self, revision): |
| 632 | return self.checkout.prepare(revision) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 633 | |
| 634 | def get_settings(self, key): |
| 635 | return self.checkout.get_settings(key) |
| 636 | |
[email protected] | b1d1a78 | 2011-09-29 14:13:55 | [diff] [blame] | 637 | def apply_patch(self, patches, post_processors=None): |
| 638 | return self.checkout.apply_patch( |
| 639 | patches, post_processors or self.post_processors) |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 640 | |
| 641 | def commit(self, message, user): # pylint: disable=R0201 |
| 642 | logging.info('Would have committed for %s with message: %s' % ( |
| 643 | user, message)) |
| 644 | return 'FAKE' |
| 645 | |
[email protected] | bc32ad1 | 2012-07-26 13:22:47 | [diff] [blame] | 646 | def revisions(self, rev1, rev2): |
| 647 | return self.checkout.revisions(rev1, rev2) |
| 648 | |
[email protected] | dfaecd2 | 2011-04-21 00:33:31 | [diff] [blame] | 649 | @property |
| 650 | def project_name(self): |
| 651 | return self.checkout.project_name |
| 652 | |
| 653 | @property |
| 654 | def project_path(self): |
| 655 | return self.checkout.project_path |