|
| 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