1# Copyright 2017 The PDFium Authors 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4"""Classes for dealing with git.""" 5 6import subprocess 7 8from common import RunCommandPropagateErr 9 10 11class GitHelper: 12 """Issues git commands. Stateful.""" 13 14 def __init__(self): 15 self.stashed = 0 16 17 def Checkout(self, branch): 18 """Checks out a branch.""" 19 RunCommandPropagateErr(['git', 'checkout', branch], exit_status_on_error=1) 20 21 def FetchOriginMaster(self): 22 """Fetches new changes on origin/main.""" 23 RunCommandPropagateErr(['git', 'fetch', 'origin', 'main'], 24 exit_status_on_error=1) 25 26 def StashPush(self): 27 """Stashes uncommitted changes.""" 28 output = RunCommandPropagateErr(['git', 'stash', '--include-untracked'], 29 exit_status_on_error=1) 30 if 'No local changes to save' in output: 31 return False 32 33 self.stashed += 1 34 return True 35 36 def StashPopAll(self): 37 """Pops as many changes as this instance stashed.""" 38 while self.stashed > 0: 39 RunCommandPropagateErr(['git', 'stash', 'pop'], exit_status_on_error=1) 40 self.stashed -= 1 41 42 def GetCurrentBranchName(self): 43 """Returns a string with the current branch name.""" 44 return RunCommandPropagateErr(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], 45 exit_status_on_error=1).strip() 46 47 def GetCurrentBranchHash(self): 48 return RunCommandPropagateErr(['git', 'rev-parse', 'HEAD'], 49 exit_status_on_error=1).strip() 50 51 def IsCurrentBranchClean(self): 52 output = RunCommandPropagateErr(['git', 'status', '--porcelain'], 53 exit_status_on_error=1) 54 return not output 55 56 def BranchExists(self, branch_name): 57 """Return whether a branch with the given name exists.""" 58 output = RunCommandPropagateErr( 59 ['git', 'rev-parse', '--verify', branch_name]) 60 return output is not None 61 62 def CloneLocal(self, source_repo, new_repo): 63 RunCommandPropagateErr(['git', 'clone', source_repo, new_repo], 64 exit_status_on_error=1) 65