Skip to content

Commit e3bb6d7

Browse files
bearomorphismLee-W
authored andcommitted
refactor(hooks): refactor to improve readability
1 parent b7c2d8e commit e3bb6d7

File tree

1 file changed

+31
-29
lines changed

1 file changed

+31
-29
lines changed

hooks/prepare-commit-msg.py

Lines changed: 31 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import shutil
33
import subprocess
44
import sys
5-
from subprocess import CalledProcessError
5+
from pathlib import Path
66

77
try:
88
from commitizen.cz.utils import get_backup_file_path
@@ -23,38 +23,40 @@ def prepare_commit_msg(commit_msg_file: str) -> int:
2323
],
2424
capture_output=True,
2525
).returncode
26-
if exit_code != 0:
27-
backup_file_path = get_backup_file_path()
28-
if backup_file_path.is_file():
29-
# confirm if commit message from backup file should be reused
30-
answer = input("retry with previous message? [y/N]: ")
31-
if answer.lower() == "y":
32-
shutil.copyfile(backup_file_path, commit_msg_file)
33-
return 0
34-
35-
# use commitizen to generate the commit message
36-
try:
37-
subprocess.run(
38-
[
39-
"cz",
40-
"commit",
41-
"--dry-run",
42-
"--write-message-to-file",
43-
commit_msg_file,
44-
],
45-
stdin=sys.stdin,
46-
stdout=sys.stdout,
47-
).check_returncode()
48-
except CalledProcessError as error:
49-
return error.returncode
50-
51-
# write message to backup file
52-
shutil.copyfile(commit_msg_file, backup_file_path)
26+
if exit_code == 0:
27+
return 0
28+
29+
backup_file = Path(get_backup_file_path())
30+
if backup_file.is_file():
31+
# confirm if commit message from backup file should be reused
32+
answer = input("retry with previous message? [y/N]: ")
33+
if answer.lower() == "y":
34+
shutil.copyfile(backup_file, commit_msg_file)
35+
return 0
36+
37+
# use commitizen to generate the commit message
38+
exit_code = subprocess.run(
39+
[
40+
"cz",
41+
"commit",
42+
"--dry-run",
43+
"--write-message-to-file",
44+
commit_msg_file,
45+
],
46+
stdin=sys.stdin,
47+
stdout=sys.stdout,
48+
).returncode
49+
if exit_code:
50+
return exit_code
51+
52+
# write message to backup file
53+
shutil.copyfile(commit_msg_file, backup_file)
5354
return 0
5455

5556

5657
if __name__ == "__main__":
5758
# make hook interactive by attaching /dev/tty to stdin
5859
with open("/dev/tty") as tty:
5960
sys.stdin = tty
60-
exit(prepare_commit_msg(sys.argv[1]))
61+
exit_code = prepare_commit_msg(sys.argv[1])
62+
exit(exit_code)

0 commit comments

Comments
 (0)