checkout.py 27.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# coding=utf8
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Manages a project checkout.

Includes support for svn, git-svn and git.
"""

from __future__ import with_statement
import ConfigParser
import fnmatch
import logging
import os
import re
16
import shutil
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
import subprocess
import sys
import tempfile

import patch
import scm
import subprocess2


def get_code_review_setting(path, key,
    codereview_settings_file='codereview.settings'):
  """Parses codereview.settings and return the value for the key if present.

  Don't cache the values in case the file is changed."""
  # TODO(maruel): Do not duplicate code.
  settings = {}
  try:
    settings_file = open(os.path.join(path, codereview_settings_file), 'r')
    try:
      for line in settings_file.readlines():
        if not line or line.startswith('#'):
          continue
        if not ':' in line:
          # Invalid file.
          return None
        k, v = line.split(':', 1)
        settings[k.strip()] = v.strip()
    finally:
      settings_file.close()
46
  except IOError:
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    return None
  return settings.get(key, None)


class PatchApplicationFailed(Exception):
  """Patch failed to be applied."""
  def __init__(self, filename, status):
    super(PatchApplicationFailed, self).__init__(filename, status)
    self.filename = filename
    self.status = status


class CheckoutBase(object):
  # Set to None to have verbose output.
  VOID = subprocess2.VOID

63 64 65 66 67 68
  def __init__(self, root_dir, project_name, post_processors):
    """
    Args:
      post_processor: list of lambda(checkout, patches) to call on each of the
                      modified files.
    """
69
    super(CheckoutBase, self).__init__()
70 71
    self.root_dir = root_dir
    self.project_name = project_name
72 73 74 75
    if self.project_name is None:
      self.project_path = self.root_dir
    else:
      self.project_path = os.path.join(self.root_dir, self.project_name)
76 77
    # Only used for logging purposes.
    self._last_seen_revision = None
78
    self.post_processors = post_processors
79 80 81 82 83 84
    assert self.root_dir
    assert self.project_path

  def get_settings(self, key):
    return get_code_review_setting(self.project_path, key)

85
  def prepare(self, revision):
86 87 88 89
    """Checks out a clean copy of the tree and removes any local modification.

    This function shouldn't throw unless the remote repository is inaccessible,
    there is no free disk space or hard issues like that.
90 91 92

    Args:
      revision: The revision it should sync to, SCM specific.
93 94 95
    """
    raise NotImplementedError()

96
  def apply_patch(self, patches, post_processors=None):
97 98 99 100
    """Applies a patch and returns the list of modified files.

    This function should throw patch.UnsupportedPatchFormat or
    PatchApplicationFailed when relevant.
101 102 103

    Args:
      patches: patch.PatchSet object.
104 105 106 107 108 109 110 111 112 113 114 115 116
    """
    raise NotImplementedError()

  def commit(self, commit_message, user):
    """Commits the patch upstream, while impersonating 'user'."""
    raise NotImplementedError()


class RawCheckout(CheckoutBase):
  """Used to apply a patch locally without any intent to commit it.

  To be used by the try server.
  """
117
  def prepare(self, revision):
118 119 120
    """Stubbed out."""
    pass

121
  def apply_patch(self, patches, post_processors=None):
122
    """Ignores svn properties."""
123
    post_processors = post_processors or self.post_processors or []
124 125 126 127 128 129 130 131 132 133 134
    for p in patches:
      try:
        stdout = ''
        filename = os.path.join(self.project_path, p.filename)
        if p.is_delete:
          os.remove(filename)
        else:
          dirname = os.path.dirname(p.filename)
          full_dir = os.path.join(self.project_path, dirname)
          if dirname and not os.path.isdir(full_dir):
            os.makedirs(full_dir)
135 136

          filepath = os.path.join(self.project_path, p.filename)
137
          if p.is_binary:
138
            with open(filepath, 'wb') as f:
139 140
              f.write(p.get())
          else:
141 142 143 144 145 146 147 148 149 150 151
            if p.source_filename:
              if not p.is_new:
                raise PatchApplicationFailed(
                    p.filename,
                    'File has a source filename specified but is not new')
              # Copy the file first.
              if os.path.isfile(filepath):
                raise PatchApplicationFailed(
                    p.filename, 'File exist but was about to be overwriten')
              shutil.copy2(
                  os.path.join(self.project_path, p.source_filename), filepath)
152 153
            if p.diff_hunks:
              stdout = subprocess2.check_output(
154 155
                  ['patch', '-u', '--binary', '-p%s' % p.patchlevel],
                  stdin=p.get(False),
156
                  stderr=subprocess2.STDOUT,
157
                  cwd=self.project_path)
158
            elif p.is_new and not os.path.exists(filepath):
159
              # There is only a header. Just create the file.
160
              open(filepath, 'w').close()
161
        for post in post_processors:
162
          post(self, p)
163 164 165 166 167 168 169 170 171 172 173 174 175 176
      except OSError, e:
        raise PatchApplicationFailed(p.filename, '%s%s' % (stdout, e))
      except subprocess.CalledProcessError, e:
        raise PatchApplicationFailed(
            p.filename, '%s%s' % (stdout, getattr(e, 'stdout', None)))

  def commit(self, commit_message, user):
    """Stubbed out."""
    raise NotImplementedError('RawCheckout can\'t commit')


class SvnConfig(object):
  """Parses a svn configuration file."""
  def __init__(self, svn_config_dir=None):
177
    super(SvnConfig, self).__init__()
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    self.svn_config_dir = svn_config_dir
    self.default = not bool(self.svn_config_dir)
    if not self.svn_config_dir:
      if sys.platform == 'win32':
        self.svn_config_dir = os.path.join(os.environ['APPDATA'], 'Subversion')
      else:
        self.svn_config_dir = os.path.join(os.environ['HOME'], '.subversion')
    svn_config_file = os.path.join(self.svn_config_dir, 'config')
    parser = ConfigParser.SafeConfigParser()
    if os.path.isfile(svn_config_file):
      parser.read(svn_config_file)
    else:
      parser.add_section('auto-props')
    self.auto_props = dict(parser.items('auto-props'))


class SvnMixIn(object):
  """MixIn class to add svn commands common to both svn and git-svn clients."""
  # These members need to be set by the subclass.
  commit_user = None
  commit_pwd = None
  svn_url = None
  project_path = None
  # Override at class level when necessary. If used, --non-interactive is
  # implied.
  svn_config = SvnConfig()
  # Set to True when non-interactivity is necessary but a custom subversion
  # configuration directory is not necessary.
  non_interactive = False

208
  def _add_svn_flags(self, args, non_interactive, credentials=True):
209 210 211 212 213
    args = ['svn'] + args
    if not self.svn_config.default:
      args.extend(['--config-dir', self.svn_config.svn_config_dir])
    if not self.svn_config.default or self.non_interactive or non_interactive:
      args.append('--non-interactive')
214 215 216 217 218
    if credentials:
      if self.commit_user:
        args.extend(['--username', self.commit_user])
      if self.commit_pwd:
        args.extend(['--password', self.commit_pwd])
219 220 221 222 223 224
    return args

  def _check_call_svn(self, args, **kwargs):
    """Runs svn and throws an exception if the command failed."""
    kwargs.setdefault('cwd', self.project_path)
    kwargs.setdefault('stdout', self.VOID)
225 226
    return subprocess2.check_call_out(
        self._add_svn_flags(args, False), **kwargs)
227

228
  def _check_output_svn(self, args, credentials=True, **kwargs):
229 230 231 232 233
    """Runs svn and throws an exception if the command failed.

     Returns the output.
    """
    kwargs.setdefault('cwd', self.project_path)
234
    return subprocess2.check_output(
235 236 237
        self._add_svn_flags(args, True, credentials),
        stderr=subprocess2.STDOUT,
        **kwargs)
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

  @staticmethod
  def _parse_svn_info(output, key):
    """Returns value for key from svn info output.

    Case insensitive.
    """
    values = {}
    key = key.lower()
    for line in output.splitlines(False):
      if not line:
        continue
      k, v = line.split(':', 1)
      k = k.strip().lower()
      v = v.strip()
      assert not k in values
      values[k] = v
    return values.get(key, None)


class SvnCheckout(CheckoutBase, SvnMixIn):
  """Manages a subversion checkout."""
260 261
  def __init__(self, root_dir, project_name, commit_user, commit_pwd, svn_url,
      post_processors=None):
262 263
    CheckoutBase.__init__(self, root_dir, project_name, post_processors)
    SvnMixIn.__init__(self)
264 265 266 267 268
    self.commit_user = commit_user
    self.commit_pwd = commit_pwd
    self.svn_url = svn_url
    assert bool(self.commit_user) >= bool(self.commit_pwd)

269
  def prepare(self, revision):
270
    # Will checkout if the directory is not present.
271
    assert self.svn_url
272 273 274
    if not os.path.isdir(self.project_path):
      logging.info('Checking out %s in %s' %
          (self.project_name, self.project_path))
275
    return self._revert(revision)
276

277 278
  def apply_patch(self, patches, post_processors=None):
    post_processors = post_processors or self.post_processors or []
279 280
    for p in patches:
      try:
281 282 283
        # It is important to use credentials=False otherwise credentials could
        # leak in the error message. Credentials are not necessary here for the
        # following commands anyway.
284 285
        stdout = ''
        if p.is_delete:
286 287
          stdout += self._check_output_svn(
              ['delete', p.filename, '--force'], credentials=False)
288 289 290 291 292 293 294 295 296 297 298 299 300
        else:
          # svn add while creating directories otherwise svn add on the
          # contained files will silently fail.
          # First, find the root directory that exists.
          dirname = os.path.dirname(p.filename)
          dirs_to_create = []
          while (dirname and
              not os.path.isdir(os.path.join(self.project_path, dirname))):
            dirs_to_create.append(dirname)
            dirname = os.path.dirname(dirname)
          for dir_to_create in reversed(dirs_to_create):
            os.mkdir(os.path.join(self.project_path, dir_to_create))
            stdout += self._check_output_svn(
301
                ['add', dir_to_create, '--force'], credentials=False)
302

303
          filepath = os.path.join(self.project_path, p.filename)
304
          if p.is_binary:
305
            with open(filepath, 'wb') as f:
306 307
              f.write(p.get())
          else:
308 309 310 311 312 313 314 315 316 317 318
            if p.source_filename:
              if not p.is_new:
                raise PatchApplicationFailed(
                    p.filename,
                    'File has a source filename specified but is not new')
              # Copy the file first.
              if os.path.isfile(filepath):
                raise PatchApplicationFailed(
                    p.filename, 'File exist but was about to be overwriten')
              shutil.copy2(
                  os.path.join(self.project_path, p.source_filename), filepath)
319 320 321
            if p.diff_hunks:
              cmd = ['patch', '-p%s' % p.patchlevel, '--forward', '--force']
              stdout += subprocess2.check_output(
322
                  cmd, stdin=p.get(False), cwd=self.project_path)
323 324 325 326
            elif p.is_new and not os.path.exists(filepath):
              # There is only a header. Just create the file if it doesn't
              # exist.
              open(filepath, 'w').close()
327
          if p.is_new:
328 329
            stdout += self._check_output_svn(
                ['add', p.filename, '--force'], credentials=False)
330 331
          for prop in p.svn_properties:
            stdout += self._check_output_svn(
332 333
                ['propset', prop[0], prop[1], p.filename], credentials=False)
          for prop, values in self.svn_config.auto_props.iteritems():
334
            if fnmatch.fnmatch(p.filename, prop):
335 336 337 338 339 340 341
              for value in values.split(';'):
                if '=' not in value:
                  params = [value, '*']
                else:
                  params = value.split('=', 1)
                stdout += self._check_output_svn(
                    ['propset'] + params + [p.filename], credentials=False)
342
        for post in post_processors:
343
          post(self, p)
344 345 346 347
      except OSError, e:
        raise PatchApplicationFailed(p.filename, '%s%s' % (stdout, e))
      except subprocess.CalledProcessError, e:
        raise PatchApplicationFailed(
348 349 350
            p.filename,
            'While running %s;\n%s%s' % (
              ' '.join(e.cmd), stdout, getattr(e, 'stdout', '')))
351 352 353 354

  def commit(self, commit_message, user):
    logging.info('Committing patch for %s' % user)
    assert self.commit_user
355
    assert isinstance(commit_message, unicode)
356 357
    handle, commit_filename = tempfile.mkstemp(text=True)
    try:
358 359 360
      # Shouldn't assume default encoding is UTF-8. But really, if you are using
      # anything else, you are living in another world.
      os.write(handle, commit_message.encode('utf-8'))
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
      os.close(handle)
      # When committing, svn won't update the Revision metadata of the checkout,
      # so if svn commit returns "Committed revision 3.", svn info will still
      # return "Revision: 2". Since running svn update right after svn commit
      # creates a race condition with other committers, this code _must_ parse
      # the output of svn commit and use a regexp to grab the revision number.
      # Note that "Committed revision N." is localized but subprocess2 forces
      # LANGUAGE=en.
      args = ['commit', '--file', commit_filename]
      # realauthor is parsed by a server-side hook.
      if user and user != self.commit_user:
        args.extend(['--with-revprop', 'realauthor=%s' % user])
      out = self._check_output_svn(args)
    finally:
      os.remove(commit_filename)
    lines = filter(None, out.splitlines())
    match = re.match(r'^Committed revision (\d+).$', lines[-1])
    if not match:
      raise PatchApplicationFailed(
          None,
          'Couldn\'t make sense out of svn commit message:\n' + out)
    return int(match.group(1))

384
  def _revert(self, revision):
385 386 387 388
    """Reverts local modifications or checks out if the directory is not
    present. Use depot_tools's functionality to do this.
    """
    flags = ['--ignore-externals']
389 390
    if revision:
      flags.extend(['--revision', str(revision)])
391 392 393 394 395 396 397 398 399
    if not os.path.isdir(self.project_path):
      logging.info(
          'Directory %s is not present, checking it out.' % self.project_path)
      self._check_call_svn(
          ['checkout', self.svn_url, self.project_path] + flags, cwd=None)
    else:
      scm.SVN.Revert(self.project_path)
      # Revive files that were deleted in scm.SVN.Revert().
      self._check_call_svn(['update', '--force'] + flags)
400
    return self._get_revision()
401

402
  def _get_revision(self):
403
    out = self._check_output_svn(['info', '.'])
404 405 406 407 408
    revision = int(self._parse_svn_info(out, 'revision'))
    if revision != self._last_seen_revision:
      logging.info('Updated to revision %d' % revision)
      self._last_seen_revision = revision
    return revision
409 410 411 412


class GitCheckoutBase(CheckoutBase):
  """Base class for git checkout. Not to be used as-is."""
413 414 415 416
  def __init__(self, root_dir, project_name, remote_branch,
      post_processors=None):
    super(GitCheckoutBase, self).__init__(
        root_dir, project_name, post_processors)
417 418 419 420 421
    # There is no reason to not hardcode it.
    self.remote = 'origin'
    self.remote_branch = remote_branch
    self.working_branch = 'working_branch'

422
  def prepare(self, revision):
423 424 425 426
    """Resets the git repository in a clean state.

    Checks it out if not present and deletes the working branch.
    """
427
    assert self.remote_branch
428 429
    assert os.path.isdir(self.project_path)
    self._check_call_git(['reset', '--hard', '--quiet'])
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    if revision:
      try:
        revision = self._check_output_git(['rev-parse', revision])
      except subprocess.CalledProcessError:
        self._check_call_git(
            ['fetch', self.remote, self.remote_branch, '--quiet'])
        revision = self._check_output_git(['rev-parse', revision])
      self._check_call_git(['checkout', '--force', '--quiet', revision])
    else:
      branches, active = self._branches()
      if active != 'master':
        self._check_call_git(['checkout', '--force', '--quiet', 'master'])
      self._check_call_git(['pull', self.remote, self.remote_branch, '--quiet'])
      if self.working_branch in branches:
        self._call_git(['branch', '-D', self.working_branch])
445

446
  def apply_patch(self, patches, post_processors=None):
447 448 449 450 451 452
    """Applies a patch on 'working_branch' and switch to it.

    Also commits the changes on the local branch.

    Ignores svn properties and raise an exception on unexpected ones.
    """
453
    post_processors = post_processors or self.post_processors or []
454 455
    # It this throws, the checkout is corrupted. Maybe worth deleting it and
    # trying again?
456 457 458 459
    if self.remote_branch:
      self._check_call_git(
          ['checkout', '-b', self.working_branch,
            '%s/%s' % (self.remote, self.remote_branch), '--quiet'])
460
    for index, p in enumerate(patches):
461 462 463
      try:
        stdout = ''
        if p.is_delete:
464 465 466 467 468 469 470 471
          if (not os.path.exists(p.filename) and
              any(p1.source_filename == p.filename for p1 in patches[0:index])):
            # The file could already be deleted if a prior patch with file
            # rename was already processed. To be sure, look at all the previous
            # patches to see if they were a file rename.
            pass
          else:
            stdout += self._check_output_git(['rm', p.filename])
472 473 474 475 476 477 478 479 480 481
        else:
          dirname = os.path.dirname(p.filename)
          full_dir = os.path.join(self.project_path, dirname)
          if dirname and not os.path.isdir(full_dir):
            os.makedirs(full_dir)
          if p.is_binary:
            with open(os.path.join(self.project_path, p.filename), 'wb') as f:
              f.write(p.get())
            stdout += self._check_output_git(['add', p.filename])
          else:
482 483
            # No need to do anything special with p.is_new or if not
            # p.diff_hunks. git apply manages all that already.
484
            stdout += self._check_output_git(
485
                ['apply', '--index', '-p%s' % p.patchlevel], stdin=p.get(True))
486 487 488 489 490 491 492 493 494 495 496
          for prop in p.svn_properties:
            # Ignore some known auto-props flags through .subversion/config,
            # bails out on the other ones.
            # TODO(maruel): Read ~/.subversion/config and detect the rules that
            # applies here to figure out if the property will be correctly
            # handled.
            if not prop[0] in ('svn:eol-style', 'svn:executable'):
              raise patch.UnsupportedPatchFormat(
                  p.filename,
                  'Cannot apply svn property %s to file %s.' % (
                        prop[0], p.filename))
497
        for post in post_processors:
498
          post(self, p)
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
      except OSError, e:
        raise PatchApplicationFailed(p.filename, '%s%s' % (stdout, e))
      except subprocess.CalledProcessError, e:
        raise PatchApplicationFailed(
            p.filename, '%s%s' % (stdout, getattr(e, 'stdout', None)))
    # Once all the patches are processed and added to the index, commit the
    # index.
    self._check_call_git(['commit', '-m', 'Committed patch'])
    # TODO(maruel): Weirdly enough they don't match, need to investigate.
    #found_files = self._check_output_git(
    #    ['diff', 'master', '--name-only']).splitlines(False)
    #assert sorted(patches.filenames) == sorted(found_files), (
    #    sorted(out), sorted(found_files))

  def commit(self, commit_message, user):
    """Updates the commit message.

    Subclass needs to dcommit or push.
    """
518
    assert isinstance(commit_message, unicode)
519 520 521 522 523 524
    self._check_call_git(['commit', '--amend', '-m', commit_message])
    return self._check_output_git(['rev-parse', 'HEAD']).strip()

  def _check_call_git(self, args, **kwargs):
    kwargs.setdefault('cwd', self.project_path)
    kwargs.setdefault('stdout', self.VOID)
525
    return subprocess2.check_call_out(['git'] + args, **kwargs)
526 527 528 529 530 531 532 533 534

  def _call_git(self, args, **kwargs):
    """Like check_call but doesn't throw on failure."""
    kwargs.setdefault('cwd', self.project_path)
    kwargs.setdefault('stdout', self.VOID)
    return subprocess2.call(['git'] + args, **kwargs)

  def _check_output_git(self, args, **kwargs):
    kwargs.setdefault('cwd', self.project_path)
535 536
    return subprocess2.check_output(
        ['git'] + args, stderr=subprocess2.STDOUT, **kwargs)
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554

  def _branches(self):
    """Returns the list of branches and the active one."""
    out = self._check_output_git(['branch']).splitlines(False)
    branches = [l[2:] for l in out]
    active = None
    for l in out:
      if l.startswith('*'):
        active = l[2:]
        break
    return branches, active


class GitSvnCheckoutBase(GitCheckoutBase, SvnMixIn):
  """Base class for git-svn checkout. Not to be used as-is."""
  def __init__(self,
      root_dir, project_name, remote_branch,
      commit_user, commit_pwd,
555
      svn_url, trunk, post_processors=None):
556
    """trunk is optional."""
557 558 559
    GitCheckoutBase.__init__(
        self, root_dir, project_name + '.git', remote_branch, post_processors)
    SvnMixIn.__init__(self)
560 561 562 563 564 565 566 567 568 569
    self.commit_user = commit_user
    self.commit_pwd = commit_pwd
    # svn_url in this case is the root of the svn repository.
    self.svn_url = svn_url
    self.trunk = trunk
    assert bool(self.commit_user) >= bool(self.commit_pwd)
    assert self.svn_url
    assert self.trunk
    self._cache_svn_auth()

570
  def prepare(self, revision):
571 572
    """Resets the git repository in a clean state."""
    self._check_call_git(['reset', '--hard', '--quiet'])
573 574 575 576 577
    if revision:
      try:
        revision = self._check_output_git(
            ['svn', 'find-rev', 'r%d' % revision])
      except subprocess.CalledProcessError:
578
        self._check_call_git(
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
            ['fetch', self.remote, self.remote_branch, '--quiet'])
        revision = self._check_output_git(
            ['svn', 'find-rev', 'r%d' % revision])
      super(GitSvnCheckoutBase, self).prepare(revision)
    else:
      branches, active = self._branches()
      if active != 'master':
        if not 'master' in branches:
          self._check_call_git(
              ['checkout', '--quiet', '-b', 'master',
              '%s/%s' % (self.remote, self.remote_branch)])
        else:
          self._check_call_git(['checkout', 'master', '--force', '--quiet'])
      # git svn rebase --quiet --quiet doesn't work, use two steps to silence
      # it.
      self._check_call_git_svn(['fetch', '--quiet', '--quiet'])
      self._check_call_git(
          ['rebase', '--quiet', '--quiet',
            '%s/%s' % (self.remote, self.remote_branch)])
      if self.working_branch in branches:
        self._call_git(['branch', '-D', self.working_branch])
    return self._get_revision()
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618

  def _git_svn_info(self, key):
    """Calls git svn info. This doesn't support nor need --config-dir."""
    return self._parse_svn_info(self._check_output_git(['svn', 'info']), key)

  def commit(self, commit_message, user):
    """Commits a patch."""
    logging.info('Committing patch for %s' % user)
    # Fix the commit message and author. It returns the git hash, which we
    # ignore unless it's None.
    if not super(GitSvnCheckoutBase, self).commit(commit_message, user):
      return None
    # TODO(maruel): git-svn ignores --config-dir as of git-svn version 1.7.4 and
    # doesn't support --with-revprop.
    # Either learn perl and upstream or suck it.
    kwargs = {}
    if self.commit_pwd:
      kwargs['stdin'] = self.commit_pwd + '\n'
619
      kwargs['stderr'] = subprocess2.STDOUT
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    self._check_call_git_svn(
        ['dcommit', '--rmdir', '--find-copies-harder',
          '--username', self.commit_user],
        **kwargs)
    revision = int(self._git_svn_info('revision'))
    return revision

  def _cache_svn_auth(self):
    """Caches the svn credentials. It is necessary since git-svn doesn't prompt
    for it."""
    if not self.commit_user or not self.commit_pwd:
      return
    # Use capture to lower noise in logs.
    self._check_output_svn(['ls', self.svn_url], cwd=None)

  def _check_call_git_svn(self, args, **kwargs):
    """Handles svn authentication while calling git svn."""
    args = ['svn'] + args
    if not self.svn_config.default:
      args.extend(['--config-dir', self.svn_config.svn_config_dir])
    return self._check_call_git(args, **kwargs)

  def _get_revision(self):
    revision = int(self._git_svn_info('revision'))
    if revision != self._last_seen_revision:
645
      logging.info('Updated to revision %d' % revision)
646 647 648 649 650 651 652 653 654 655 656 657 658
      self._last_seen_revision = revision
    return revision


class GitSvnPremadeCheckout(GitSvnCheckoutBase):
  """Manages a git-svn clone made out from an initial git-svn seed.

  This class is very similar to GitSvnCheckout but is faster to bootstrap
  because it starts right off with an existing git-svn clone.
  """
  def __init__(self,
      root_dir, project_name, remote_branch,
      commit_user, commit_pwd,
659
      svn_url, trunk, git_url, post_processors=None):
660 661 662
    super(GitSvnPremadeCheckout, self).__init__(
        root_dir, project_name, remote_branch,
        commit_user, commit_pwd,
663
        svn_url, trunk, post_processors)
664 665 666
    self.git_url = git_url
    assert self.git_url

667
  def prepare(self, revision):
668 669 670 671 672 673 674
    """Creates the initial checkout for the repo."""
    if not os.path.isdir(self.project_path):
      logging.info('Checking out %s in %s' %
          (self.project_name, self.project_path))
      assert self.remote == 'origin'
      # self.project_path doesn't exist yet.
      self._check_call_git(
675 676 677
          ['clone', self.git_url, self.project_name, '--quiet'],
          cwd=self.root_dir,
          stderr=subprocess2.STDOUT)
678 679 680 681 682 683 684 685 686 687 688 689 690
    try:
      configured_svn_url = self._check_output_git(
          ['config', 'svn-remote.svn.url']).strip()
    except subprocess.CalledProcessError:
      configured_svn_url = ''

    if configured_svn_url.strip() != self.svn_url:
      self._check_call_git_svn(
          ['init',
           '--prefix', self.remote + '/',
           '-T', self.trunk,
           self.svn_url])
    self._check_call_git_svn(['fetch'])
691
    return super(GitSvnPremadeCheckout, self).prepare(revision)
692 693 694 695 696 697 698 699 700 701


class GitSvnCheckout(GitSvnCheckoutBase):
  """Manages a git-svn clone.

  Using git-svn hides some of the complexity of using a svn checkout.
  """
  def __init__(self,
      root_dir, project_name,
      commit_user, commit_pwd,
702
      svn_url, trunk, post_processors=None):
703 704 705
    super(GitSvnCheckout, self).__init__(
        root_dir, project_name, 'trunk',
        commit_user, commit_pwd,
706
        svn_url, trunk, post_processors)
707

708
  def prepare(self, revision):
709
    """Creates the initial checkout for the repo."""
710
    assert not revision, 'Implement revision if necessary'
711 712 713 714 715 716 717 718 719
    if not os.path.isdir(self.project_path):
      logging.info('Checking out %s in %s' %
          (self.project_name, self.project_path))
      # TODO: Create a shallow clone.
      # self.project_path doesn't exist yet.
      self._check_call_git_svn(
          ['clone',
           '--prefix', self.remote + '/',
           '-T', self.trunk,
720 721 722 723
           self.svn_url, self.project_path,
           '--quiet'],
          cwd=self.root_dir,
          stderr=subprocess2.STDOUT)
724
    return super(GitSvnCheckout, self).prepare(revision)
725 726 727 728


class ReadOnlyCheckout(object):
  """Converts a checkout into a read-only one."""
729
  def __init__(self, checkout, post_processors=None):
730
    super(ReadOnlyCheckout, self).__init__()
731
    self.checkout = checkout
732 733
    self.post_processors = (post_processors or []) + (
        self.checkout.post_processors or [])
734

735 736
  def prepare(self, revision):
    return self.checkout.prepare(revision)
737 738 739 740

  def get_settings(self, key):
    return self.checkout.get_settings(key)

741 742 743
  def apply_patch(self, patches, post_processors=None):
    return self.checkout.apply_patch(
        patches, post_processors or self.post_processors)
744 745 746 747 748 749 750 751 752 753 754 755 756

  def commit(self, message, user):  # pylint: disable=R0201
    logging.info('Would have committed for %s with message: %s' % (
        user, message))
    return 'FAKE'

  @property
  def project_name(self):
    return self.checkout.project_name

  @property
  def project_path(self):
    return self.checkout.project_path