Debian Codegraph @

hooks/prepare-commit-msg.py

raw
1 #!/usr/bin/env python
2 import shutil
3 import subprocess
4 import sys
5 from pathlib import Path
6
7 try:
8 from commitizen.cz.utils import get_backup_file_path
9 except ImportError as error:
10 print("could not import commitizen:")
11 print(error)
12 exit(1)
13
14
15 def prepare_commit_msg(commit_msg_file: str) -> int:
16 # check if the commit message needs to be generated using commitizen
17 exit_code = subprocess.run(
18 [
19 "cz",
20 "check",
21 "--commit-msg-file",
22 commit_msg_file,
23 ],
24 capture_output=True,
25 ).returncode
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)
54 return 0
55
56
57 if __name__ == "__main__":
58 # make hook interactive by attaching /dev/tty to stdin
59 with open("/dev/tty") as tty:
60 sys.stdin = tty
61 exit_code = prepare_commit_msg(sys.argv[1])
62 exit(exit_code)