-
Notifications
You must be signed in to change notification settings - Fork 9
/
.check-formatting.py
183 lines (158 loc) · 4.94 KB
/
.check-formatting.py
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
173
174
175
176
177
178
179
180
181
182
183
#! /usr/bin/env python
import argparse
import os.path
import sys
from colorama import Fore, Style
args_parser = argparse.ArgumentParser(
description="Check basic formatting rules on text files"
)
args_parser.add_argument(
"--autofix",
action="store_true",
help="When possible, update files to fix detected formatting issues",
)
args_parser.add_argument(
"--force-colors",
action="store_true",
help=(
"Force colored output. This is necessary when the output is not a TTY"
" but still supports ANSI codes."
),
)
args_parser.add_argument(
"files",
nargs="*",
help=(
"List of files on which to run. If none is passed, process all source"
" files found in the current directory that look like source files."
),
)
class Checker:
filename_extensions = {
"adb",
"adc",
"ads",
"c",
"cc",
"cpp",
"gpr",
"h",
"hh",
"hpp",
"opt",
"py",
}
"""
List of file extensions that look like source files.
"""
def __init__(self, autofix: bool = False, force_colors: bool = False):
self.issue_found = False
"""
Whether at least one issue was found so far.
"""
self.use_colors = force_colors or os.isatty(sys.stdout.fileno())
"""
Whether to colorize the error messages.
"""
self.autofix = autofix
"""
Whether to attempt to fix the style issues found in place.
"""
def report(
self,
filename: str,
message: str,
lineno: int | None = None,
) -> None:
"""
Report a style issue.
:param filename: File in which the issue was found.
:param message: Human-readable description of the issue.
:param lineno: Line number for the issue, if applicable, None
otherwise.
"""
self.issue_found = True
# Build a list of text chunks to print. Put colorama elements in tuples
# so that we can keep only text chunks if the output is not a TTY.
chunks = [
(Fore.MAGENTA,),
filename,
(Fore.CYAN,),
":",
]
if lineno is not None:
chunks += [
(Fore.GREEN,),
str(lineno),
(Fore.CYAN,),
":",
]
chunks += [
(Style.RESET_ALL,),
" ",
message,
]
filtered_chunks = []
for c in chunks:
if isinstance(c, str):
filtered_chunks.append(c)
elif isinstance(c, tuple):
if self.use_colors:
filtered_chunks += c
else:
raise AssertionError
print("".join(filtered_chunks))
def process_file(self, filename: str) -> None:
"""
Look for style issues in the given file.
"""
with open(filename, encoding="utf-8") as f:
try:
content = f.read()
except UnicodeDecodeError as exc:
self.report(filename, str(exc))
return
if not content:
return
lines = content.splitlines()
modified = False
if not content.endswith("\n"):
modified = True
self.report(filename, "missing trailing newline")
for i, line in enumerate(lines, 1):
stripped_line = line.rstrip()
if line != stripped_line:
modified = True
self.report(filename, "trailing whitespace", i)
lines[i - 1] = stripped_line
while not lines[-1].strip():
modified = True
self.report(filename, "last line is empty")
lines.pop()
# If requested, fix the issues that were found
if self.autofix and modified:
with open(filename, "w") as f:
if lines:
for line in lines:
f.write(line)
f.write("\n")
@classmethod
def main(cls, argv: list[str] | None = None):
args = args_parser.parse_args(argv)
checker = cls(
autofix=args.autofix,
force_colors=args.force_colors,
)
# Process the list of files to check if present, otherwise look for all
# source files in the current directory.
if args.files:
for filename in args.files:
checker.process_file(filename)
else:
for path, _, filenames in os.walk("."):
for f in filenames:
if f.rsplit(".", 1)[-1] in cls.filename_extensions:
checker.process_file(os.path.join(path, f))
return 1 if checker.issue_found else 0
if __name__ == "__main__":
sys.exit(Checker.main())