-
Notifications
You must be signed in to change notification settings - Fork 6
/
format_code.py
74 lines (65 loc) · 1.99 KB
/
format_code.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
from faasmtools.env import LLVM_NATIVE_VERSION
from invoke import task
from tasks.util.env import PROJ_ROOT
from subprocess import run
@task(default=True)
def format(ctx, check=False):
"""
Format Python and C++ code
"""
# ---- Python formatting ----
files_to_check = (
run(
'git ls-files -- "*.py"',
shell=True,
check=True,
cwd=PROJ_ROOT,
capture_output=True,
)
.stdout.decode("utf-8")
.split("\n")[:-1]
)
black_cmd = [
"python3 -m black",
"{}".format("--check" if check else ""),
" ".join(files_to_check),
]
black_cmd = " ".join(black_cmd)
run(black_cmd, shell=True, check=True, cwd=PROJ_ROOT)
flake8_cmd = [
"python3 -m flake8",
" ".join(files_to_check),
]
flake8_cmd = " ".join(flake8_cmd)
run(flake8_cmd, shell=True, check=True, cwd=PROJ_ROOT)
# ---- C/C++ formatting ----
files_to_check = (
run(
'git ls-files -- "*.h" "*.cpp" "*.c"',
shell=True,
check=True,
cwd=PROJ_ROOT,
capture_output=True,
)
.stdout.decode("utf-8")
.split("\n")[:-1]
)
clang_cmd = [
"clang-format-{}".format(LLVM_NATIVE_VERSION.split(".")[0]),
"--dry-run --Werror" if check else "-i",
"-style=file",
" ".join(files_to_check),
]
clang_cmd = " ".join(clang_cmd)
run(clang_cmd, shell=True, check=True, cwd=PROJ_ROOT)
# ---- Append newlines to C/C++ files if not there ----
for f in files_to_check:
# Append opens the file from the end, but there is no easy way to read
# just one character backwards unless you open the file as a byte
# stream, which then makes it very involved to compare against the
# newline character
with open(f, "a+") as fh:
fh.seek(0)
read = fh.read()
if read[-1] != "\n":
fh.write("\n")