-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev
executable file
·195 lines (157 loc) · 5.15 KB
/
dev
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/env python3
# Copyright (c) 2023 Graphcore Ltd. All rights reserved.
"""Dev task launcher."""
import argparse
import datetime
import os
import subprocess
import sys
from pathlib import Path
from typing import Any, Callable, Iterable, List, Optional, TypeVar
# Utilities
def run(command: Iterable[Any], gdb: bool = False) -> None:
"""Run a command, terminating on failure."""
cmd = [str(arg) for arg in command if arg is not None]
if gdb:
cmd = ["gdb", "-ex", "catch throw", "-ex", "run", "--args"] + cmd
print("$ " + " ".join(cmd), file=sys.stderr)
environ = os.environ.copy()
environ["PYTHONPATH"] = f"{os.getcwd()}:{environ.get('PYTHONPATH', '')}"
exit_code = subprocess.call(cmd, env=environ)
if exit_code:
sys.exit(exit_code)
T = TypeVar("T")
def cli(*args: Any, **kwargs: Any) -> Callable[[T], T]:
"""Declare a CLI command / arguments for that command."""
def wrap(func: T) -> T:
if not hasattr(func, "cli_args"):
setattr(func, "cli_args", [])
if args or kwargs:
getattr(func, "cli_args").append((args, kwargs))
return func
return wrap
# Commands
PYTHON_ROOTS = ["poptorch_experimental_addons", "examples", "tests", "dev", "setup.py"]
@cli()
def build() -> None:
"""build C++ shared library"""
run(["make", "-j"])
@cli("-s", "--no-capture", action="store_false", dest="capture")
@cli("-k", "--filter")
@cli("--gdb", action="store_true")
def tests(capture: bool, filter: Optional[str], gdb: bool) -> None:
"""run Python tests"""
build()
run(
[
"python",
"-m",
"pytest",
"tests",
None if filter else "--cov=poptorch_experimental_addons",
*(["-k", filter] if filter else []),
None if capture else "-s",
],
gdb=gdb,
)
@cli("command", nargs="*")
@cli("--gdb", action="store_true")
def python(command: List[Any], gdb: bool) -> None:
build()
run(["python"] + command, gdb=gdb)
@cli()
def lint() -> None:
"""run static analysis"""
run(["python", "-m", "flake8", *PYTHON_ROOTS])
run(["python", "-m", "mypy", *PYTHON_ROOTS])
@cli("--check", action="store_true")
def format(check: bool) -> None:
"""autoformat all sources"""
run(["python", "-m", "black", "--check" if check else None, *PYTHON_ROOTS])
run(["python", "-m", "isort", "--check" if check else None, *PYTHON_ROOTS])
cpp_files = Path("poptorch_experimental_addons/cpp").glob("**/*.[ch]pp")
run(
[
"clang-format",
*(["-Werror", "--dry-run"] if check else ["-i"]),
*map(str, cpp_files),
]
)
@cli()
def copyright() -> None:
"""check for Graphcore copyright headers on relevant files"""
command = (
"find Makefile " + " ".join(PYTHON_ROOTS) + " -type f -not -name *.pyc"
" | xargs grep -L 'Copyright (c) 202. Graphcore Ltd[.] All rights reserved[.]'"
)
print(f"$ {command}", file=sys.stderr)
# Note: grep exit codes are not consistent between versions, so we don't use
# check=True
output = (
subprocess.run(
command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
.stdout.decode()
.strip()
)
if output:
print(
"Error - failed copyright header check in:\n "
+ output.replace("\n", "\n "),
file=sys.stderr,
)
print("Template(s):")
comment_prefixes = {
{".cpp": "//"}.get(Path(f).suffix, "#") for f in output.split("\n")
}
for prefix in comment_prefixes:
print(
f"{prefix} Copyright (c) {datetime.datetime.now().year}"
" Graphcore Ltd. All rights reserved.",
file=sys.stderr,
)
sys.exit(1)
@cli()
def doc() -> None:
"""generate API documentation"""
subprocess.call(["rm", "-r", "doc/poptorch_experimental_addons"])
run(
[
"python",
"-m",
"pdoc",
"--html",
"--output-dir",
"doc",
"poptorch_experimental_addons",
]
)
@cli("--skip", nargs="*", default=[], help="commands to skip")
def ci(skip: List[str] = []) -> None:
"""run all continuous integration tests & checks"""
if "tests" not in skip:
tests(capture=True, filter=None, gdb=False)
if "lint" not in skip:
lint()
if "format" not in skip:
format(check=True)
if "copyright" not in skip:
copyright()
if "doc" not in skip:
doc()
# Script
def _main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.set_defaults(action=ci)
subs = parser.add_subparsers()
for key, value in globals().items():
if hasattr(value, "cli_args"):
sub = subs.add_parser(key.replace("_", "-"), help=value.__doc__)
for args, kwargs in value.cli_args:
sub.add_argument(*args, **kwargs)
sub.set_defaults(action=value)
cli_args = vars(parser.parse_args())
action = cli_args.pop("action")
action(**cli_args)
if __name__ == "__main__":
_main()