-
Notifications
You must be signed in to change notification settings - Fork 15
/
lint-clang-format.py
executable file
·91 lines (83 loc) · 2.79 KB
/
lint-clang-format.py
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/env python3
# Copyright (c) 2018-2019 The Unit-e developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import difflib
import subprocess
import sys
import shared.lib
def formatfile(filename):
ps = subprocess.Popen("clang-format -style=file -i " + filename,
shell=True,
stdout=subprocess.PIPE)
return ps.wait()
def gitadd(filename):
ps = subprocess.Popen("git add " + filename,
shell=True,
stdout=subprocess.PIPE)
return ps.wait()
def checkandupdate(filename, replace=False, addtogit=False):
ps = subprocess.Popen("clang-format -style=file " + filename,
shell=True,
stdout=subprocess.PIPE)
formatted = ps.stdout.read().decode("utf-8")
with open(filename, "rb") as file:
unformatted = file.read().decode("utf-8")
isformatted = formatted == unformatted
if not isformatted:
if replace:
if formatfile(filename) == 0:
if addtogit:
if gitadd(filename) == 0:
print(filename, "has been formatted and added to commit")
return True
else:
print(filename, "has been formatted")
else:
print(filename, "is not formatted")
diff = difflib.unified_diff(unformatted.splitlines(True), formatted.splitlines(True))
print(''.join(diff))
return isformatted
def help(argv):
print("Using: {0} [--check-commit] [--replace [--git-add]]".format(argv[0]))
print()
print("Check that unit-e sources follow the style guide.")
print("With no options, just check all the project files.")
print()
print("--check-commit consider only unit-e files from the current commit")
print("--replace adjust unformatted files")
print("--git-add add formatted files back into your commit")
return 1
def main(argv):
if ("-h" in argv) or ("--help" in argv):
return help(argv)
autoformat = "--replace" in argv
autogitadd = autoformat and "--git-add" in argv
iscurrentcommit = "--check-commit" in argv
dirs = [
"src/blockchain",
"src/esperanza",
"src/finalization",
"src/key",
"src/p2p",
"src/proposer",
"src/snapshot",
"src/staking",
"src/usbdevice",
"src/test/blockchain",
"src/test/esperanza",
"src/test/finalization",
"src/test/proposer",
"src/test/snapshot",
"src/test/staking",
]
violations = []
for dir in dirs:
violations += shared.lib.checkfiles(
pattern = ".+\\.(cpp|h)",
dir = dir,
action = lambda f : checkandupdate(f, replace=autoformat, addtogit=autogitadd),
only_changed = iscurrentcommit)
return 0 if len(violations) == 0 else 1
if __name__ == "__main__":
sys.exit(main(sys.argv))