Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5b4f944

Browse files
committed
feat(hooks): add prepare-commit-msg and post-commit hooks
1 parent ab42fd4 commit 5b4f944

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

‎hooks/post-commit.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/usr/bin/env python
2+
import os
3+
import tempfile
4+
from pathlib import Path
5+
6+
7+
def post_commit():
8+
backup_file = Path(
9+
tempfile.gettempdir(), f"cz.commit{os.environ.get('USER', '')}.backup"
10+
)
11+
12+
# remove backup file if it exists
13+
if backup_file.is_file():
14+
backup_file.unlink()
15+
16+
17+
if __name__ == "__main__":
18+
exit(post_commit())

‎hooks/prepare-commit-msg.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#!/usr/bin/env python
2+
import os
3+
import shutil
4+
import subprocess
5+
import sys
6+
import tempfile
7+
from pathlib import Path
8+
from subprocess import CalledProcessError
9+
10+
11+
def prepare_commit_msg(commit_msg_file: Path) -> int:
12+
# check that commitizen is installed
13+
if shutil.which("cz") is None:
14+
print("commitizen is not installed!")
15+
return 0
16+
17+
# check if the commit message needs to be generated using commitizen
18+
if (
19+
subprocess.run(
20+
[
21+
"cz",
22+
"check",
23+
"--commit-msg-file",
24+
commit_msg_file,
25+
],
26+
capture_output=True,
27+
).returncode
28+
!= 0
29+
):
30+
backup_file = Path(
31+
tempfile.gettempdir(), f"cz.commit{os.environ.get('USER', '')}.backup"
32+
)
33+
34+
if backup_file.is_file():
35+
# confirm if commit message from backup file should be reused
36+
answer = input("retry with previous message? [y/N]: ")
37+
if answer.lower() == "y":
38+
shutil.copyfile(backup_file, commit_msg_file)
39+
return 0
40+
41+
# use commitizen to generate the commit message
42+
try:
43+
subprocess.run(
44+
[
45+
"cz",
46+
"commit",
47+
"--dry-run",
48+
"--write-message-to-file",
49+
commit_msg_file,
50+
],
51+
stdin=sys.stdin,
52+
stdout=sys.stdout,
53+
).check_returncode()
54+
except CalledProcessError as error:
55+
return error.returncode
56+
57+
# write message to backup file
58+
shutil.copyfile(commit_msg_file, backup_file)
59+
60+
61+
if __name__ == "__main__":
62+
# make hook interactive by attaching /dev/tty to stdin
63+
with open("/dev/tty") as tty:
64+
sys.stdin = tty
65+
exit(prepare_commit_msg(sys.argv[1]))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /