-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathprecommit.py
executable file
·70 lines (53 loc) · 1.97 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
#!/usr/bin/env python3
"""Runs precommit checks on the repository."""
import argparse
import os
import pathlib
import shutil
import subprocess
import sys
import sysconfig
import textwrap
# os.fspath() is 3.6+. str is a reasonable substitute
# https://docs.python.org/3.9/library/os.html#os.fspath
fspath = getattr(os, "fspath", str)
class ToxNotFoundError(Exception):
"""Rasie when tox not found in expected locations."""
def main() -> int:
"""Execute the main routine."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--overwrite",
help=
"Overwrites the unformatted source files with the well-formatted code in place. " # pylint: disable=line-too-long
"If not set, an exception is raised if any of the files do not conform to the style guide.", # pylint: disable=line-too-long
action='store_true')
args = parser.parse_args()
tox_environments = ["check", "_auto_version"]
if args.overwrite:
tox_environments.insert(0, "format")
tox_from_path = shutil.which("tox")
maybe_scripts = sysconfig.get_path("scripts")
tox_from_scripts = pathlib.Path(maybe_scripts).joinpath(
"tox") if maybe_scripts is not None else None
if tox_from_path is not None:
tox = pathlib.Path(tox_from_path)
elif tox_from_scripts is not None and tox_from_scripts.is_file():
tox = tox_from_scripts
else:
message = textwrap.dedent(f'''\
'tox' executable not found in PATH or scripts directory
PATH: {os.environ['PATH']}
scripts: {maybe_scripts}
''')
raise ToxNotFoundError(message)
repo_root = pathlib.Path(__file__).parent
tox_ini = repo_root.joinpath("tox.ini")
command = [
fspath(tox), "-c",
fspath(tox_ini), "-e", ",".join(tox_environments)
]
completed_process = subprocess.run(command) # pylint: disable=W1510
return completed_process.returncode
if __name__ == "__main__":
sys.exit(main())