-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpre-commit
executable file
·77 lines (59 loc) · 2.33 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
#!/usr/bin/env python3
import sys
import hooks_cfg as cfg
pre_commit_cfg = cfg.checks_cfg['pre-commit']
root_path = cfg.get_repo_path()
def _get_modified_files(endswith='.py'):
_, modified_files_str, _ = cfg.run(
'git diff-index --name-only --diff-filter=dr --cached HEAD')
modified_files = modified_files_str.strip().split()
return [
"%s/%s" % (root_path, fname) for fname in modified_files if
fname.endswith(endswith)]
def _get_modified_files_str(endswith='.py'):
modified_files = _get_modified_files(endswith=endswith)
return ' '.join(modified_files)
def run_checks(command_items):
"""Run provided checks on modified files."""
last_failed_exit_code = 0
for command, fnames_str in command_items:
exit_code, stdout, stderr = cfg.run(
"%s %s" % (command, fnames_str))
if exit_code:
print("%s failed!\nSTDOUT: %s.\nSTDERR: %s\n" % (
command, stdout, stderr), end='')
last_failed_exit_code = exit_code
else:
print("%s OK!" % command, file=sys.stderr)
if last_failed_exit_code:
sys.exit(last_failed_exit_code)
def _get_check_arg_str(check_command, modified_files_str):
ignore = pre_commit_cfg[check_command]['ignore']
if ignore:
return "--ignore=%s %s" % (ignore, modified_files_str)
return modified_files_str
def _add_cmd_prefix(check_command):
if pre_commit_cfg[check_command].get('cmd_prefix'):
return pre_commit_cfg[check_command]['cmd_prefix'] % check_command
return check_command
def get_command_items(*checks):
"""Generate command items to run checks.
Args:
*checks: number of different checks to run, like flake8,
pydocstyle. Currently only flake8 and pydocstyle are
implemented.
Returns:
list
commands with their arguments to run wanted checks.
"""
modified_files_str = _get_modified_files_str(endswith='.py')
command_items = []
# Only run checks if there was anything modified.
if modified_files_str:
for check in checks:
arg_str = _get_check_arg_str(check, modified_files_str)
check = _add_cmd_prefix(check)
command_items.append((check, arg_str))
return command_items
checks = pre_commit_cfg['run']
run_checks(get_command_items(*checks))