-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake.py
More file actions
183 lines (143 loc) · 5.79 KB
/
make.py
File metadata and controls
183 lines (143 loc) · 5.79 KB
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
# SPDX-FileCopyrightText: 2025-2026 Ohad Livne <libohad-dev@proton.me>
#
# SPDX-License-Identifier: CC0-1.0
import shutil
import subprocess
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from pathlib import Path
from tempfile import TemporaryDirectory
type Target = Callable[[], None]
targets: dict[str, tuple[str, Target]] = {}
PYTEST_BASE_COMMAND = ["pytest", "-vv", "--numprocesses", "auto"]
COVERAGE_BASE_COMMAND = PYTEST_BASE_COMMAND + [
"--cov",
"src",
"--cov",
"tests",
"--cov-fail-under",
"0",
"--cov-report=",
]
def target(description: str) -> Callable[[Target], Target]:
def register_target(tgt: Target) -> Target:
from caseconverter import kebabcase # type: ignore[import-not-found]
targets[kebabcase(tgt.__name__)] = description, tgt
return tgt
return register_target
def execute(args: list[str], capture_output: bool = True) -> str:
output = subprocess.run(args, capture_output=capture_output, check=True, text=True)
if capture_output:
return output.stdout.strip()
else:
return ""
def clean_coverage_files() -> None:
for cov_file in Path.cwd().glob(".coverage*"):
cov_file.unlink()
shutil.rmtree(Path.cwd() / "htmlcov", ignore_errors=True)
def combine_container_coverage(container_cov_dir: Path) -> None:
for cov_file in container_cov_dir.glob(".coverage.*"):
shutil.move(cov_file, Path.cwd())
execute(["coverage", "combine", "--append"])
@contextmanager
def coverage_directory() -> Iterator[Path]:
with TemporaryDirectory(prefix="temper-edit-coverage-") as tmpdir:
try:
tmp_path = Path(tmpdir)
tmp_path.chmod(0o777)
yield tmp_path
finally:
combine_container_coverage(Path(tmpdir))
def coverage_run_command(container_cov_dir: Path) -> list[str]:
return COVERAGE_BASE_COMMAND + ["--container-coverage-dir", str(container_cov_dir), "tests"]
@target("Build container images used by tests. Fails fast if any image build fails.")
def build_test_images() -> None:
execute(PYTEST_BASE_COMMAND + ["--setup-only", "tests/test_image_build.py::test_image_build"], capture_output=False)
@target("Verify that the code has full test coverage")
def check_coverage() -> None:
build_test_images()
clean_coverage_files()
with coverage_directory() as container_cov_dir:
execute(coverage_run_command(container_cov_dir), capture_output=False)
execute(["coverage", "report", "--fail-under", "100"], capture_output=False)
@target("Find all the uses of linting-avoiding pragmas in the code")
def list_pragmas() -> None:
from pathlib import Path
tracked_files = sorted(execute(["git", "ls-tree", "-r", "--name-only", "HEAD"]).splitlines())
this_file = str(Path(__file__).relative_to(Path.cwd()))
tracked_files.remove(this_file)
try:
pragmas = execute(
[
"grep",
"--line-number",
"--regexp",
"# pragma:",
"--regexp",
"# type: ignore",
"--regexp",
"# noqa:",
]
+ tracked_files
)
except subprocess.CalledProcessError as e:
if e.returncode == 1:
print("No matching pragmas found")
return
else:
print(e.stdout)
raise
print(pragmas)
pragma_lines = pragmas.splitlines()
pragma_files = {line.partition(":")[0] for line in pragma_lines}
num_lines = "one match" if len(pragma_lines) == 1 else f"{len(pragma_lines)} matches"
num_files = "one file" if len(pragma_files) == 1 else f"{len(pragma_files)} files"
print(f"Found {num_lines} in {num_files}")
# Note: The Makefile regeneration command should also be a .PHONY target with no
# dependency. Writing a it as a recipe with an explicit Makefile output
# and dependency on make.py would mean that manual changes to the Makefile
# would persist and only be overridden at an undetermined point later,
# rather than being rectified immediately and conspicuously at commit time.
@target("Recreate the Makefile")
def makefile() -> None:
from pathlib import Path
from textwrap import dedent
content = dedent(f"""\
# This is an autogenerated file. Do not change it manually.
# Any changes you make here WILL be overwritten!
TARGETS = {" ".join(sorted(targets))}
.PHONY: $(TARGETS)
PYTHON = python
$(TARGETS):
\t$(PYTHON) make.py $@
""")
with Path("Makefile").open(mode="w", encoding="utf-8") as makefile:
makefile.write(content)
@target("Run the full test suite and report the code coverage")
def test() -> None:
build_test_images()
clean_coverage_files()
with coverage_directory() as container_cov_dir:
execute(coverage_run_command(container_cov_dir), capture_output=False)
execute(["coverage", "report"], capture_output=False)
@target("Run the full test suite and open the coverage report in a browser")
def test_html() -> None:
build_test_images()
clean_coverage_files()
with coverage_directory() as container_cov_dir:
execute(coverage_run_command(container_cov_dir), capture_output=False)
execute(["coverage", "html"], capture_output=False)
execute(["xdg-open", "htmlcov/index.html"])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser("Short scripts for developing the package")
subparsers = parser.add_subparsers(title="Available targets")
for target_name, (desc, tgt) in sorted(targets.items()):
tgt_subparser = subparsers.add_parser(
name=target_name,
description=desc,
help=desc,
)
tgt_subparser.set_defaults(target_func=tgt)
args = parser.parse_args()
args.target_func()