-
Notifications
You must be signed in to change notification settings - Fork 5
/
.git-pre-commit
executable file
·85 lines (65 loc) · 1.98 KB
/
.git-pre-commit
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
#!/usr/bin/env python3
"""This gets executed on 'git commit' and rejects the commit in case the
submitted code does not pass validation. Validation is run only against
the files which were modified in the commit.
"""
import os
import subprocess
import sys
PYTHON = sys.executable
THIS_SCRIPT = os.path.realpath(__file__)
def term_supports_colors():
try:
import curses
assert sys.stderr.isatty()
curses.setupterm()
assert curses.tigetnum("colors") > 0
except Exception: # noqa
return False
return True
def hilite(s, ok=True, bold=False):
"""Return an highlighted version of 'string'."""
if not term_supports_colors():
return s
attr = []
if ok is None: # no color
pass
elif ok: # green
attr.append('32')
else: # red
attr.append('31')
if bold:
attr.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
def exit(msg):
print(hilite("commit aborted: " + msg, ok=False), file=sys.stderr)
sys.exit(1)
def sh(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, # noqa
stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise RuntimeError(stderr)
if stderr:
print(stderr, file=sys.stderr)
if stdout.endswith('\n'):
stdout = stdout[:-1]
return stdout
def git_commit_files():
out = sh("git diff --cached --name-only")
py_files = [x for x in out.split('\n') if x.endswith('.py') and
os.path.exists(x)]
return py_files
def ruff(files):
print("running ruff (%s)" % len(files))
cmd = [PYTHON, "-m", "ruff", "check", "--no-cache"] + files
if subprocess.call(cmd) != 0:
return exit(
"Python code didn't pass 'ruff' style check."
"Try running 'make fix-ruff'."
)
def main():
py_files = git_commit_files()
if py_files:
ruff(py_files)
main()