-
Notifications
You must be signed in to change notification settings - Fork 8
/
dev
executable file
·183 lines (147 loc) · 4.79 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
#!/usr/bin/env python
# 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]) -> None:
"""Run a command, terminating on failure."""
cmd = [str(arg) for arg in command if arg is not None]
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 = ["unit_scaling", "dev", "examples"]
@cli("-k", "--filter")
def tests(filter: Optional[str]) -> None:
"""run Python tests"""
run(
[
"python",
"-m",
"pytest",
"unit_scaling",
None if filter else "--cov=unit_scaling",
*(["-k", filter] if filter else []),
]
)
@cli("commands", nargs="*")
def python(commands: List[Any]) -> None:
"""run Python with the current directory on PYTHONPATH, for development"""
run(["python"] + commands)
@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])
@cli()
def copyright() -> None:
"""check for Graphcore copyright headers on relevant files"""
command = (
f"find {' '.join(PYTHON_ROOTS)} -type f -not -name *.pyc -not -name *.json"
" -not -name .gitignore -not -name *_version.py"
" | 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", "docs/generated", "docs/_build"])
run(
[
"make",
"-C",
"docs",
"html",
]
)
@cli(
"-s",
"--skip",
nargs="*",
default=[],
choices=["tests", "lint", "format", "copyright"],
help="commands to skip",
)
def ci(skip: List[str] = []) -> None:
"""run all continuous integration tests & checks"""
if "tests" not in skip:
tests(filter=None)
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:
# Build an argparse command line by finding globals in the current module
# that are marked via the @cli() decorator. Each one becomes a subcommand
# running that function, usage "$ ./dev fn_name ...args".
parser = argparse.ArgumentParser(description=__doc__)
parser.set_defaults(command=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(command=value)
cli_args = vars(parser.parse_args())
command = cli_args.pop("command")
command(**cli_args)
if __name__ == "__main__":
_main()