-
Notifications
You must be signed in to change notification settings - Fork 0
/
codeclimate-black
executable file
·84 lines (65 loc) · 2.42 KB
/
codeclimate-black
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
#!/usr/bin/env python3
import json
import os.path
import black
import sys
from identify import identify
root_path = "/code/"
class CodeClimateReport:
"""Print results of the checks in Code Climate format."""
def error(line_number, offset, filename):
"""Print an error in Code Climate format."""
issue = {
"type": "issue",
"check_name": "Python/Black",
"categories": ["Style"],
"description": "File not formatted according to black style guide",
"remediation_points": 50000,
"location": {
"path": os.path.normpath(filename),
"positions": {
"begin": {"line": line_number, "column": offset + 1},
"end": {"line": line_number, "column": offset + 1},
},
},
}
print(json.dumps(issue) + "\0")
def _included(fp, include_paths):
for path in include_paths:
if fp.startswith(path):
return True
return False
def _is_python_file(filename):
return "python" in identify.tags_from_path(filename)
def run(paths):
"""Parse options and run checks on Python source."""
import signal
import os
# Handle "Broken pipe" gracefully
try:
signal.signal(signal.SIGPIPE, lambda signum, frame: sys.exit(1))
except AttributeError:
pass # not supported on Windows
for dirpath, dnames, fnames in os.walk(root_path):
for f in fnames:
filepath = os.path.join(dirpath, f)
if _is_python_file(filepath) and _included(filepath, paths):
with open(filepath, "r") as fp:
inp_buf = fp.read()
out = black.format_str(inp_buf, mode=black.Mode())
diff = black.diff(inp_buf, out, filepath, filepath)
if diff:
CodeClimateReport.error(0, 0, filepath[len(root_path) :])
include_paths = [root_path]
if os.path.exists("/config.json"):
contents = open("/config.json").read()
config = json.loads(contents)
i_paths = config.get("include_paths")
if type(i_paths) == list:
python_paths = []
for i in i_paths:
ext = os.path.splitext(i)[1]
if os.path.isdir(i) or _is_python_file(i):
python_paths.append(os.path.normpath(os.path.join(root_path, i)))
include_paths = python_paths
run(include_paths)