-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython-git-pre-commit.py
More file actions
executable file
·156 lines (127 loc) · 4.48 KB
/
python-git-pre-commit.py
File metadata and controls
executable file
·156 lines (127 loc) · 4.48 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Huoty, All rights reserved
# Author: Huoty <sudohuoty@gmail.com>
# CreateTime: 2018-04-19 19:14:09
# Forked From https://gist.github.com/spulec/1364640
from __future__ import print_function
import os
import re
import sys
import subprocess
if sys.version_info[0] < 3:
reload(sys)
sys.setdefaultencoding("utf-8")
CHECKS = [
{
'output': 'Checking for pdb and ipdbs...',
'command': r'grep -n "import [i]*pdb" %s',
'match_files': ['.*\.py$'],
'ignore_files': ['.*pre-commit', '.*__main__.py'],
'print_filename': True,
'exists': False,
'package': ''
},
{
'output': 'Checking for print statements...',
'command': r'grep -n "^\s*\bprint" %s',
'match_files': ['.*\.py$'],
'ignore_files': ['.*migrations.*', '.*management/commands.*',
'.*manage[r]?.py', '.*/scripts/.*', '.*/test[s]?/.*',
'.*__main__.py'],
'print_filename': True,
'exists': False,
'package': ''
},
{
'output': 'Running PyCodeStyle...',
'command': 'pycodestyle -r --ignore=E402,E501,E731,W293 %s',
'match_files': ['.*\.py$'],
'ignore_files': ['.*migrations.*'],
'print_filename': False,
'exists': True,
'package': 'pycodestyle'
},
{
'output': 'Running PyFlakes...',
'command': 'pyflakes %s',
'match_files': ['.*\.py$'],
'ignore_files': ['.*migrations.*', '.*/terrain/.*'],
'print_filename': False,
'exists': True,
'package': 'pyflakes'
}
]
def highlight(text, status):
attrs = []
colors = {
'red': '31', 'green': '32', 'yellow': '33'
}
if not sys.stdout.isatty():
return text
attrs.append(colors.get(status, 'red'))
attrs.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attrs), text)
def exists(cmd, error=True):
devnull = open(os.devnull, 'w')
params = {'stdout': devnull, 'stderr': devnull, }
query = 'which %s' % cmd
code = subprocess.call(query.split(), **params)
if code != 0 and error:
print(highlight('not installed %(command)s' % {'command': cmd}, 'red'))
sys.exit(1)
def matches_file(file_name, match_files):
return any(re.compile(match_file).match(file_name) for match_file in match_files)
def system(*args, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
out = out if out is None or isinstance(out, str) else out.decode("utf-8")
err = err if err is None or isinstance(err, str) else err.decode("utf-8")
return out, err
def check_files(files, check):
result = 0
print(highlight(check['output'], 'green'))
if check['exists'] and check['package']:
exists(check['package'])
for file_name in files:
if 'match_files' not in check or matches_file(
file_name, check['match_files']):
if 'ignore_files' not in check or not matches_file(
file_name, check['ignore_files']):
out, err = system(check['command'] % file_name,
stderr=subprocess.PIPE, shell=True)
if out or err:
if check['print_filename']:
prefix = '\t%s:' % file_name
else:
prefix = '\t'
output_lines = ['{}{}'.format(prefix, line) for line in
out.splitlines()]
print(highlight('\n'.join(output_lines), 'red'))
if err:
print(highlight(err, 'red'))
result = 1
return result
def main():
out, err = system('git', 'status', '--porcelain', stderr=subprocess.PIPE)
if err:
print(highlight(err, 'red'), end='')
return 1
modified = re.compile('^[MA]\s+(?P<name>.*)$')
files = []
for line in out.splitlines():
match = modified.match(str(line))
if match:
files.append(match.group('name'))
if not files:
return 0
result = 0
for check in CHECKS:
result = check_files(files, check) or result
if result != 0:
prompt_message = "Commit failed, above problems need to be solved"
print("\n", highlight(prompt_message, 'yellow'), sep='')
return result
if __name__ == '__main__':
sys.exit(main())