-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpre-commit.py
More file actions
executable file
·192 lines (164 loc) · 5.29 KB
/
pre-commit.py
File metadata and controls
executable file
·192 lines (164 loc) · 5.29 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
#!/usr/bin/env python
import collections
import optparse
import os
import os.path
import shutil
import subprocess
import sys
FILE_LIST = 'git ls-files | egrep "\.%s$"'
ALL_FILES = FILE_LIST % '(php|sql|py|js|htm|c|cpp|h|sh|css)'
JS_FILES = FILE_LIST % 'js'
PY_FILES = FILE_LIST % 'py'
CPP_FILES = FILE_LIST % '(cc|cpp|h)'
C_FILES = FILE_LIST % '(c|h)'
C_LIKE_FILES = FILE_LIST % '(c|cc|cpp|h)'
HEADER_FILES = FILE_LIST % 'h'
RED = '\033[41m'
GREEN = '\033[42m'
NORMAL = '\033[0m'
COLS = int(subprocess.check_output(['tput', 'cols']))
Test = collections.namedtuple('Test', ['command', 'name', 'nonzero', 'config'])
TESTS = [
Test(
"./check.sh",
'All - Things installed',
False, 'testconsolelog',
),
Test(
"%s | xargs grep 'console.log'" % JS_FILES,
'JS - Console.log',
True, 'testconsolelog',
),
Test(
"%s | xargs pyflakes" % PY_FILES,
'Py - Pyflakes',
False, 'testpyflakes',
),
Test(
"%s | xargs grep 'import\sipdb'" % PY_FILES,
'Py - ipdb',
True, 'testipdby',
),
Test(
"%s | xargs grep -H -n -P '\t'" % ALL_FILES,
"All - No tabs",
True, 'testtabs',
),
]
def get_git_config(config_name):
config_result = ''
try:
config_result = subprocess.check_output([
'git', 'config', config_name
])
except subprocess.CalledProcessError: pass
return config_result.strip()
def get_pre_commit_path():
git_top = subprocess.check_output(
['git', 'rev-parse', '--show-toplevel']
).strip()
return os.path.join(git_top, '.git/hooks/pre-commit')
class FixAllBase(object):
name = None
matching_files_command = None
def get_all_files(self):
try:
files = subprocess.check_output(
self.matching_files_command,
shell=True,
)
files_split = files.splitlines()
return [file.strip() for file in files_split]
except subprocess.CalledProcessError:
return []
def fix_file(self, file):
'''Implement to fix the file.'''
raise NotImplementedError
def run(self):
'''Runs the process to fix the files. Returns True if nothign to fix.'''
print '%s...' % self.name
all_files = self.get_all_files()
for file in all_files:
print 'Fixing %s' % file
self.fix_file(file)
return not all_files
class FixTrailingWhitespace(FixAllBase):
name = 'Trimming trailing whitespace'
matching_files_command = '%s | xargs egrep -l "[[:space:]]$"' % ALL_FILES
def fix_file(self, file):
subprocess.check_call(['sed', '-i', '-e', 's/[[:space:]]*$//', file])
class FixLineEndings(FixAllBase):
name = 'Fixing line endings'
matching_files_command = "%s | xargs egrep -l $'\\r'\\$" % ALL_FILES
def fix_file(self, file):
subprocess.check_call(['dos2unix', file])
subprocess.check_call(['mac2unix', file])
FIXERS = [
FixTrailingWhitespace,
FixLineEndings,
]
def run_tests():
passed = True
for test in TESTS:
run_test = get_git_config('hooks.%s' % test.config)
if run_test == 'false':
print 'Skipping "%s" due to git config.' % test.name
continue
try:
retcode = 0
output = subprocess.check_output(
test.command, shell=True, stderr=subprocess.STDOUT
)
except subprocess.CalledProcessError as e:
retcode = e.returncode
output = e.output
pass_fail = '%sSuccess%s' % (GREEN, NORMAL)
failed_test = False
if (retcode and not test.nonzero) or (not retcode and test.nonzero):
pass_fail = '%sFailure(%s)%s' % (RED, retcode, NORMAL)
failed_test = True
dots = COLS - len(pass_fail) - len(test.name)
print '%s%s%s' % (test.name, '.' * dots, pass_fail)
if failed_test:
print
print output
passed = False
return passed
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option(
'-u', '--uninstall',
action='store_true', dest='uninstall', default=False,
help='Uninstall pre-commit script.'
)
parser.add_option(
'-i', '--install',
action='store_true', dest='install', default=False,
help='Install pre-commit script.'
)
opts, args = parser.parse_args()
if opts.install:
pre_commit_path = get_pre_commit_path()
shutil.copyfile(__file__, pre_commit_path)
os.chmod(pre_commit_path, 0755)
print 'Installed pre commit to %s' % pre_commit_path
sys.exit(0)
elif opts.uninstall:
pre_commit_path = get_pre_commit_path()
if os.path.exists(pre_commit_path):
os.remove(pre_commit_path)
print 'Removed pre-commit scripts.'
passed = True
for fixer in FIXERS:
passed &= fixer().run()
passed &= run_tests()
if not passed:
print '%sFailures / Fixes detected.%s' % (RED, NORMAL)
print 'Please fix and commit again.'
print "You could also pass --no-verify, but you probably shouldn't."
print
print "Here's git status for convenience: "
print
os.system('git status')
sys.exit(-1)