-
Notifications
You must be signed in to change notification settings - Fork 0
/
precommit.py
executable file
·289 lines (240 loc) · 8.38 KB
/
precommit.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#! .venv/bin/python
"""
precommit
~~~~~~~~~
Things that should be done before committing changes to the repo.
"""
import configparser
import doctest
from fnmatch import fnmatch
import glob
import importlib
from itertools import zip_longest
import os
from pathlib import Path
import sys
import unittest as ut
from textwrap import wrap
import mypy.api
import pycodestyle as pcs
import rstcheck_core.checker as rstchecker
from rstcheck_core.config import RstcheckConfig
# Script configuration.
CONFIG_FILE = 'setup.cfg'
def get_config(filepath):
"""Pull configuration settings from the configuration file."""
config_file = open(filepath)
config = configparser.ConfigParser()
config.read_file(config_file)
return config['precommit']
def import_modules(names):
"""Import the modules needed for the doctest checks."""
return [importlib.import_module(name) for name in names]
# Precommit checks.
def check_doctests(names):
"""Run documentation tests."""
print('Running doctests...')
if not names:
print('No doctests found.')
else:
modules = import_modules(names)
for mod in modules:
doctest.testmod(mod)
print('Doctests complete.')
def check_requirements():
"""Check requirements."""
print('Checking requirements...')
os.putenv('PIPENV_VERBOSITY', '-1')
cmd = '.venv/bin/python -m pipenv requirements'
current = os.popen(cmd).readlines()
current = wrap_lines(current, 35, '', ' ')
with open('requirements.txt') as fh:
old = fh.readlines()
old = wrap_lines(old, 35, '', ' ')
# If the packages installed don't match the requirements, it's
# likely the requirements need to be updated. Display the two
# lists to the user, and let them make the decision whether
# to freeze the new requirements.
if current != old:
print('requirements.txt out of date.')
print()
tmp = '{:<35} {:<35}'
print(tmp.format('current', 'old'))
print('\u2500' * 70)
for c, o in zip_longest(current, old, fillvalue=''):
print(tmp.format(c, o))
print()
update = input('Update? [y/N]: ')
if update.casefold() == 'y':
os.system(f'{cmd} > requirements.txt')
os.unsetenv('PIPENV_VERBOSITY')
print('Requirements checked...')
def check_rst(file_paths, ignore):
"""Run syntax checks on any ReStructured Text documents."""
def action(files):
results = []
config = RstcheckConfig()
for file in files:
result = list(rstchecker.check_file(Path(file), config))
if result:
for item in result:
msg = f'{file}:{item["line_number"]} {item["message"]}'
results.append(msg)
return results
title = 'Checking RSTs'
file_ext = '.rst'
run_check_on_files(title, action, file_paths, ignore,
file_ext, write_report)
def check_style(file_paths, ignore):
"""Run style checks on the code."""
def result_handler(result):
if result.get_count():
write_report(result.result_messages)
result.result_messages = []
class StyleReport(pcs.BaseReport):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.result_messages = []
def error(self, line_number, offset, text, check):
super().error(line_number, offset, text, check)
msg = (f'{self.filename} {line_number}:{offset} {text}')
self.result_messages.append(msg)
title = 'Checking style'
style = pcs.StyleGuide(config_file='setup.cfg', reporter=StyleReport)
action = style.check_files
file_ext = '.py'
run_check_on_files(title, action, file_paths, ignore,
file_ext, result_handler)
def check_type_hints(path):
"""Check the type hinting."""
print('Running type hinting check...')
results = mypy.api.run([path, ])
for report in results[:-1]:
ps = report.split('\n')
for p in ps:
lines = wrap(p, initial_indent=' ', subsequent_indent=' ')
for line in lines:
print(line)
print('Type hint checks complete.')
def check_unit_tests(path):
"""Run the unit tests."""
print('Running unit tests...')
loader = ut.TestLoader()
tests = loader.discover(path)
runner = ut.TextTestRunner()
result = runner.run(tests)
print('Unit tests complete.')
return result
def check_venv():
"""Ensure this is running from the virtual environment for
pjinoise. I know this is a little redundant with the shebang
line at the top, but debugging issues caused by running from
the wrong venv are a giant pain.
"""
venv_path = '.venv/bin/python'
dir_delim = '/'
cwd = os.getcwd()
exp_path = cwd + dir_delim + venv_path
act_path = sys.executable
if exp_path != act_path:
msg = (f'precommit run from unexpected python: {act_path}. '
f'Run from {exp_path} instead.')
raise ValueError(msg)
def check_whitespace(file_paths, ignore):
"""Remove trailing whitespace."""
title = 'Checking whitespace'
action = remove_whitespace
file_ext = '.py'
run_check_on_files(title, action, file_paths, ignore, file_ext)
# Utility functions.
def get_module_dir():
"""Get the directory of the module."""
cwd = os.getcwd()
dirs = cwd.split('/')
return f'{cwd}/{dirs[-1]}'
def in_ignore(name, ignore):
for item in ignore:
if fnmatch(name, item):
return True
return False
def run_check_on_files(title, action, file_paths, ignore,
file_ext=None, result_handler=None):
print(f'{title}...')
for file_path in file_paths:
print(' ' * 2 + f'Checking {file_path}...', end='')
files = glob.glob(file_path)
if file_ext:
files = [name for name in files if name.endswith(file_ext)]
if ignore:
files = [name for name in files if not in_ignore(name, ignore)]
result = action(files)
print('. Done.')
if result and result_handler:
result_handler(result)
print(f'{title} complete.')
return result
def remove_whitespace(filename):
if isinstance(filename, (list, tuple)):
for item in filename:
remove_whitespace(item)
else:
with open(filename, 'r') as fh:
lines = fh.readlines()
newlines = [line.rstrip() for line in lines]
newlines = [line + '\n' for line in newlines]
with open(filename, 'w') as fh:
fh.writelines(newlines)
def wrap_lines(lines, width, initial_indent, subsequent_indent):
"""Perform word wrapping on a sequence of lines of text."""
out = []
kwargs = {
'width': width,
'initial_indent': initial_indent,
'subsequent_indent': subsequent_indent,
}
for line in lines:
if line.endswith('\n'):
line = line[:-1]
wrapped = wrap(line, **kwargs)
out.extend(wrapped)
return out
def write_report(result):
if not result:
return None
wrapped = wrap_lines(result, 72, ' ' * 4, ' ' * 6)
for line in wrapped:
print(line)
def main():
# Save time by not checking files that git ignores.
ignore = []
with open('./.gitignore') as fh:
lines = fh.readlines()
for line in lines:
if line.endswith('\n'):
line = line[:-1]
if line:
ignore.append(line)
# Set up the configuration for the checks.
config = get_config(CONFIG_FILE)
doctest_modules = []
if 'doctest_modules' in config:
doctest_modules = config['doctest_modules'].split('\n')
python_files = config['python_files'].split('\n')
rst_files = config['rst_files'].split('\n')
unit_tests = config['unit_tests']
# Initial checks.
check_venv()
check_whitespace(python_files, ignore)
result = check_unit_tests(unit_tests)
# Only continue with precommit checks if the unit tests passed.
if not result.errors and not result.failures:
check_requirements()
if 'doctest_modules' in config:
check_doctests(doctest_modules)
check_style(python_files, ignore)
check_rst(rst_files, ignore)
check_type_hints(get_module_dir())
else:
print('Unit tests failed. Precommit checks aborted. Do not commit.')
if __name__ == '__main__':
main()