-
Notifications
You must be signed in to change notification settings - Fork 5
/
pre-commit
executable file
·182 lines (144 loc) · 4.77 KB
/
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
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
#!/usr/bin/env python
"""
Git pre-commit hook for checking Python code quality. The hook requires pylint
to check the code quality.
AUTHOR:
Sebastian Dahlgren <sebastian.dahlgren@gmail.com>
VERSION:
1.0.0
LICENSE:
Apache License 2.0
http://www.apache.org/licenses/LICENSE-2.0.html
"""
#######################################
#
# CONFIGURATION
#
#######################################
# The lowest allowed score (should be a float between 0.00 and 10.00)
LIMIT = 10.00
# pylint command to run
PYLINT = 'pylint'
# where to look for options
PYLINTRC = '.pylintrc'
# Custom pylint command line parameters. See pylint --help for more info
# E.g.
# PYLINT_PARAMS = '--rcfile=/path/to/project/pylint.rc'
PYLINT_PARAMS = ''
#######################################
#
# CODE BELOW
#
#######################################
import os
import re
import sys
import subprocess
import ConfigParser
def get_list_of_committed_files():
"""
Returns a list of files about to be commited.
"""
files = []
# pylint: disable=E1103
output = subprocess.check_output(
'git diff-index --cached HEAD'.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 checker():
"""
Main function doing the checks
"""
global PYLINT, PYLINT_PARAMS, LIMIT
# List of checked files and their results
python_files = []
# Set the exit code
exit_code = 0
# Find Python files
for filename in get_list_of_committed_files():
# Check the file extension
if filename[-3:] == '.py':
python_files.append((filename, None))
continue
# Check the first line for a python shebang
try:
with open(filename, 'r') as file_handle:
first_line = file_handle.readline()
if 'python' in first_line and '#!' in first_line:
python_files.append((filename, None))
except IOError:
print 'File not found (probably deleted): %s\t\tSKIPPED' % 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 += ' ' + conf.get('pre-commit-hook', 'limit')
# Pylint Python files
i = 1
regexp = re.compile(r'^Your\ code\ has\ been\ rated\ at\ (\-?[0-9\.]+)/10')
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 %s (empty __init__.py)..\tSKIPPED' % (
python_file)
# Bump parsed files
i += 1
continue
# Set the initial score
score = 0.00
# skipping test files
if python_file.startswith('src/slidelint/tests'):
continue
# Start pylinting
sys.stdout.write("Running pylint on %s (file %i/%i)..\t" % (
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:
if os.path.exists('.pylintrc'):
command.append('--rcfile=.pylintrc')
command.append(python_file)
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, _ = proc.communicate()
except OSError as err:
print "\nAn error occurred. Is pylint installed?"
sys.exit(1)
# Check for the result
# pylint: disable=E1103
for line in out.split('\n'):
match = re.match(regexp, line)
if match:
score = float(match.group(1))
# Verify the score
if score >= float(LIMIT):
status = 'PASSED'
else:
status = 'FAILED'
exit_code = 1
# Add some output
print '%.2f/10.00\t%s' % (score, status)
# Bump parsed files
i += 1
sys.exit(exit_code)
if __name__ == '__main__':
checker()
sys.exit(1)