Skip to content

Commit 9fc2c99

Browse files
committed
Updated documentation and added better debugging for v0.1.0 release
1 parent 8fc70e0 commit 9fc2c99

File tree

4 files changed

+105
-53
lines changed

4 files changed

+105
-53
lines changed

.pylintrc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
[pre-commit-hook]
2-
limit=8.0
1+
[MASTER]
2+
ignore=test
33

44
[FORMAT]
55
indent-string=' '

README.md

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,49 @@
11
# commit-msg-regex-hook
22

3-
Before the readme, big shoutout to @dimaka-wix who's repo [commit-msg-hook](https://github.com/dimaka-wix/commit-msg-hook) was the basis for this repository. Go check out his repo for more information.
4-
53
This hook is designed to be used with the [pre-commit](https://pre-commit.com/) hook framework. It will check your commit string against the provided regex.
64

7-
### Utilizing
85

9-
First you will need to setup [pre-commit](https://pre-commit.com/) using their documentation. Then you will be able to add this repository under it with the following:
6+
### Using the commit-msg-regex-hook
7+
8+
First you will need to setup [pre-commit](https://pre-commit.com/) using their documentation.
9+
10+
Next you will need to enable commit message hooks:
11+
`pre-commit install --hook-type commit-msg`
12+
13+
Finally you can add this to your .pre-commit-config.yaml:
1014

1115
```
12-
- repo: https://github.com/dimaka-wix/commit-msg-hook.git
13-
rev: v0.3.1
16+
- repo: https://github.com/dtaivpp/commit-msg-regex-hook
17+
rev: v0.1.0
1418
hooks:
1519
- id: commit-msg-hook
1620
args: ["--pattern='[A-Z]{3,4}-[0-9]{3,6} \\| [\\w\\s]* \\| .+'"]
1721
stages: [commit-msg]
1822
```
1923

20-
**note the backslashes need to be escaped
24+
**note: the backslashes in regex need to be escaped need to be escaped
25+
**double note: if you are having issues you can run with the --debug argument as well for additional logging.
2126

22-
### To enable commit-msg hook with pre-commit run:
23-
`pre-commit install --hook-type commit-msg`
2427

25-
### Update to the latest release (optional)
26-
`pre-commit autoupdate --repo https://github.com/dtaivpp/commit-msg-regex-hook.git`
28+
### Developing this project
29+
30+
If you would like to contribute to this project I am happy to accept contributions. Small note I use two spaces for indents and am not looking to swap.
31+
32+
Here is how you can contribute:
33+
34+
1. Fork the repo
35+
2. Create a virtual envrionment `python -m venv venv`
36+
3. Activate the virtual environment:
37+
- Windows: `venv\Scripts\activate`
38+
- Mac/Linux: `source venv/bin/activate`
39+
4. Install the reqirements `python -m pip install -r requirements.txt`
40+
5. Install our hooks:
41+
- `pre-commit install`
42+
43+
And you are off to the races!
44+
45+
Before committing I would reccomend checking your build against unittest and the linter. If it doesn't pass it wont pass!
46+
- `python -m unittest test`
47+
- `python -m pylint commit_msg_regex_hook`
48+
49+
Make sure if you add a check to add a test case!

commit_msg_regex_hook/commit_msg_regex_hook.py

Lines changed: 65 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,19 @@
77
import sys
88
import argparse
99
import re
10+
import logging
1011
from typing import Pattern
1112

13+
14+
logger = logging.getLogger("__main__")
15+
logger.setLevel(logging.ERROR)
16+
consoleHandle = logging.StreamHandler()
17+
consoleHandle.setLevel(logging.DEBUG)
18+
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
19+
consoleHandle.setFormatter(formatter)
20+
logger.addHandler(consoleHandle)
21+
22+
1223
# Default commit message path
1324
COMMIT_EDITMSG = ".git/COMMIT_EDITMSG"
1425
PASS=True
@@ -23,45 +34,56 @@ def __init__(self, message, result):
2334
self.result = result
2435

2536
def is_passing(self):
37+
"""Whether the result is a passing or failing result
38+
"""
2639
return self.result
2740

2841

2942
def main():
30-
"""Perform validations of the commit message.
31-
Parse passed in regex and verify message matches
32-
"""
33-
parser = argparse.ArgumentParser()
34-
parser.add_argument("message", nargs="?", type=process_file, default=COMMIT_EDITMSG,
35-
help="File path for commit message")
36-
parser.add_argument("--pattern", type=process_pattern)
37-
parser.add_argument(
38-
'--debug',
39-
action='store_true',
40-
help='print debug messages to stdout'
41-
)
43+
"""Perform validations of the commit message.
44+
Parse passed in regex and verify message matches
45+
"""
46+
parser = argparse.ArgumentParser()
47+
parser.add_argument("message", nargs="?", type=process_file, default=COMMIT_EDITMSG,
48+
help="File path for commit message")
49+
parser.add_argument("--pattern", type=process_pattern)
50+
parser.add_argument(
51+
'--debug',
52+
action='store_true',
53+
help='print debug messages to stdout'
54+
)
55+
56+
args = parser.parse_args()
4257

43-
args = parser.parse_args()
58+
if args.debug:
59+
logger.setLevel(logging.DEBUG)
4460

45-
checks = [
46-
message_not_empty(args.message),
47-
message_pattern_match(args.message, args.pattern)
48-
]
61+
checks = [
62+
message_not_empty(args.message),
63+
message_pattern_match(args.message, args.pattern)
64+
]
4965

50-
for check in checks:
51-
result = check()
52-
53-
if not result.is_passing():
54-
print(f"Check Failed:\n {result.message}")
55-
sys.exit(1)
66+
run_checks(checks)
5667

57-
if args.debug:
58-
print(result.message)
5968

60-
sys.exit(0)
69+
def run_checks(checks: list):
70+
"""Processs the checks and in the event of a failure
71+
kill the commit
72+
"""
73+
for check in checks:
74+
result = check()
75+
76+
if not result.is_passing():
77+
logger.error("Check Failed:\n {failure}", failure=result.message)
78+
sys.exit(1)
79+
80+
logger.debug(result.message)
81+
82+
sys.exit(0)
6183

6284

6385
def process_file(path: str) -> str:
64-
"""Extract commit message.
86+
"""Extract commit message.
6587
6688
Args:
6789
path (str): The path of the file with commit message
@@ -71,8 +93,8 @@ def process_file(path: str) -> str:
7193
try:
7294
with open(path, "r", encoding="utf-8") as file:
7395
msg = file.read()
74-
except FileNotFoundError:
75-
raise argparse.ArgumentError(f"File does not exist: \n\t{path}")
96+
except FileNotFoundError as file_not_found:
97+
raise argparse.ArgumentTypeError(f"File does not exist: \n\t{path}") from file_not_found
7698

7799
return msg
78100

@@ -87,9 +109,9 @@ def process_pattern(str_pattern: str) -> Pattern:
87109
"""
88110
try:
89111
pattern = re.compile(str_pattern[1:-1])
90-
except Exception as e:
112+
except Exception as err:
91113
raise argparse.ArgumentTypeError(
92-
f"'{str_pattern}' is not a valid regex pattern\n {e}"
114+
f"'{str_pattern}' is not a valid regex pattern\n {err}"
93115
)
94116

95117
return pattern
@@ -99,22 +121,26 @@ def message_not_empty(message: str) -> Result:
99121
"""Verify the commit message is not empty
100122
"""
101123
def check():
124+
logger.debug("Current Message: {message}", message=message)
125+
102126
if len(message.strip()) == 0:
103-
return Result(f"ֿError: commit message cannot be empty", FAIL)
104-
105-
return Result(f"The commit message is not empty", PASS)
127+
return Result("ֿError: commit message cannot be empty", FAIL)
128+
129+
return Result("The commit message is not empty", PASS)
106130
return check
107131

108132

109-
def message_pattern_match(msg: str, pattern: Pattern) -> Result:
133+
def message_pattern_match(message: str, pattern: Pattern) -> Result:
110134
"""Verify the commit message matches the pattern
111135
"""
112136
def check():
113-
if not pattern.match(msg):
137+
logger.debug("Pattern: {regex}\nMessage: {message}", regex=pattern, message=message)
138+
139+
if not pattern.match(message):
114140
# Fail the commit message
115-
return Result(f"Commit Message does not match pattern\n\t{pattern}\n\t{msg}", FAIL)
116-
117-
return Result(f"The commit message matches the regex", PASS)
141+
return Result(f"Commit Message does not match pattern\n\t{pattern}\n\t{message}", FAIL)
142+
143+
return Result("The commit message matches the regex", PASS)
118144
return check
119145

120146

test/test.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
"""Test suite for the project
2+
"""
3+
14
import re
25
import unittest
3-
from src import commit_msg_regex_hook
6+
from commit_msg_regex_hook import commit_msg_regex_hook
47

58

69
class TestMessageEmpty(unittest.TestCase):

0 commit comments

Comments
 (0)