Home | History | Annotate | Download | only in bots
      1 #!/usr/bin/env python
      2 # Copyright (c) 2014 The Chromium Authors. All rights reserved.
      3 # Use of this source code is governed by a BSD-style license that can be
      4 # found in the LICENSE file.
      5 
      6 """This module contains functions for using git."""
      7 
      8 import re
      9 import shutil
     10 import subprocess
     11 import tempfile
     12 
     13 import utils
     14 
     15 
     16 class GitLocalConfig(object):
     17   """Class to manage local git configs."""
     18   def __init__(self, config_dict):
     19     self._config_dict = config_dict
     20     self._previous_values = {}
     21 
     22   def __enter__(self):
     23     for k, v in self._config_dict.iteritems():
     24       try:
     25         prev = subprocess.check_output(['git', 'config', '--local', k]).rstrip()
     26         if prev:
     27           self._previous_values[k] = prev
     28       except subprocess.CalledProcessError:
     29         # We are probably here because the key did not exist in the config.
     30         pass
     31       subprocess.check_call(['git', 'config', '--local', k, v])
     32 
     33   def __exit__(self, exc_type, _value, _traceback):
     34     for k in self._config_dict:
     35       if self._previous_values.get(k):
     36         subprocess.check_call(
     37             ['git', 'config', '--local', k, self._previous_values[k]])
     38       else:
     39         subprocess.check_call(['git', 'config', '--local', '--unset', k])
     40 
     41 
     42 class GitBranch(object):
     43   """Class to manage git branches.
     44 
     45   This class allows one to create a new branch in a repository to make changes,
     46   then it commits the changes, switches to master branch, and deletes the
     47   created temporary branch upon exit.
     48   """
     49   def __init__(self, branch_name, commit_msg, upload=True, commit_queue=False,
     50                delete_when_finished=True):
     51     self._branch_name = branch_name
     52     self._commit_msg = commit_msg
     53     self._upload = upload
     54     self._commit_queue = commit_queue
     55     self._patch_set = 0
     56     self._delete_when_finished = delete_when_finished
     57 
     58   def __enter__(self):
     59     subprocess.check_call(['git', 'reset', '--hard', 'HEAD'])
     60     subprocess.check_call(['git', 'checkout', 'master'])
     61     if self._branch_name in subprocess.check_output(['git', 'branch']).split():
     62       subprocess.check_call(['git', 'branch', '-D', self._branch_name])
     63     subprocess.check_call(['git', 'checkout', '-b', self._branch_name,
     64                            '-t', 'origin/master'])
     65     return self
     66 
     67   def commit_and_upload(self, use_commit_queue=False):
     68     """Commit all changes and upload a CL, returning the issue URL."""
     69     subprocess.check_call(['git', 'commit', '-a', '-m', self._commit_msg])
     70     upload_cmd = ['git', 'cl', 'upload', '-f', '--bypass-hooks',
     71                   '--bypass-watchlists']
     72     self._patch_set += 1
     73     if self._patch_set > 1:
     74       upload_cmd.extend(['-t', 'Patch set %d' % self._patch_set])
     75     if use_commit_queue:
     76       upload_cmd.append('--use-commit-queue')
     77     subprocess.check_call(upload_cmd)
     78     output = subprocess.check_output(['git', 'cl', 'issue']).rstrip()
     79     return re.match('^Issue number: (?P<issue>\d+) \((?P<issue_url>.+)\)$',
     80                     output).group('issue_url')
     81 
     82   def __exit__(self, exc_type, _value, _traceback):
     83     if self._upload:
     84       # Only upload if no error occurred.
     85       try:
     86         if exc_type is None:
     87           self.commit_and_upload(use_commit_queue=self._commit_queue)
     88       finally:
     89         subprocess.check_call(['git', 'checkout', 'master'])
     90         if self._delete_when_finished:
     91           subprocess.check_call(['git', 'branch', '-D', self._branch_name])
     92 
     93 
     94 class NewGitCheckout(utils.tmp_dir):
     95   """Creates a new local checkout of a Git repository."""
     96 
     97   def __init__(self, repository, commit='HEAD'):
     98     """Set parameters for this local copy of a Git repository.
     99 
    100     Because this is a new checkout, rather than a reference to an existing
    101     checkout on disk, it is safe to assume that the calling thread is the
    102     only thread manipulating the checkout.
    103 
    104     You must use the 'with' statement to create this object:
    105 
    106     with NewGitCheckout(*args) as checkout:
    107       # use checkout instance
    108     # the checkout is automatically cleaned up here
    109 
    110     Args:
    111       repository: URL of the remote repository (e.g.,
    112           'https://skia.googlesource.com/common') or path to a local repository
    113           (e.g., '/path/to/repo/.git') to check out a copy of
    114       commit: commit hash, branch, or tag within refspec, indicating what point
    115           to update the local checkout to
    116     """
    117     super(NewGitCheckout, self).__init__()
    118     self._repository = repository
    119     self._commit = commit
    120 
    121   @property
    122   def root(self):
    123     """Returns the root directory containing the checked-out files."""
    124     return self.name
    125 
    126   def __enter__(self):
    127     """Check out a new local copy of the repository.
    128 
    129     Uses the parameters that were passed into the constructor.
    130     """
    131     super(NewGitCheckout, self).__enter__()
    132     subprocess.check_output(args=['git', 'clone', self._repository, self.root])
    133     return self
    134