-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
noxfile.py
448 lines (359 loc) · 12 KB
/
noxfile.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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
"""Task runner for the developer
Usage
-----
nox -l
nox -s <session>
nox -k <keyword>
or:
make <session>
execute ``make list-sessions```` or ``nox -l`` for a list of sessions.
"""
import os
import re
import shlex
import shutil
from functools import partial
from pathlib import Path
import nox
PACKAGE = "snek5000"
CWD = Path.cwd()
if (CWD / "poetry.lock").exists():
BUILD_SYSTEM = "poetry"
PACKAGE_SPEC = "pyproject.toml"
else:
BUILD_SYSTEM = "setuptools"
PACKAGE_SPEC = "setup.cfg"
try:
NEK_SOURCE_ROOT = os.environ["NEK_SOURCE_ROOT"]
except KeyError:
raise RuntimeError(
"Environment variable NEK_SOURCE_ROOT should be set "
"pointing to Nek5000 top level directory."
)
TEST_ENV_VARS = {
"NEK_SOURCE_ROOT": NEK_SOURCE_ROOT,
"SNEK_DEBUG": "1",
}
if os.getenv("CI"):
TEST_ENV_VARS["PYTEST_ADDOPTS"] = "--color=yes"
EXTRA_REQUIRES = ("main", "docs", "tests", "dev")
no_venv_session = partial(nox.session, venv_backend="none")
nox.options.sessions = ["tests"]
def run_ext(session, cmd):
"""Run an external command, i.e. outside a nox managed virtual envionment"""
session.run(*shlex.split(cmd), external=True)
def rmdir(path_dir: str):
if Path(path_dir).exists():
shutil.rmtree(path_dir)
def poetry_install(session, *args):
"""Install with dependencies pinned in pyproject.toml"""
run_ext(session, "python -m poetry install " + " ".join(args))
def pip_install(session, filename, *args):
"""Install with dependencies pinned in requirements/*.txt"""
run_ext(
session,
f"python -m pip install -r requirements/{filename}.txt " + " ".join(args),
)
def pip_sync(session, filename):
"""Reset developer environment with dependencies pinned in requirements/dev.txt"""
run_ext(session, f"python -m piptools sync requirements/{filename}.txt")
@no_venv_session
def install(session):
"""Install package."""
if BUILD_SYSTEM == "poetry":
poetry_install(session)
else:
pip_install(session, "main", ".")
@no_venv_session
def develop(session):
"""Install developer environment."""
if BUILD_SYSTEM == "poetry":
poetry_install(session, "--with=dev")
else:
pip_install(session, "dev")
@no_venv_session
def sync(session):
"""Sync developer environment."""
if BUILD_SYSTEM == "poetry":
poetry_install(session, "--sync", "--with=dev")
else:
pip_sync(session, "dev")
@no_venv_session
def requires(session):
"""Pin dependencies"""
if BUILD_SYSTEM == "poetry":
run_ext(session, "python -m poetry lock --no-update")
else:
session.notify("pip-compile")
@nox.session(name="pip-compile", reuse_venv=True)
@nox.parametrize("extra", [nox.param(extra, id=extra) for extra in EXTRA_REQUIRES])
def pip_compile(session, extra):
"""Pin dependencies to requirements/*.txt
How to run all in parallel::
pipx install nox
make -j requirements
or::
nox -l | awk '/pip-compile/{print $2}' | xargs -P6 -I_ nox -s _
"""
session.install("pip-tools")
req = Path("requirements")
if extra == "main":
in_extra = ""
in_file = ""
else:
in_extra = f"--extra {extra}"
in_file = req / "vcs_packages.in"
out_file = req / f"{extra}.txt"
session.run(
*shlex.split(
"python -m piptools compile --resolver backtracking --quiet -U "
f"{in_extra} {in_file} {PACKAGE_SPEC} "
f"-o {out_file}"
),
*session.posargs,
)
session.log(f"Removing absolute paths from {out_file}")
packages = out_file.read_text()
rel_path_packages = packages.replace("file://" + str(Path.cwd().resolve()), ".")
# special cases for snek5000-canonical and snek5000-tgv
for package in ("snek5000-canonical", "snek5000-tgv"):
rel_path_packages = rel_path_packages.replace(f"{package} @ ", "")
if extra == "tests":
tests_editable = out_file.parent / out_file.name.replace(
"tests", "tests-editable"
)
session.log(f"Copying {out_file} with -e flag in {tests_editable}")
tests_editable.write_text(rel_path_packages)
session.log(f"Removing -e flag in {out_file}")
rel_path_packages = re.sub(r"^-e\ \.", ".", rel_path_packages, flags=re.M)
session.log(f"Writing {out_file}")
out_file.write_text(rel_path_packages)
def install_with_tests(session, args=()):
if BUILD_SYSTEM == "poetry":
session.install("poetry")
session.run("python", "-m", "poetry", "install", "--with=tests", *args)
session.run("python", "-m", "poetry", "env", "info")
return "python", "-m", "poetry", "run", "pytest"
else:
session.install("-r", "requirements/tests.txt", *args)
return "python", "-m", "pytest"
@nox.session
def tests(session):
"""Execute unit-tests using pytest"""
pytest_cmd = install_with_tests(session)
session.run(
*pytest_cmd,
*session.posargs,
env=TEST_ENV_VARS,
)
@no_venv_session(name="tests-cov")
def tests_cov(session):
"""Execute unit-tests using pytest+pytest-cov"""
session.notify(
"tests",
[
"--cov",
"--cov-config=pyproject.toml",
"--no-cov-on-fail",
"--cov-report=term-missing",
*session.posargs,
],
)
@nox.session(name="coverage-html")
def coverage_html(session, nox=False):
"""Generate coverage report in HTML. Requires `tests-cov` session."""
report = Path.cwd() / ".coverage" / "html" / "index.html"
session.install("coverage[toml]")
session.run("coverage", "html")
print("Code coverage analysis complete. View detailed report:")
print(f"file://{report}")
@no_venv_session(name="format")
def format_(session):
"""Run pre-commit hooks on all files to set and lint code-format"""
run_ext(session, "pre-commit install")
run_ext(session, "pre-commit run --all-files")
@nox.session
def lint(session):
"""Run pre-commit hooks on files which differ in the current branch from origin/HEAD."""
remote = "origin/HEAD" if not session.posargs else session.posargs[0]
session.install("pre-commit")
session.run("pre-commit", "install")
session.run("pre-commit", "run", "--from-ref", remote, "--to-ref", "HEAD")
def _prepare_docs_session(session):
session.install("-r", "requirements/docs.txt")
session.chdir("./docs")
build_dir = Path.cwd() / "_build"
source_dir = "."
output_dir = str(build_dir.resolve() / "html")
return source_dir, output_dir
@nox.session
def docs(session):
"""Build documentation using Sphinx."""
source, output = _prepare_docs_session(session)
session.run(
"python", "-m", "sphinx", "-b", "html", *session.posargs, source, output
) # Same as sphinx-build
print("Build finished.")
print(f"file://{output}/index.html")
@nox.session(name="docs-autobuild")
def docs_autobuild(session):
"""Build documentation using sphinx-autobuild."""
source, output = _prepare_docs_session(session)
session.run(
"python",
"-m",
"sphinx_autobuild",
"--watch",
"../src",
"--re-ignore",
r"(_build|generated)\/.*",
source,
output,
) # Same as sphinx-autobuild
print("Build finished.")
print(f"file://{output}/index.html")
@no_venv_session
def ctags(session):
"""Runs universal-ctags to build .tags file"""
sources = {
"nek5000": str(Path(NEK_SOURCE_ROOT) / "core"),
"snek5000": "src/snek5000",
}
output = ".tags"
excludes = " ".join(
(
f"--exclude={pattern}"
for pattern in (
".snakemake",
"__pycache__",
"obj",
"logs",
"*.tar.gz",
"*.f?????",
)
)
)
run_ext(
session,
f"ctags -f {output} --language-force=Fortran -R {sources['nek5000']}",
)
run_ext(session, f"ctags -f {output} {excludes} --append -R {sources['snek5000']}")
@no_venv_session
def testpypi(session):
"""Release clean, build, upload to TestPyPI"""
session.notify("release-clean")
session.notify("release-build")
session.notify("release-upload", ["--repository", "testpypi"])
@no_venv_session
def pypi(session):
"""Release clean, download from TestPyPI, test, upload to PyPI"""
session.notify("release-clean")
# NOTE: parametrizing dist_type ends up in erraneous deduplication of sessions
# by nox
for dist_type in ("no-binary", "only-binary"):
session.notify(f"download-testpypi(dist_type='{dist_type}')")
session.notify(f"release-tests(dist_type='{dist_type}')")
session.notify("release-upload", ["--repository", "pypi"])
@nox.session(name="download-testpypi")
@nox.parametrize("dist_type", ["no-binary", "only-binary"])
def download_testpypi(session, dist_type):
"""Download from TestPyPI and run tests"""
(Path.cwd() / "dist").mkdir(exist_ok=True)
session.chdir("./dist")
git_tags = session.run(
"git", "tag", "--list", "--sort=committerdate", external=True, silent=True
)
latest_version = git_tags.splitlines()[-1]
spec = f"{PACKAGE}=={latest_version}"
session.run(
"python",
"-m",
"pip",
"index",
"versions",
"--index-url",
"https://test.pypi.org/simple",
"--pre",
PACKAGE,
)
session.run(
"python",
"-m",
"pip",
"download",
"--index-url",
"https://test.pypi.org/simple",
"--extra-index-url",
"https://pypi.org/simple",
"--pre",
"--no-deps",
f"--{dist_type}",
PACKAGE,
spec,
)
@nox.session(name="release-tests")
@nox.parametrize("dist_type", ["no-binary", "only-binary"])
def release_tests(session, dist_type):
"""Execute test suite with build / downloaded package in ./dist"""
if dist_type == "only-binary":
pattern = "*.whl"
else:
pattern = "*.tar.gz"
if BUILD_SYSTEM == "poetry":
poetry_conf = CWD / "poetry.toml"
assert (
not poetry_conf.exists()
), "Poetry local configuration exists. Please remove to continue"
session.install("poetry")
session.run(
"python",
"-m",
"poetry",
"config",
"--local",
"virtualenvs.create",
"false",
)
pytest_cmd = install_with_tests(session, ["--no-root"])
else:
pytest_cmd = install_with_tests(session)
dist_packages = [str(p) for p in Path("./dist").glob(pattern)]
session.install(*dist_packages)
try:
session.run(
*pytest_cmd,
env=TEST_ENV_VARS,
)
finally:
if BUILD_SYSTEM == "poetry":
poetry_conf.unlink()
@no_venv_session(name="release-clean")
def release_clean(session):
"""Remove build and dist directories"""
session.log("Removing build and dist")
rmdir("./build/")
rmdir("./dist/")
@nox.session(name="release-build")
def release_build(session):
"""Build package into dist."""
session.install("build")
session.run("python", "-m", "build")
@nox.session(name="release-upload")
def release_upload(session):
"""Upload dist/* to repository testpypi (default, must be configured in ~/.pypirc).
Also accepts positional arguments to `twine upload` command.
"""
session.install("twine")
session.run("twine", "check", "--strict", "dist/*")
args = session.posargs
# See
# https://pypi.org/help/#apitoken and
# https://twine.readthedocs.io/en/latest/#environment-variables
env = {"TWINE_USERNAME": "__token__"}
test_pypi_token = os.getenv("TEST_PYPI_TOKEN")
pypi_token = os.getenv("PYPI_TOKEN")
if "testpypi" in args and test_pypi_token:
env["TWINE_PASSWORD"] = test_pypi_token
elif pypi_token:
env["TWINE_PASSWORD"] = pypi_token
session.run("twine", "upload", *args, "dist/*", env=env)