-
Notifications
You must be signed in to change notification settings - Fork 0
/
prepend_jira_issue.py
95 lines (65 loc) · 2.51 KB
/
prepend_jira_issue.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
94
95
from __future__ import annotations
import argparse
import re
import subprocess
from typing import Sequence
def run_command(command: str) -> str:
"""Run a command and return its output
If the command fails, return an empty string"""
try:
stdout: str = subprocess.check_output(command.split()).decode("utf-8").strip()
except Exception:
stdout = ""
return stdout
def get_branch_name() -> str:
# git rev-parse --abbrev-ref HEAD
# returns HEAD if in detached state
# git symbolic-ref --short HEAD
# returns fatal: ref HEAD is not a symbolic ref if in detached state
return run_command("git symbolic-ref --short HEAD")
def extract_jira_issue(content: str) -> str | None:
project_key, issue_number = r"[A-Z]{2,}", r"[0-9]+"
match = re.search(f"{project_key}-{issue_number}", content)
if match:
return match.group(0)
return None
def get_commit_msg(commit_msg_filepath: str) -> str:
"""Get the commit message
Ignore comment lines as those aren't included in the commit message
"""
# todo: instead of removing comment lines from the commit message, we should instead
# skip them in our regex search
with open(commit_msg_filepath) as f:
msg = ""
for line in f:
if not line.startswith("#"):
msg += line
return msg
def prepend_jira_issue(msg: str, issue: str) -> str:
return f"{issue}: {msg}"
def write_commit_msg(commit_msg_filepath: str, commit_msg: str) -> None:
with open(commit_msg_filepath, "w") as f:
f.write(commit_msg)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("commit_msg_filepath", type=str)
args = parser.parse_args(argv)
git_branch_name = get_branch_name()
branch_jira_issue = extract_jira_issue(git_branch_name)
# if no jira issue in branch name, exit
if branch_jira_issue is None:
return 0
commit_msg = get_commit_msg(args.commit_msg_filepath)
# ignore merge requests
if re.match("^Merge commit '", commit_msg):
return 0
# check if commit message already has a jira issue in it's name
commit_msg_jira_issue = extract_jira_issue(commit_msg)
# if jira issue already in commit message, skip
if commit_msg_jira_issue:
return 0
new_commit_msg = prepend_jira_issue(commit_msg, branch_jira_issue)
write_commit_msg(args.commit_msg_filepath, new_commit_msg)
return 0
if __name__ == "__main__":
raise SystemExit(main())