Created
November 16, 2022 17:16
-
-
Save HotelCalifornia/02abf88405735917c89560053ac0869b to your computer and use it in GitHub Desktop.
create a new branch or switch to an existing branch (either local or remote) by JIRA issue reference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
from git import Head, RemoteReference, Repo | |
from subprocess import check_output | |
def checkout_branch(r, b): | |
if isinstance(b, RemoteReference): | |
# if it's remote we need to do some chicanery | |
r.create_head((n := b.name.split('origin/') | |
[-1]), b).set_tracking_branch(b).checkout() | |
print(b.name, n) | |
elif isinstance(b, Head): | |
# otherwise it's already local so we can just check it out i think | |
b.checkout() | |
else: | |
raise ValueError( | |
'branch argument is neither a local nor a remote branch') | |
if len(sys.argv) < 2: | |
print('Error: expected an argument') | |
print('Usage: git switch-issue ISSUE_REF') | |
sys.exit(os.EX_USAGE) | |
issue = sys.argv[1] | |
repo = Repo(os.getcwd()) | |
repo.remote().fetch() | |
# prioritize local branches by only querying the remote if we find no matches | |
# locally so that we don't get prompted for multiple matches when there's a | |
# local and a remote branch that reference the issue number | |
branches = [b for b in repo.branches if issue in b.name] | |
if len(branches) == 0: | |
branches = [b for b in repo.remote().refs if issue in b.name] | |
if len(branches) > 1: | |
print('Multiple matching branches found') | |
print(os.linesep.join([f'\t[{i}] {b.name}' for i, b in zip(range(len(branches)), branches)])) | |
while (choice := int(input(f'Select a match: [0-{len(branches) - 1}]: '))) not in range(len(branches)): | |
print('Error: invalid choice') | |
checkout_branch(repo, branches[choice]) | |
elif len(branches) == 1: | |
checkout_branch(repo, branches[0]) | |
else: | |
print('No matches found') | |
choice = input('Would you like to create a branch? (y/n): ') | |
if choice == 'y': | |
ok = 'n' | |
while ok == 'n': | |
branch_types = ['feature', 'bugfix', 'hotfix', 'release'] | |
while (branch_type := input(f'Enter an issue type: ({branch_types}): ')) not in branch_types: | |
print('Error: Invalid branch type selected') | |
name = input('Enter a branch name (spaces ok): ').replace(' ', '-') | |
new_branch = f'{branch_type}/{issue}-{name}' | |
ok = input(f'Create branch {new_branch} from develop? (y/n): ') | |
repo.create_head(new_branch, repo.branches['develop']).checkout() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment