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 # Need the --send-mail flag to publish the CL and remove WIP bit. 78 upload_cmd.append('--send-mail') 79 subprocess.check_call(upload_cmd) 80 output = subprocess.check_output(['git', 'cl', 'issue']).rstrip() 81 return re.match('^Issue number: (?P<issue>\d+) \((?P<issue_url>.+)\)$', 82 output).group('issue_url') 83 84 def __exit__(self, exc_type, _value, _traceback): 85 if self._upload: 86 # Only upload if no error occurred. 87 try: 88 if exc_type is None: 89 self.commit_and_upload(use_commit_queue=self._commit_queue) 90 finally: 91 subprocess.check_call(['git', 'checkout', 'master']) 92 if self._delete_when_finished: 93 subprocess.check_call(['git', 'branch', '-D', self._branch_name]) 94 95 96 class NewGitCheckout(utils.tmp_dir): 97 """Creates a new local checkout of a Git repository.""" 98 99 def __init__(self, repository, commit='HEAD'): 100 """Set parameters for this local copy of a Git repository. 101 102 Because this is a new checkout, rather than a reference to an existing 103 checkout on disk, it is safe to assume that the calling thread is the 104 only thread manipulating the checkout. 105 106 You must use the 'with' statement to create this object: 107 108 with NewGitCheckout(*args) as checkout: 109 # use checkout instance 110 # the checkout is automatically cleaned up here 111 112 Args: 113 repository: URL of the remote repository (e.g., 114 'https://skia.googlesource.com/common') or path to a local repository 115 (e.g., '/path/to/repo/.git') to check out a copy of 116 commit: commit hash, branch, or tag within refspec, indicating what point 117 to update the local checkout to 118 """ 119 super(NewGitCheckout, self).__init__() 120 self._repository = repository 121 self._commit = commit 122 123 @property 124 def root(self): 125 """Returns the root directory containing the checked-out files.""" 126 return self.name 127 128 def __enter__(self): 129 """Check out a new local copy of the repository. 130 131 Uses the parameters that were passed into the constructor. 132 """ 133 super(NewGitCheckout, self).__enter__() 134 subprocess.check_output(args=['git', 'clone', self._repository, self.root]) 135 return self 136