forked from vyperlang/vyper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfmt_commit_msg.py
More file actions
executable file
·172 lines (140 loc) · 4.8 KB
/
fmt_commit_msg.py
File metadata and controls
executable file
·172 lines (140 loc) · 4.8 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env python3
"""
Format commit messages while preserving:
- List items (-, *, +, numbered)
- Code blocks
- Blank lines between paragraphs
- Intentional formatting
"""
import sys
import re
from textwrap import fill
def is_list_item(line):
"""Check if a line starts with a list marker."""
stripped = line.lstrip()
# bullet lists: -, *, +
if stripped.startswith(("- ", "* ", "+ ")):
return True
# numbered lists: 1. 2. etc
if re.match(r"^\d+\.\s", stripped):
return True
return False
def get_list_prefix(line):
"""Extract the list prefix and calculate continuation indent."""
indent = len(line) - len(line.lstrip())
stripped = line.lstrip()
# bullet lists - continuation aligns with text after marker
for marker in ["- ", "* ", "+ "]:
if stripped.startswith(marker):
prefix = " " * indent + marker
content = stripped[len(marker) :].strip()
# continuation lines indent by 2 spaces after the bullet
cont_indent = " " * (indent + 2)
return prefix, content, cont_indent
# numbered lists - continuation aligns with text after number
match = re.match(r"^(\d+\.)\s+", stripped)
if match:
number = match.group(1)
prefix = " " * indent + number + " "
content = stripped[match.end() :].strip()
# continuation lines align with the start of text, not the number
cont_indent = " " * (indent + len(number) + 1)
return prefix, content, cont_indent
return None, line.strip(), ""
def format_commit_message(text, width=72):
"""Format commit message text while preserving structure."""
lines = text.split("\n")
result = []
i = 0
while i < len(lines):
line = lines[i]
# preserve blank lines
if not line.strip():
result.append("")
i += 1
continue
# handle code blocks
if line.strip().startswith("```"):
# preserve the opening fence
result.append(line)
i += 1
# preserve all lines until closing fence
while i < len(lines):
result.append(lines[i])
if lines[i].strip().startswith("```"):
i += 1
break
i += 1
continue
# handle list items
if is_list_item(line):
prefix, content, cont_indent = get_list_prefix(line)
# collect continuation lines for this list item
j = i + 1
while j < len(lines) and lines[j].strip() and not is_list_item(lines[j]):
content += " " + lines[j].strip()
j += 1
# wrap the list item content
wrapped = fill(
content, width=width - len(prefix), initial_indent="", subsequent_indent=""
)
# add the prefix to the first line
wrapped_lines = wrapped.split("\n")
result.append(prefix + wrapped_lines[0])
# add continuation lines with proper indent
for wline in wrapped_lines[1:]:
result.append(cont_indent + wline)
i = j
continue
# handle regular paragraphs
paragraph = []
while (
i < len(lines)
and lines[i].strip()
and not is_list_item(lines[i])
and not lines[i].strip().startswith("```")
):
paragraph.append(lines[i].strip())
i += 1
if paragraph:
# join and wrap the paragraph
text = " ".join(paragraph)
wrapped = fill(text, width=width)
result.extend(wrapped.split("\n"))
return "\n".join(result)
def main():
import argparse
parser = argparse.ArgumentParser(description="Format commit messages")
parser.add_argument(
"file", nargs="?", default="commitmsg.txt", help="File to format (default: commitmsg.txt)"
)
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
help="Print formatted output without modifying the file",
)
args = parser.parse_args()
# read from file or stdin
if args.file == "-":
text = sys.stdin.read()
else:
try:
with open(args.file, "r") as f:
text = f.read()
except FileNotFoundError:
print(f"Error: File '{args.file}' not found", file=sys.stderr)
sys.exit(1)
# format the message
formatted = format_commit_message(text)
# output
if args.dry_run or args.file == "-":
# dry run or stdin: just print
print(formatted)
else:
# write back to file and print
with open(args.file, "w") as f:
f.write(formatted)
print(formatted)
if __name__ == "__main__":
main()