forked from RTEMS/rtems
/
pre-commit
93 lines (70 loc) · 2.46 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
#!/usr/bin/python3
import configparser
import os
import re
from git import Repo
dir_list = os.getcwd()
# Gets the modes assigned by the user in the git config file.
def getModes():
repo = Repo('.', search_parent_directories=True)
reader = repo.config_reader()
try:
mode = str(reader.get_value("style","mode"))
except (configparser.NoSectionError, configparser.NoOptionError):
mode = None
try:
verbose = str(reader.get_value("style","verbose"))
except (configparser.NoSectionError, configparser.NoOptionError):
verbose = None
return mode, verbose
def colorText(string, col, style=1):
return f"\n \033[{style};{col};{col}m {string} \033[0;0m"
def ignoreDirs():
return '/bsps/|/testsuites/|/cpukit/mghttpd|/cpukit/zlib'
import subprocess
import sys
def getDiff():
cmd = "git diff -U0 --no-color --staged HEAD --$dir_list"
cmd = cmd + f" | grep -Ev '{ignoreDirs()}'"
cmd = cmd + " | clang-format-diff -p1 -style=file"
# Execute the format command
diff = subprocess.getoutput(cmd)
return diff
def handleErrors(mode, verbose):
print(colorText("Checking for style differences...", 34, style=3))
out = output.split('\n')
files = []
num_diff = 0
for line in out:
if verbose is not None and verbose.lower() == "verbose":
if line.startswith("+"):
num_diff += 1
print("\033[1;34;34m" + line + "\033[0;0m")
else:
print(line)
elif line.startswith("+"):
num_diff += 1
if line.startswith("+++"):
file = str(re.sub('[+]', '', line))
file = file.replace("(after formatting)", "").strip()
files.append(file)
out.remove(line)
print(colorText("Files affected:", 33))
for file in files:
print(file)
message = "StyleWarning: You have about a total of " + str(num_diff) + \
" style issue(s) in the " + str(len(files)) + " file(s) listed above"
print(colorText(message, 31))
if mode is not None and mode.lower() == "nonstrict":
print(colorText("Your style issues were ignored", 31))
sys.exit(0)
print(colorText("ERROR: Commit aborted due to code format inconsistencies" \
" with RTEMS", 31))
output = getDiff()
rv = len(output)
if rv == 0:
print(colorText("Everything is clean - style matches RTEMS", 34))
else:
modes = getModes()
handleErrors(modes[0], modes[1])
sys.exit(rv)