-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat.py
64 lines (55 loc) · 2.04 KB
/
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
import argparse
import difflib
import os
import subprocess
import sys
from typing import List
IGNORE_DIRS = ["build"]
EXTENSIONS = [".cpp", ".hpp"]
def main(dirs: List[str], fix: bool):
changed_paths: List[str] = []
for root in dirs:
for dirpath, dirnames, filenames in os.walk(root):
# Filter out directories to skip
dirnames[:] = filter(lambda d: d not in IGNORE_DIRS, dirnames)
for name in filenames:
path = os.path.join(dirpath, name)
if any(name.endswith(ext) for ext in EXTENSIONS):
if fix:
subprocess.check_call(["clang-format", "-i", path])
continue
stdout = (
subprocess.check_output(["clang-format", path])
.decode("utf-8")
.splitlines()
)
with open(path, "r") as f:
orig = [line.rstrip("\n") for line in f]
diff = difflib.unified_diff(
orig,
stdout,
fromfile=path,
tofile=f"clang-format {path}",
lineterm="",
)
had_diff = False
for line in diff:
had_diff = True
print(line)
if had_diff:
changed_paths.append(path)
print("\n")
if changed_paths:
print(f"{len(changed_paths)} files need to be formatted:")
for path in changed_paths:
print(f" {path}")
return 1
return 0
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Run clang-format and display changed files."
)
parser.add_argument("dirs", help="List of directories to search", nargs="+")
parser.add_argument("--fix", action="store_true")
args = parser.parse_args()
sys.exit(main(**vars(args)))