-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat-code
executable file
·76 lines (58 loc) · 2.01 KB
/
format-code
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
#!/usr/bin/env python
"""
Auto-format all the code in the benchmark repo.
Usage:
code-format [PATH]
PATH is optional path to benchmark repo. Default is current directory.
"""
import os
import sys
from pathlib import Path
from typing import Callable, List
def clang_format(path) -> None:
"""
Format a file with clang-format.
"""
print(f"Running clang-format on {path}")
os.system(f"clang-format -i {path}")
def autopep8_format(path) -> None:
"""
Format a file with autopep8.
"""
print(f"Running autopep8 on {path}")
os.system(f"autopep8 -i {path}")
def format_files(root: Path, extensions: List[str] = None, exclude_dirs: List[str] = None,
formatter: Callable = None) -> None:
"""
Search for and format all files found under a directory.
Args:
root (pathlib.Path): Path to crawl looking for files to format
extensions (List[str]): File extensions to look for
exclude_dirs (List[str]): List of directories (relative to root) to exclude from the search.
formatter (Callable): The function to call on each found file path
"""
extensions = extensions or []
exclude_dirs = [Path(root) / d for d in exclude_dirs or []]
for dirpath, dirnames, filenames in os.walk(root):
for name in filenames:
path = Path(dirpath) / name
if any([name.endswith(ext) for ext in extensions]):
formatter(path)
# prune excluded directories
dirnames[:] = [d for d in dirnames if Path(
dirpath) / d not in exclude_dirs]
def main() -> None:
"""
Find and format the source code files in this project.
"""
root = Path(sys.argv[1] if len(sys.argv) > 1 else "")
# Format C++ code with clang-format
format_files(
root,
extensions=[".h", ".cpp"],
exclude_dirs=["build", "vendor"],
formatter=clang_format)
# Format python script (this script)
autopep8_format(root / "format-code")
if __name__ == "__main__":
main()