Repository navigation
Expand file tree
/
Copy pathnoxfile.py
More file actions
723 lines (570 loc) · 23.9 KB
/
Copy pathnoxfile.py
File metadata and controls
723 lines (570 loc) · 23.9 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
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# /// script
# requires-python = ">=3.12"
# dependencies = ["nox", "nox-uv", "uv"]
# ///
"""
Nox is an automation tool used by PlasmaPy to run tests, build
documentation, and perform other checks. Nox sessions are defined in
noxfile.py.
Running `nox` without arguments will run tests with the version of
Python that `nox` is installed under, skipping slow tests. To invoke a
nox session, enter the top-level directory of this repository and run
`nox -s "<session>"`, where <session> is replaced with the name of the
session. To list available sessions, run `nox -l`.
The tests can be run with the following options:
* "all": run all tests
* "skipslow": run tests, except tests decorated with `@pytest.mark.slow`
* "cov": run all tests with code coverage checks
* "lowest-direct" : run all tests with lowest versions of direct dependencies
* "lowest-direct-skipslow" : run non-slow tests with lowest versions of direct dependencies
Doctests are run only for the most recent versions of Python and
PlasmaPy dependencies, and not when code coverage checks are performed.
Some of the checks require the most recent supported version of Python
to be installed.
Nox documentation: https://nox.thea.codes
"""
import datetime
import os
import pathlib
import re
import shutil
import sys
import nox # ty:ignore[import-not-found]
import nox_uv # ty:ignore[import-not-found]
# SPEC 0 indicates that scientific Python packages should support
# versions of Python that have been released in the last 3 years, or
# equivalently the most three recently released versions of Python.
# The minimum version of Python should be incremented immediately
# following the first release after October of each year.
SUPPORTED_PYTHON_VERSIONS: tuple[str, ...] = ("3.12", "3.13", "3.14")
SUPPORTED_OPERATING_SYSTEMS: tuple[str, ...] = ("linux", "macos", "windows")
MAXPYTHON = max(SUPPORTED_PYTHON_VERSIONS)
MINPYTHON = min(SUPPORTED_PYTHON_VERSIONS)
ROOT_DIR = pathlib.Path(__file__).parent
CURRENT_PYTHON = f"{sys.version_info.major}.{sys.version_info.minor}"
# Define what sessions get run when running `nox` without a session
nox.options.sessions = [f"tests-{CURRENT_PYTHON}(all)"]
# The documentation should be build always using the same version of
# Python, which should be the latest version of Python supported by Read
# the Docs. Because Read the Docs takes some time to support new
# releases of Python, DOCPYTHON should stay independent of MAXPYTHON.
# Changing DOCPYTHON also requires updating .readthedocs.yml and the
# GitHub workflows for building the documentation.
DOCPYTHON = "3.14"
nox.options.default_venv_backend = "uv"
UV_SYNC = ("uv", "sync", "--no-progress", "--frozen")
RUNNING_ON_CI: bool = os.getenv("CI") is not None
RUNNING_ON_RTD: bool = os.getenv("READTHEDOCS") is not None
def _create_lockfile_pr_message(uv_output: str, session: nox.Session) -> None:
"""
Create the pull request message during requirements updates.
This function copies a GitHub flavored Markdown template to a new
file and appends a table containing the updated requirements, with
links to the corresponding PyPI pages. This file is then used as the
body of the pull request message used in the workflow for updating
requirements.
⚠️ This function requires that `uv.lock` existed before
`uv lock --upgrade` was run.
Parameters
----------
uv_output : str
The multi-line output of ``session.run(..., silent=True)``.
"""
pr_template = pathlib.Path(
ROOT_DIR / "./.github/content/upgrade-uv-lock-pr-template.md",
)
pr_message = pathlib.Path(ROOT_DIR / "./.github/content/upgrade-uv-lock-pr-body.md")
shutil.copy(pr_template, pr_message)
preamble = [
"",
"| package | old version | new version |",
"| :-----: | :---------: | :---------: |",
]
lines = []
for line in uv_output.splitlines():
if line.startswith("Resolved") or not line:
continue
if not line.startswith("Updated"):
session.warn(f"Line not added to table: {line}")
continue
try:
# An example line is "Updated nbsphinx v0.9.6 -> v0.9.7"
_, package_name_, old_version_, _, new_version_ = line.strip().split()
except ValueError:
session.warn(f"Line not added to table: {line}:")
continue
old_version = f"{old_version_.removeprefix('v')}"
new_version = f"{new_version_.removeprefix('v')}"
pypi_link = f"https://pypi.org/project/{package_name_}/{new_version}"
package_name = f"[`{package_name_}`]({pypi_link})"
lines.append(f"| {package_name} | `{old_version}` | `{new_version}` |")
table_of_package_upgrades = "\n".join(preamble + lines)
with pr_message.open(mode="a") as file:
file.write(table_of_package_upgrades)
@nox.session
def lock(session: nox.Session) -> None:
"""
Upgrade Python environments used in CI, with a dependency cooldown.
This session upgrades uv.lock: the cross-platform lockfile that
defines the exact Python environments used when running tests,
building documentation, and performing continuous integration (CI)
checks.
When run in CI, this session generates a file that contains the pull
request message for the GitHub workflow that uses this session
(:file:`.github/workflows/upgrade-uv-lock.yml`).
"""
uv_lock = (
"uv",
"lock",
"--upgrade",
"--no-progress",
*session.posargs,
)
try:
# Use session.run() with silent=True to return the command output
uv_output: str | bool = session.run(*uv_lock, silent=RUNNING_ON_CI)
except nox.command.CommandFailed:
session.warn("⚠️ uv.lock is invalid, likely due to a git merge conflict.")
session.log(
"📥 Checking out uv.lock from the branch being merged into this one.",
)
session.log(
"🪧 If this next attempt is unsuccessful, delete uv.lock and try again.",
)
session.run("git", "checkout", "--theirs", "--", "uv.lock", external=True)
uv_output: str | bool = session.run(*uv_lock, silent=RUNNING_ON_CI)
if RUNNING_ON_CI:
session.log(uv_output)
_create_lockfile_pr_message(uv_output=uv_output, session=session) # ty:ignore[invalid-argument-type]
@nox.session
def validate_lockfile(session: nox.Session) -> None:
"""
Ensure that uv.lock is consistent with pyproject.toml.
This check is normally performed locally when running pre-commit or
prek. Because pre-commit.ci blocks network access, this check is
instead done in CI via a GitHub workflow that calls this session.
"""
if RUNNING_ON_CI:
errmsg = (
"The Python environments in file 'uv.lock' are inconsistent "
"with the requirements defined in 'pyproject.toml'. "
"After installing Nox, this problem can be fixed by running "
"`nox -s validate_lockfile` in the top-level directory of "
"your clone of PlasmaPy, and then pushing the updated "
"'uv.lock' to GitHub. "
)
else:
errmsg = (
"File 'uv.lock' has been updated for consistency with the "
"requirements defined in 'pyproject.toml'."
)
try:
session.run("uv", "lock", "--no-progress")
except nox.command.CommandFailed:
session.error(errmsg)
# Define pytest flags that are only sometimes used. Define flags that
# are always used in tool.pytest.addopts in pyproject.toml instead of
# noxfile.py, since that allows users to run `pytest` and get
WITH_DOCTESTS: tuple[str, ...] = ("--doctest-modules", "--doctest-continue-on-failure")
WITH_COVERAGE: tuple[str, ...] = (
"--cov=plasmapy",
"--cov-report=xml",
"--cov-config=pyproject.toml",
"--cov-append",
"--cov-report",
"xml:coverage.xml",
)
REPORT_WARNINGS_ONCE = ("-W", "once")
SKIPSLOW: tuple[str, ...] = ("-m", "not slow")
test_specifiers: list[nox._parametrize.Param] = [
nox.param("run all tests", id="all"),
nox.param("skip slow tests", id="skipslow"),
nox.param("with code coverage", id="cov"),
nox.param("lowest-direct", id="lowest-direct"),
nox.param("lowest-direct-skipslow", id="lowest-direct-skipslow"),
]
@nox.session(python=SUPPORTED_PYTHON_VERSIONS)
@nox.parametrize("test_specifier", test_specifiers)
def tests(session: nox.Session, test_specifier: nox._parametrize.Param) -> None:
"""Run tests with pytest."""
options: list[str] = []
if test_specifier in {"skip slow tests", "lowest-direct-skipslow"}:
options += SKIPSLOW
if test_specifier == "with code coverage":
options += WITH_COVERAGE
# There may be some warnings that got fixed later with the oldest
# allowed versions of dependencies
if test_specifier in {"lowest-direct", "lowest-direct-skipslow"}:
options += REPORT_WARNINGS_ONCE
# Doctests are only run with the most recent versions of Python and
# other dependencies because there may be subtle differences in the
# output between different versions of Python, NumPy, and Astropy.
if session.python == MAXPYTHON and test_specifier not in {"lowest-direct", "cov"}:
options += WITH_DOCTESTS
if gh_token := os.getenv("GH_TOKEN"):
session.env["GH_TOKEN"] = gh_token
match test_specifier:
case "lowest-direct" | "lowest-direct-skipslow":
session.install(
".",
"--resolution=lowest-direct",
"--group=test",
)
case _:
# From https://nox.thea.codes/en/stable/cookbook.html#using-a-lockfile
# If we separate out the lowest-direct tests, then we can use
# @nox_uv.session for tests too.
session.run_install(
*UV_SYNC,
"--group=test",
f"--python={session.virtualenv.location}",
env={"UV_PROJECT_ENVIRONMENT": session.virtualenv.location},
)
session.run("pytest", *options, *session.posargs)
@nox_uv.session(python=MAXPYTHON, uv_groups=["test"])
@nox.parametrize(
["package"],
[
nox.param("numpy", id="numpy"),
nox.param("astropy", id="astropy"),
nox.param("pandas", id="pandas"),
nox.param("xarray", id="xarray"),
nox.param("https://github.com/lmfit/lmfit-py", id="lmfit"),
],
)
def test_upstream(session: nox.Session, package: str) -> None:
"""
Run tests against the development branch of an upstream dependency.
Testing against unreleased versions of upstream dependencies helps
us catch problems before they make it into an official release.
"""
if package.startswith("https"):
session.install(f"git+{package}")
else:
session.run_install(
"uv",
"pip",
"install",
"--upgrade",
package,
env={
"UV_INDEX": "https://pypi.anaconda.org/scientific-python-nightly-wheels/simple",
"UV_INDEX_STRATEGY": "unsafe-best-match",
"UV_PRERELEASE": "allow",
},
)
session.run("uv", "pip", "show", package)
session.run("pytest", *session.posargs)
if RUNNING_ON_RTD:
rtd_output_path = pathlib.Path(os.environ.get("READTHEDOCS_OUTPUT")) / "html" # ty:ignore[invalid-argument-type]
rtd_output_path.mkdir(parents=True, exist_ok=True)
doc_build_dir = str(rtd_output_path)
else:
doc_build_dir = "docs/_build/html"
SPHINX_BASE_COMMAND: list[str] = [
"sphinx-build",
"docs/",
doc_build_dir,
"--nitpicky",
"--quiet",
"--keep-going",
]
if not RUNNING_ON_RTD:
SPHINX_BASE_COMMAND.extend(["--fail-on-warning"])
BUILD_HTML: tuple[str, ...] = ("--builder", "html")
CHECK_HYPERLINKS: tuple[str, ...] = ("--builder", "linkcheck")
DOC_TROUBLESHOOTING_MESSAGE = """
📘 Tips for troubleshooting common documentation build failures are in
PlasmaPy's documentation guide at:
🔗 https://docs.plasmapy.org/en/latest/contributing/doc_guide.html#troubleshooting
"""
@nox_uv.session(python=DOCPYTHON, uv_groups=["docs"])
def docs(session: nox.Session) -> None:
"""
Build documentation with Sphinx.
This session may require installation of pandoc and graphviz.
Configuration file: docs/conf.py
"""
if RUNNING_ON_CI:
session.log(DOC_TROUBLESHOOTING_MESSAGE)
# Can we use pixi or conda to install graphviz and pandoc if they
# are not installed?
session.run_install("dot", "-V", external=True)
session.run_install("pandoc", "--version", external=True)
session.run(*SPHINX_BASE_COMMAND, *BUILD_HTML, *session.posargs)
landing_page = pathlib.Path(doc_build_dir) / "index.html"
if landing_page.exists():
session.log(f"The documentation may be previewed at {landing_page}")
else:
session.error(f"Documentation preview landing page not found: {landing_page}")
@nox_uv.session(python=DOCPYTHON, uv_groups=["docs"])
def htmlzip(session: nox.Session) -> None:
"""Bundle documentation build into a zip file on Read the Docs."""
if not RUNNING_ON_RTD:
session.error("This session must be run on Read the Docs.")
html_build_dir = pathlib.Path(doc_build_dir)
html_landing_page = (html_build_dir / "index.html").resolve()
READTHEDOCS_OUTPUT = html_build_dir.parent
if not html_landing_page.exists():
session.error(
f"No documentation build found at: {html_landing_page}\n"
f"It appears the documentation has not been built.",
)
command = [
"sphinx-build",
"--show-traceback",
"--doctree-dir",
f"{html_build_dir / '.doctrees'}",
"--builder",
"singlehtml",
"--define",
"language=en",
"./docs/", # source directory
f"{READTHEDOCS_OUTPUT / 'htmlzip'}", # output directory
]
session.run(*command)
# now build the zip file
READTHEDOCS_PROJECT = os.environ.get("READTHEDOCS_PROJECT")
READTHEDOCS_LANGUAGE = os.environ.get("READTHEDOCS_LANGUAGE")
READTHEDOCS_VERSION = os.environ.get("READTHEDOCS_VERSION")
# mimic RTD default naming convention
zip_name = f"{READTHEDOCS_PROJECT}-{READTHEDOCS_LANGUAGE}-{READTHEDOCS_VERSION}.zip"
cwd = pathlib.Path.cwd()
session.chdir(f"{READTHEDOCS_OUTPUT / 'htmlzip'}")
session.run("zip", "-r", "-m", f"{zip_name}", ".", external=True)
session.chdir(f"{cwd}")
session.log(f"The htmlzip was placed in: {READTHEDOCS_OUTPUT / 'htmlzip'}")
@nox_uv.session(python=DOCPYTHON, uv_groups=["docs"])
@nox.parametrize(
["site", "repository"],
[
nox.param("github", "sphinx-doc/sphinx", id="sphinx"),
nox.param("github", "readthedocs/sphinx_rtd_theme", id="sphinx_rtd_theme"),
nox.param("github", "spatialaudio/nbsphinx", id="nbsphinx"),
nox.param("github", "plasmapy/plasmapy_sphinx", id="plasmapy_sphinx"),
],
)
def docs_upstream(session: nox.Session, site: str, repository: str) -> None:
"""
Build documentation against the development branch of an upstream dependency.
The purpose of this session is to catch bugs and breaking changes
so that they can be fixed or updated earlier rather than later.
"""
session.install(f"git+https://{site}.com/{repository}")
package = repository.rsplit("/", maxsplit=1)[-1]
session.run_install("uv", "pip", "show", package)
session.run(*SPHINX_BASE_COMMAND, *BUILD_HTML, *session.posargs)
LINKCHECK_TROUBLESHOOTING = """
The Sphinx configuration variables `linkcheck_ignore` and
`linkcheck_allowed_redirects` in `docs/conf.py` can be used to specify
hyperlink patterns to be ignored along with allowed redirects. For more
information, see:
🔗 https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-linkcheck_ignore
🔗 https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-linkcheck_allowed_redirects
These variables are in the form of Python regular expressions:
🔗 https://docs.python.org/3/howto/regex.html
"""
@nox_uv.session(python=DOCPYTHON, uv_groups=["docs"])
def linkcheck(session: nox.Session) -> None:
"""Check hyperlinks in documentation."""
if RUNNING_ON_CI:
session.log(LINKCHECK_TROUBLESHOOTING)
session.run(*SPHINX_BASE_COMMAND, *CHECK_HYPERLINKS, *session.posargs)
TY_TROUBLESHOOTING = (
"\n\n"
"For more details about specific static type checking errors, go to: "
"🔗 https://docs.astral.sh/ty/reference/rules"
"\n\n"
"🛡 For an introduction to type annotations, check out: "
"https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html"
"\n\n"
"🛠 Automatically add type annotations for common patterns with: "
"nox -s 'autotyping(safe)'"
"\n\n"
"🪧 Particularly tricky errors can be ignored with an inline comment of "
"the form: `# ty:ignore[error]`, where `error` is replaced with the "
"ty error code. Please use sparingly!"
"\n"
)
@nox_uv.session(python=MAXPYTHON, uv_groups=["type_check"])
def ty(session: nox.Session) -> None:
"""Perform static type checking with ty."""
if RUNNING_ON_CI:
session.log(TY_TROUBLESHOOTING)
session.run("ty", "check", *session.posargs)
@nox.session(name="import")
def try_import(session: nox.Session) -> None:
"""Install PlasmaPy and import it."""
session.install(".")
session.run("python", "-c", "import plasmapy", *session.posargs)
@nox.session
def build(session: nox.Session) -> None:
"""
Build the source distribution (sdist) and wheel.
The sdist and wheel are deposited into the dist/ directory.
"""
session.install("uv_build")
session.run("uv", "build", *session.posargs)
session.notify("check_build")
@nox.session
def check_build(session: nox.Session) -> None:
"""
Validate the source distribution and wheel.
This session requires that `nox -s build` has already been run.
"""
session.install("twine")
session.run("twine", "check", "dist/*")
@nox_uv.session(python=MAXPYTHON, uv_only_groups=["changelog"])
@nox.parametrize("final", [nox.param(False, id="draft"), nox.param(True, id="final")])
def changelog(session: nox.Session, final: str) -> None:
"""
Build the changelog with towncrier.
- 'final': build the combined changelog for the release, delete
the individual changelog entries in `changelog`, and replace
`CHANGELOG.rst`. Be sure to commit changes before running this
session.
- 'draft': print the draft changelog to standard output, without
writing to files
When executing this session, provide the version of the release, as
in this example:
nox -s 'changelog(final)' -- 2026.5.0
"""
now = datetime.datetime.now(datetime.UTC)
if len(session.posargs) != 1:
raise TypeError(
"Please provide the version of PlasmaPy to be released "
f"(i.e., `nox -s changelog -- {now.year}.{now.month}.0`).",
)
version = session.posargs[0]
year_pattern = r"(202[4-9]|20[3-9][0-9]|2[1-9][0-9]{2}|[3-9][0-9]{3,})"
month_pattern = r"(1[0-2]|[1-9])"
patch_pattern = r"(0?[0-9]|[1-9][0-9])"
version_pattern = rf"^{year_pattern}\.{month_pattern}\.{patch_pattern}$"
if not re.match(version_pattern, version):
raise ValueError(
"Please provide a version of the form YYYY.M.PATCH, where "
"YYYY is he year, M is the one or two digit month, "
"and PATCH is a non-negative integer.",
)
towncrier = ["towncrier", "build", "--version", version]
if not final:
session.run(*towncrier, "--draft", "--keep")
return
original_file = pathlib.Path(ROOT_DIR / "CHANGELOG.rst")
original_file.unlink()
session.run(*towncrier, "--yes")
destination = pathlib.Path(ROOT_DIR / f"docs/changelog/{version}.rst")
shutil.copy(original_file, destination)
AUTOTYPING_SAFE: tuple[str, ...] = (
"--none-return",
"--scalar-return",
"--annotate-magics",
)
AUTOTYPING_RISKY: tuple[str, ...] = (
*AUTOTYPING_SAFE,
"--bool-param",
"--int-param",
"--float-param",
"--str-param",
"--bytes-param",
"--annotate-imprecise-magics",
)
@nox_uv.session(
python=MINPYTHON,
uv_only_groups=["autotyping"],
uv_no_install_project=True,
)
@nox.parametrize(
"options",
[
nox.param(AUTOTYPING_SAFE, id="safe"),
nox.param(AUTOTYPING_RISKY, id="aggressive"),
],
)
def autotyping(session: nox.Session, options: tuple[str, ...]) -> None:
"""
Automatically add type annotations with autotyping.
The `safe` option generates very few incorrect type annotations, and
can be used in CI. The `aggressive` option may add type annotations
that are incorrect, so please perform a careful code review when
using this option.
To check specific files, pass them after a `--`, such as:
nox -s 'autotyping(safe)' -- noxfile.py
"""
session.install("autotyping", "typing_extensions")
default_paths = ("src", "tests", "tools", "*.py", ".github", "docs/*.py")
paths = session.posargs or default_paths
session.run("python", "-m", "autotyping", *options, *paths, *session.posargs)
@nox_uv.session(
python=MAXPYTHON,
uv_only_groups=["manifest"],
uv_no_install_project=True,
)
def manifest(session: nox.Session) -> None:
"""
Check for missing files in MANIFEST.in.
When run outside of CI, this check may report files that were
locally created but not included in version control. These false
positives can be ignored by adding file patterns and paths to
`ignore` under `[tool.check-manifest]` in `pyproject.toml`.
"""
# check-manifest would be suitable as a pre-commit hook, except that
# it requires ∼6 seconds to build the package, which would triple
# the time needed to run pre-commit.
session.install("check-manifest")
session.run("check-manifest", *session.posargs)
@nox_uv.session(python=MAXPYTHON, uv_only_groups=["lint"], uv_no_install_project=True)
def lint(session: nox.Session) -> None:
"""Run all pre-commit hooks defined in .pre-commit-config.yaml."""
session.run(
"pre-commit",
"run",
"--all-files",
*session.posargs,
)
ZIZMOR_TROUBLESHOOTING_MESSAGE = """
🪧 Run this check locally with `nox -s zizmor` to find potential
security vulnerabilities in GitHub workflows and perform safe fixes.
🧰 Perform safe and unsafe fixes with `nox -s zizmor -- --fix=all`.
📜 Audit rules: https://woodruffw.github.io/zizmor/audits
🔗 If a reported potential vulnerability does not necessitate a fix,
then either append a comment like `# zizmor: ignore[unpinned-uses]` to
the reported line (replacing `unpinned-uses` with the audit rule code),
or add the appropriate configuration settings to: .github/zizmor.yml
"""
@nox_uv.session(python=MAXPYTHON, uv_only_groups=["zizmor"], uv_no_install_project=True)
def zizmor(session: nox.Session) -> None:
"""
Find common security issues in GitHub workflows.
Because some of the zizmor audit rules require a GitHub token,
running this check locally may produce different results than
running it in CI.
If no positional arguments are provided, safe fixes will be applied.
To perform unsafe fixes, run `nox -s zizmor -- --fix=unsafe-only`.
Configuration file: .github/zizmor.yml
"""
if RUNNING_ON_CI:
session.log(ZIZMOR_TROUBLESHOOTING_MESSAGE)
options = [
"--show-audit-urls=always",
]
if not RUNNING_ON_CI and not session.posargs:
options.append("--quiet")
options.extend(session.posargs or ["--fix=safe"])
session.run("zizmor", ".github", *options)
@nox.session
def update_ionization_energies(session: nox.Session) -> None:
"""Update ionization energies from NIST."""
session.log("This script is expected to raise exceptions, and will continue after.")
session.run("uv", "run", "tools/export_ionization_energy.py")
session.run(
"uvx",
"pre-commit",
"run",
"end-of-file-fixer",
"--files",
"src/plasmapy/particles/data/ionization_energy.json",
success_codes=[0, 1],
)
if __name__ == "__main__":
nox.main()