File: prepare-commit-msg.py

package info (click to toggle)
commitizen 4.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,672 kB
  • sloc: python: 14,530; makefile: 15
file content (61 lines) | stat: -rwxr-xr-x 1,785 bytes parent folder | download
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
#!/usr/bin/env python
import shutil
import subprocess
import sys
from pathlib import Path
from subprocess import CalledProcessError

try:
    from commitizen.cz.utils import get_backup_file_path
except ImportError as error:
    print("could not import commitizen:")
    print(error)
    exit(1)


def prepare_commit_msg(commit_msg_file: str) -> int:
    # check if the commit message needs to be generated using commitizen
    exit_code = subprocess.run(
        [
            "cz",
            "check",
            "--commit-msg-file",
            commit_msg_file,
        ],
        capture_output=True,
    ).returncode
    if exit_code != 0:
        backup_file = Path(get_backup_file_path())
        if backup_file.is_file():
            # confirm if commit message from backup file should be reused
            answer = input("retry with previous message? [y/N]: ")
            if answer.lower() == "y":
                shutil.copyfile(backup_file, commit_msg_file)
                return 0

        # use commitizen to generate the commit message
        try:
            subprocess.run(
                [
                    "cz",
                    "commit",
                    "--dry-run",
                    "--write-message-to-file",
                    commit_msg_file,
                ],
                stdin=sys.stdin,
                stdout=sys.stdout,
            ).check_returncode()
        except CalledProcessError as error:
            return error.returncode

        # write message to backup file
        shutil.copyfile(commit_msg_file, backup_file)
    return 0


if __name__ == "__main__":
    # make hook interactive by attaching /dev/tty to stdin
    with open("/dev/tty") as tty:
        sys.stdin = tty
        exit(prepare_commit_msg(sys.argv[1]))