-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit_delete_merged_branches.py
executable file
·93 lines (69 loc) · 2.58 KB
/
git_delete_merged_branches.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python3
"""Delete local branches that are already gone from remote."""
import argparse
import re
import subprocess
from typing import List
from rich import print as rprint
# Patterns for finding issue IDs
# Each pattern has to contain a single capture group for the whole issue ID
PATTERNS = []
# URL to Jira (must end with /)
JIRA_URL = ""
def get_default_branch() -> str:
output = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "origin/HEAD"],
shell=False,
check=True,
stdout=subprocess.PIPE,
)
output_str = output.stdout.decode("ascii").strip()
return output_str.replace("origin/", "")
def get_current_branch() -> str:
output = subprocess.run(
["git", "b", "--show-current"], shell=False, check=True, stdout=subprocess.PIPE
)
return output.stdout.decode("ascii").strip()
def get_merged_branches() -> List[str]:
# Get output from git-find-merged-branches
output = subprocess.run(
["git", "find-merged-branches"], shell=False, check=True, stdout=subprocess.PIPE
)
output_str = output.stdout.decode("ascii")
return output_str.strip().split("\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-f", action="store_true", default=False, help="fetch --prune before checking"
)
args = parser.parse_args()
# Check that we're on default branch
default_branch = get_default_branch()
current_branch = get_current_branch()
if current_branch != default_branch:
rprint(
f"[red]Currently checked out branch is not {default_branch}, it is: {current_branch}[/red]"
)
exit(1)
if args.f:
# First, call git fetch --prune
subprocess.run(["git", "fetch", "--prune"], shell=False, check=True)
for branch in get_merged_branches():
if not branch:
continue
rprint(
f"Branch [bold yellow]{branch}[/bold yellow] seems to be deleted in remote"
)
for pattern in PATTERNS:
if m := pattern.match(branch):
issue_id = m.group(1)
rprint(f" Issue ID: [bold cyan]{issue_id}[/bold cyan]")
rprint(f" Link: [bold green]{JIRA_URL}{issue_id}[/bold green]")
rprint(
f" Delete [bold underline]local[/bold underline] branch [bold red]{branch}[/bold red]? \[y/N] ",
end="",
)
ans = input().lower()
if ans == "y":
rprint(f" Deleting [bold red]{branch}[/bold red]")
subprocess.run(["git", "b", "-D", branch])