forked from sebdah/git-pylint-commit-hook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit_hook.py
More file actions
201 lines (161 loc) · 5.8 KB
/
commit_hook.py
File metadata and controls
201 lines (161 loc) · 5.8 KB
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
""" Commit hook for pylint """
import decimal
import os
import re
import sys
import subprocess
import collections
import ConfigParser
# Avoid collision with other things called 'pylint'
import pylint.config as pylint_config
ExecutionResult = collections.namedtuple(
'ExecutionResult',
'status, stdout, stderr'
)
def _execute(cmd):
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
status = process.poll()
return ExecutionResult(status, stdout, stderr)
def _current_commit():
if _execute('git rev-parse --verify HEAD'.split()).status:
return '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
else:
return 'HEAD'
def _get_list_of_committed_files():
""" Returns a list of files about to be commited. """
files = []
# pylint: disable=E1103
diff_index_cmd = 'git diff-index --cached %s' % _current_commit()
output = subprocess.check_output(
diff_index_cmd.split()
)
for result in output.split('\n'):
if result != '':
result = result.split()
if result[4] in ['A', 'M']:
files.append(result[5])
return files
def _is_python_file(filename):
"""Check if the input file looks like a Python script
Returns True if the filename ends in ".py" or if the first line
contains "python" and "#!", returns False otherwise.
"""
if filename.endswith('.py'):
return True
else:
with open(filename, 'r') as file_handle:
first_line = file_handle.readline()
return 'python' in first_line and '#!' in first_line
_SCORE_REGEXP = re.compile(
r'^Your\ code\ has\ been\ rated\ at\ (\-?[0-9\.]+)/10')
def _parse_score(pylint_output):
"""Parse the score out of pylint's output as a float
If the score is not found, return 0.0.
"""
for line in pylint_output.splitlines():
match = re.match(_SCORE_REGEXP, line)
if match:
return float(match.group(1))
return 0.0
def check_repo(
limit, pylint='pylint', pylintrc=None, pylint_params=None,
suppress_report=False):
""" Main function doing the checks
:type limit: float
:param limit: Minimum score to pass the commit
:type pylint: str
:param pylint: Path to pylint executable
:type pylintrc: str
:param pylintrc: Path to pylintrc file
:type pylint_params: str
:param pylint_params: Custom pylint parameters to add to the pylint command
:type suppress_report: bool
:param suppress_report: Suppress report if score is below limit
"""
if pylintrc is None:
# If no config is found, use the old default '.pylintrc'
pylintrc = pylint_config.find_pylintrc() or '.pylintrc'
# List of checked files and their results
python_files = []
# Set the exit code
all_filed_passed = True
# Find Python files
for filename in _get_list_of_committed_files():
try:
if _is_python_file(filename):
python_files.append((filename, None))
except IOError:
print 'File not found (probably deleted): {}\t\tSKIPPED'.format(
filename)
# Don't do anything if there are no Python files
if len(python_files) == 0:
sys.exit(0)
# Load any pre-commit-hooks options from a .pylintrc file (if there is one)
if os.path.exists(pylintrc):
conf = ConfigParser.SafeConfigParser()
conf.read(pylintrc)
if conf.has_option('pre-commit-hook', 'command'):
pylint = conf.get('pre-commit-hook', 'command')
if conf.has_option('pre-commit-hook', 'params'):
pylint_params += ' ' + conf.get('pre-commit-hook', 'params')
if conf.has_option('pre-commit-hook', 'limit'):
limit = float(conf.get('pre-commit-hook', 'limit'))
# Pylint Python files
i = 1
for python_file, score in python_files:
# Allow __init__.py files to be completely empty
if os.path.basename(python_file) == '__init__.py':
if os.stat(python_file).st_size == 0:
print(
'Skipping pylint on {} (empty __init__.py)..'
'\tSKIPPED'.format(python_file))
# Bump parsed files
i += 1
continue
# Start pylinting
sys.stdout.write("Running pylint on {} (file {}/{})..\t".format(
python_file, i, len(python_files)))
sys.stdout.flush()
try:
command = [pylint]
if pylint_params:
command += pylint_params.split()
if '--rcfile' not in pylint_params:
command.append('--rcfile={}'.format(pylintrc))
else:
command.append('--rcfile={}'.format(pylintrc))
command.append(python_file)
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, _ = proc.communicate()
except OSError:
print("\nAn error occurred. Is pylint installed?")
sys.exit(1)
# Verify the score
score = _parse_score(out)
if score >= float(limit):
status = 'PASSED'
else:
status = 'FAILED'
all_filed_passed = False
# Add some output
print('{:.2}/10.00\t{}'.format(decimal.Decimal(score), status))
if 'FAILED' in status:
if suppress_report:
command.append('--reports=n')
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, _ = proc.communicate()
print out
# Bump parsed files
i += 1
return all_filed_passed