-
Notifications
You must be signed in to change notification settings - Fork 42
/
check_format.py
52 lines (44 loc) · 1.65 KB
/
check_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
import sys
import subprocess
import os
from subprocess import Popen, PIPE
import difflib
import argparse
#
# check formatting of the files with clang-format >= 17.0
#
parser = argparse.ArgumentParser(description='Check file formatting with clang-format')
parser.add_argument('-f', '--fmt', action='store_true', help='Apply formatting to the file(s)')
args = parser.parse_args()
env_copy = os.environ.copy()
all_files = [name.strip() for name in sys.stdin.readlines()]
files = []
for f in all_files:
extension = os.path.splitext(f)[1][1:]
if extension in ['h', 'hpp', 'cpp']:
files.append(f)
print("files to check", files)
enable_shell = False
status = 0
for name in files:
with open(name, 'r') as f:
original = f.read()
p1 = subprocess.Popen(["sed", r"s/#pragma omp/\/\/#pragma omp/g", name], shell=enable_shell, stdout=subprocess.PIPE)
p2 = subprocess.Popen(["clang-format", "-style=file"], shell=enable_shell, stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(["sed", r"s/\/\/ *#pragma omp/#pragma omp/g"], shell=enable_shell, stdin=p2.stdout, stdout=subprocess.PIPE)
formatted = p3.communicate()[0].decode('utf-8')
p3.wait()
# save formatted file
if args.fmt:
with open(name, 'w') as f:
f.write(formatted)
# report diff
else:
if original == formatted:
print(f'{name}: OK')
else:
print(f'{name}: non-zero diff found')
for line in difflib.unified_diff(original.splitlines(), formatted.splitlines(), fromfile='original', tofile='formatted'):
print(line)
status += 1
sys.exit(status)