summaryrefslogtreecommitdiff
path: root/testing/tools/githelper.py
blob: 021ed4e61e142d1d04d8175a904a8bc406e3d064 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Copyright 2017 The PDFium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Classes for dealing with git."""

import subprocess


class GitHelper(object):
  """Issues git commands. Stateful."""

  def __init__(self):
    self.stashed = 0

  def Checkout(self, branch):
    """Checks out a branch."""
    subprocess.check_output(['git', 'checkout', branch])

  def FetchOriginMaster(self):
    """Fetches new changes on origin/master."""
    subprocess.check_output(['git', 'fetch', 'origin', 'master'])

  def StashPush(self):
    """Stashes uncommitted changes."""
    output = subprocess.check_output(['git', 'stash', '--include-untracked'])
    if 'No local changes to save' in output:
      return False

    self.stashed += 1
    return True

  def StashPopAll(self):
    """Pops as many changes as this instance stashed."""
    while self.stashed > 0:
      subprocess.check_output(['git', 'stash', 'pop'])
      self.stashed -= 1

  def GetCurrentBranchName(self):
    """Returns a string with the current branch name."""
    return subprocess.check_output(
        ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()

  def GetCurrentBranchHash(self):
    return subprocess.check_output(
        ['git', 'rev-parse', 'HEAD']).strip()

  def IsCurrentBranchClean(self):
    output = subprocess.check_output(['git', 'status', '--porcelain'])
    return not output

  def BranchExists(self, branch_name):
    """Return whether a branch with the given name exists."""
    try:
      subprocess.check_output(['git', 'rev-parse', '--verify',
                               branch_name])
      return True
    except subprocess.CalledProcessError:
      return False

  def CloneLocal(self, source_repo, new_repo):
    subprocess.check_call(['git', 'clone', source_repo, new_repo])