-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnoxfile.py
More file actions
888 lines (703 loc) · 30.4 KB
/
noxfile.py
File metadata and controls
888 lines (703 loc) · 30.4 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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
"""Nox configuration for development tasks."""
import json
import os
import re
import zipfile
from pathlib import Path
import nox
import tomli
from nox.command import CommandFailed
nox.options.reuse_existing_virtualenvs = True
nox.options.default_venv_backend = "uv"
NOT_SKIP_WITH_ACT = "not skip_with_act"
LATEXMK_VERSION_MIN = 4.86
LICENSES_JSON_PATH = "reports/licenses.json"
SBOM_CYCLONEDX_PATH = "reports/sbom.json"
SBOM_SPDX_PATH = "reports/sbom.spdx"
JUNIT_XML = "--junitxml=reports/junit.xml"
CLI_MODULE = "cli"
API_VERSIONS = ["v1", "v2"]
UTF8 = "utf-8"
PYTHON_VERSION = "3.13"
TEST_PYTHON_VERSIONS = ["3.11", "3.12", "3.13"]
DIST_VERCEL_REQUIREMENTS = "dist_vercel/requirements.txt"
DIST_VERCEL_REQUIRES_DIST_SUPPRESS = ["nicegui[native]"]
def _setup_venv(session: nox.Session, all_extras: bool = True) -> None:
"""Install dependencies for the given session using uv."""
args = ["uv", "sync", "--frozen"]
if all_extras:
args.append("--all-extras")
session.run_install(
*args,
env={
"UV_PROJECT_ENVIRONMENT": session.virtualenv.location,
"UV_PYTHON": str(session.python),
},
)
def _is_act_environment() -> bool:
"""Check if running in GitHub ACT environment.
Returns:
bool: True if running in ACT environment, False otherwise.
"""
return os.environ.get("GITHUB_WORKFLOW_RUNTIME") == "ACT"
def _format_json_with_jq(session: nox.Session, path: str) -> None:
"""Format JSON file using jq for better readability.
Args:
session: The nox session instance
path: Path to the JSON file to format
"""
with Path(f"{path}.tmp").open("w", encoding="utf-8") as outfile:
session.run("jq", ".", path, stdout=outfile, external=True)
session.run("mv", f"{path}.tmp", path, stdout=outfile, external=True)
@nox.session(python=[PYTHON_VERSION])
def lint(session: nox.Session) -> None:
"""Run code formatting checks, linting, and static type checking."""
_setup_venv(session, True)
session.run("ruff", "check", ".")
session.run(
"ruff",
"format",
"--check",
".",
)
session.run("mypy", "src")
@nox.session(python=[PYTHON_VERSION])
def audit(session: nox.Session) -> None:
"""Run security audit and license checks."""
_setup_venv(session, True)
# pip-audit to check for vulnerabilities
session.run("pip-audit", "-f", "json", "-o", "reports/vulnerabilities.json")
_format_json_with_jq(session, "reports/vulnerabilities.json")
# pip-licenses to check for compliance
pip_licenses_base_args = [
"pip-licenses",
"--with-system",
"--with-authors",
"--with-maintainer",
"--with-url",
"--with-description",
]
# Filter by .license-types-allowed file if it exists
allowed_licenses = []
licenses_allow_file = Path(".license-types-allowed")
if licenses_allow_file.exists():
allowed_licenses = [
line.strip()
for line in licenses_allow_file.read_text(encoding="utf-8").splitlines()
if line.strip() and not line.strip().startswith(("#", "//"))
]
session.log(f"Found {len(allowed_licenses)} allowed licenses in .license-types-allowed")
if allowed_licenses:
allowed_licenses_str = ";".join(allowed_licenses)
session.log(f"Using --allow-only with: {allowed_licenses_str}")
pip_licenses_base_args.extend(["--partial-match", "--allow-only", allowed_licenses_str])
# Generate CSV and JSON reports
session.run(
*pip_licenses_base_args,
"--format=csv",
"--order=license",
"--output-file=reports/licenses.csv",
)
session.run(
*pip_licenses_base_args,
"--with-license-file",
"--with-notice-file",
"--format=json",
"--output-file=" + LICENSES_JSON_PATH,
)
# Group by license type
_format_json_with_jq(session, LICENSES_JSON_PATH)
licenses_data = json.loads(Path(LICENSES_JSON_PATH).read_text(encoding="utf-8"))
licenses_grouped: dict[str, list[dict[str, str]]] = {}
licenses_grouped = {}
for pkg in licenses_data:
license_name = pkg["License"]
package_info = {"Name": pkg["Name"], "Version": pkg["Version"]}
if license_name not in licenses_grouped:
licenses_grouped[license_name] = []
licenses_grouped[license_name].append(package_info)
Path("reports/licenses_grouped.json").write_text(
json.dumps(licenses_grouped, indent=2),
encoding="utf-8",
)
_format_json_with_jq(session, "reports/licenses_grouped.json")
# SBOMs
session.run("cyclonedx-py", "environment", "-o", SBOM_CYCLONEDX_PATH)
_format_json_with_jq(session, SBOM_CYCLONEDX_PATH)
# Generates an SPDX SBOM including vulnerability scanning
session.run(
"trivy",
"fs",
"uv.lock",
"--include-dev-deps",
"--scanners",
"vuln",
"--format",
"spdx",
"--output",
SBOM_SPDX_PATH,
external=True,
)
def _generate_attributions(session: nox.Session, licenses_json_path: Path) -> None:
"""Generate ATTRIBUTIONS.md from licenses.json.
Args:
session: The nox session instance
licenses_json_path: Path to the licenses.json file
"""
attributions = "# Attributions\n\n"
attributions += f"[//]: # (This file is generated by make docs from {LICENSES_JSON_PATH})\n\n"
if not licenses_json_path.exists():
attributions += "Please run `make audit` first to generate the necessary license information.\n"
Path("ATTRIBUTIONS.md").write_text(attributions, encoding="utf-8")
session.log("Generated placeholder ATTRIBUTIONS.md file - run 'make audit' to populate it properly")
return
licenses_data = json.loads(licenses_json_path.read_text(encoding="utf-8"))
attributions += "This project includes code from the following third-party open source projects:\n\n"
for pkg in licenses_data:
attributions += _format_package_attribution(pkg)
attributions = attributions.rstrip() + "\n"
Path("ATTRIBUTIONS.md").write_text(attributions, encoding="utf-8")
session.log("Generated ATTRIBUTIONS.md file")
def _format_package_attribution(pkg: dict) -> str:
"""Format attribution for a single package.
Args:
pkg: Package information dictionary
Returns:
str: Formatted attribution text for the package
"""
name = pkg.get("Name", "Unknown")
version = pkg.get("Version", "Unknown")
license_name = pkg.get("License", "Unknown")
authors = pkg.get("Author", "Unknown")
maintainers = pkg.get("Maintainer", "")
url = pkg.get("URL", "")
description = pkg.get("Description", "")
attribution = f"## {name} ({version}) - {license_name}\n\n"
if description:
attribution += f"{description}\n\n"
if url:
attribution += f"* URL: {url}\n"
if authors and authors != "UNKNOWN":
attribution += f"* Author(s): {authors}\n"
if maintainers and maintainers != "UNKNOWN":
attribution += f"* Maintainer(s): {maintainers}\n"
attribution += "\n"
license_text = pkg.get("LicenseText", "")
if license_text and license_text != "UNKNOWN":
attribution += "### License Text\n\n"
# Sanitize backtick sequences to not escape the code block
sanitized_license_text = license_text.replace("```", "~~~")
attribution += f"```\n{sanitized_license_text}\n```\n\n"
notice_text = pkg.get("NoticeText", "")
if notice_text and notice_text != "UNKNOWN":
attribution += "### Notice\n\n"
# Sanitize backtick sequences to not escape the code block
sanitized_notice_text = notice_text.replace("```", "~~~")
attribution += f"```\n{sanitized_notice_text}\n```\n\n"
return attribution
def _generate_readme(session: nox.Session) -> None:
"""Generate README.md from partials.
Args:
session: The nox session instance
"""
preamble = "\n[//]: # (README.md generated from docs/partials/README_*.md)\n\n"
header = Path("docs/partials/README_header.md").read_text(encoding="utf-8")
main = Path("docs/partials/README_main.md").read_text(encoding="utf-8")
footer = Path("docs/partials/README_footer.md").read_text(encoding="utf-8")
readme_content = f"{preamble}{header}\n\n{main}\n\n{footer}"
Path("README.md").write_text(readme_content, encoding="utf-8")
session.log("Generated README.md file from partials")
def _generate_openapi_schemas(session: nox.Session) -> None:
"""Generate OpenAPI schemas for different API versions in YAML and JSON formats.
Args:
session: The nox session instance
"""
# Create directory if it doesn't exist
Path("docs/source/_static").mkdir(parents=True, exist_ok=True)
formats = {
"yaml": {"ext": "yaml", "args": ["--output-format=yaml"]},
"json": {"ext": "json", "args": ["--output-format=json"]},
}
for version in API_VERSIONS:
for format_name, format_info in formats.items():
output_path = Path(f"docs/source/_static/openapi_{version}.{format_info['ext']}")
with output_path.open("w", encoding="utf-8") as f:
cmd_args = [
"oe-python-template",
"system",
"openapi",
f"--api-version={version}",
*format_info["args"],
]
session.run(*cmd_args, stdout=f, external=True)
session.log(f"Generated API {version} OpenAPI schema in {format_name} format")
def _generate_cli_reference(session: nox.Session) -> None:
"""Generate CLI_REFERENCE.md.
Args:
session: The nox session instance
"""
if CLI_MODULE:
session.run(
"typer",
f"oe_python_template.{CLI_MODULE}",
"utils",
"docs",
"--name",
"oe-python-template",
"--title",
"CLI Reference",
"--output",
"CLI_REFERENCE.md",
external=True,
)
def _generate_api_reference(session: nox.Session) -> None:
"""Generate API_REFERENCE_v1.md and API_REFERENCE_v2.md.
Args:
session: The nox session instance
Raises:
FileNotFoundError: If the OpenAPI schema file for a version is not found
"""
for version in API_VERSIONS:
openapi_path = Path(f"docs/source/_static/openapi_{version}.yaml")
if not openapi_path.exists():
error_message = f"OpenAPI schema for {version} not found at {openapi_path}"
raise FileNotFoundError(error_message)
output_file = f"API_REFERENCE_{version}.md"
session.run(
"npx",
"widdershins",
f"docs/source/_static/openapi_{version}.yaml",
"--omitHeader",
"--search",
"false",
"--language_tabs",
"python:Python",
"javascript:Javascript",
"-o",
f"API_REFERENCE_{version}.md",
external=True,
)
session.log(f"Generated API_REFERENCE_{version}.md using widdershins")
content = Path(output_file).read_text(encoding="utf-8")
content = re.sub(r"<!--[\s\S]*?-->", "", content)
content = re.sub(r"<h1 id=\"[^\"]+\">([\s\S]+?)</h1>", r"# \1", content)
content = re.sub(r"<h2 id=\"[^\"]+\">([\s\S]+?)</h2>", r"## \1", content)
content = re.sub(r"<h3 id=\"[^\"]+\">([\s\S]+?)</h3>", r"### \1", content)
content = re.sub(r"<h4 id=\"[^\"]+\">([\s\S]+?)</h4>", r"#### \1", content)
content = re.sub(r"<a href=\"([^\"]+)\">([\s\S]+?)</a>", r"[\2](\1)", content)
content = re.sub(r"<a href=\"mailto:([^\"]+)\">([\s\S]+?)</a>", r"\2 (\1)", content)
content = re.sub(r"<[^>]*>", "", content)
content = re.sub(r"^\s*\n", "", content)
Path(output_file).write_text(content, encoding="utf-8")
session.log(f"Cleaned HTML from {output_file}")
content = Path(output_file).read_text(encoding="utf-8")
content = re.sub(r"^(#+)", r"\1#", content, flags=re.MULTILINE)
content = content.rstrip() + "\n"
Path(output_file).write_text(f"# API {version} Reference\n{content}", encoding="utf-8")
session.log(f"Shifted headers in {output_file}")
def _generate_pdf_docs(session: nox.Session) -> None:
"""Generate PDF documentation using latexmk.
Args:
session: The nox session instance
Raises:
CommandFailed: If latexmk is not installed or not in PATH
ValueError: If the installed latexmk version is outdated
AttributeError: If parsing the latexmk version information fails
"""
try:
out = session.run("latexmk", "--version", external=True, silent=True)
version_match = re.search(r"Version (\d+\.\d+\w*)", str(out))
if not version_match:
session.error("Could not determine latexmk version")
version_str = version_match.group(1)
# Parse version (handle cases like "4.86a")
match = re.match(r"(\d+\.\d+)", version_str)
if not match:
session.error(f"Could not parse version number from '{version_str}'")
base_version = match.group(1)
if float(base_version) < LATEXMK_VERSION_MIN:
message = f"latexmk version {version_str} is outdated. Please run 'brew upgrade mactex' to upgrade."
raise ValueError(message) # noqa: TRY301
session.log(f"latexmk version {version_str} is sufficient")
session.run("make", "-C", "docs", "latexpdf", external=True)
session.log("PDF documentation generated and available at: docs/build/latex/oe-python-template.pdf")
except CommandFailed as e:
session.error(f"latexmk is not installed or not in PATH: {e}. Please run 'brew install mactex' to install")
except (ValueError, AttributeError) as e:
session.error(f"Failed to parse latexmk version information: {e}")
@nox.session(python=[PYTHON_VERSION])
def docs(session: nox.Session) -> None:
"""Build documentation and concatenate README.
This function performs several documentation-related tasks:
1. Concatenates partial README files into a single README.md
2. Dumps OpenAPI schemas (v1 and v2) in both YAML and JSON formats
3. Builds HTML, single HTML, and LaTeX documentation
4. Optionally builds PDF documentation if "pdf" is in session arguments
Args:
session: The nox session instance
Raises:
CommandFailed: If latexmk is not installed or not in PATH
ValueError: If the installed latexmk version is outdated
AttributeError: If parsing the latexmk version information fails
"""
_setup_venv(session, True)
_generate_readme(session)
_generate_cli_reference(session)
_generate_openapi_schemas(session)
_generate_api_reference(session)
_generate_attributions(session, Path(LICENSES_JSON_PATH))
# Build HTML docs
session.run("make", "-C", "docs", "clean", external=True)
session.run("make", "-C", "docs", "html", external=True)
session.run("make", "-C", "docs", "singlehtml", external=True)
session.run("make", "-C", "docs", "latex", external=True)
if "pdf" in session.posargs:
_generate_pdf_docs(session)
@nox.session(python=[PYTHON_VERSION], default=False)
def docs_pdf(session: nox.Session) -> None:
"""Setup dev environment post project creation.""" # noqa: DOC501
_setup_venv(session, True)
try:
out = session.run("latexmk", "--version", external=True, silent=True)
version_match = re.search(r"Version (\d+\.\d+\w*)", str(out))
if not version_match:
session.error("Could not determine latexmk version")
version_str = version_match.group(1)
# Parse version (handle cases like "4.86a")
match = re.match(r"(\d+\.\d+)", version_str)
if not match:
session.error(f"Could not parse version number from '{version_str}'")
base_version = match.group(1)
if float(base_version) < LATEXMK_VERSION_MIN:
message = f"latexmk version {version_str} is outdated. Please run 'brew upgrade mactex' to upgrade."
raise ValueError(message) # noqa: TRY301
session.log(f"latexmk version {version_str} is sufficient")
session.run("make", "-C", "docs", "latexpdf", external=True)
except CommandFailed as e:
session.error(f"latexmk is not installed or not in PATH: {e}. Please run 'brew install mactex' to install")
except (ValueError, AttributeError) as e:
session.error(f"Failed to parse latexmk version information: {e}")
def _prepare_coverage(session: nox.Session) -> None:
"""Clean coverage data unless keep-coverage flag is specified.
Args:
session: The nox session
"""
if "--cov-append" not in session.posargs:
session.run("rm", "-rf", ".coverage", external=True)
def _extract_custom_marker(posargs: list[str]) -> tuple[str | None, list[str]]:
"""Extract custom marker from pytest arguments.
Args:
posargs: Command line arguments
Returns:
Tuple of (custom_marker, filtered_posargs)
"""
custom_marker = None
new_posargs = []
skip_next = False
for i, arg in enumerate(posargs):
if skip_next:
skip_next = False
continue
if arg == "-m" and i + 1 < len(posargs):
custom_marker = posargs[i + 1]
skip_next = True
elif arg != "-m" or i == 0 or posargs[i - 1] != "-m":
new_posargs.append(arg)
return custom_marker, new_posargs
def _get_report_type(session: nox.Session, custom_marker: str | None) -> str:
"""Generate report type string based on marker and Python version.
Args:
session: The nox session
custom_marker: Optional pytest marker
Returns:
Report type string
"""
# Create a report type based on marker
report_type = "regular"
if custom_marker:
# Replace spaces and special chars with underscores
report_type = re.sub(r"[\s\(\)]", "_", custom_marker).strip("_")
# Add Python version to the report type
if isinstance(session.python, str):
python_version = f"py{session.python.replace('.', '')}"
else:
# Handle case where session.python is a list, bool, or None
python_version = f"py{session.python!s}"
return f"{python_version}_{report_type}"
def _inject_headline(headline: str, file_name: str) -> None:
"""Inject headline into file.
- Checks if report file actually exists
- If so, injects headline
- If not, does nothing
Args:
headline: Headline to inject as first line
file_name: Name of the report file
"""
file = Path(file_name)
if file.is_file():
header = f"{headline}\n"
content = file.read_text(encoding=UTF8)
content = header + content
file.write_text(content, encoding=UTF8)
def _run_pytest(
session: nox.Session, test_type: str, custom_marker: str | None, posargs: list[str], report_type: str
) -> None:
"""Run pytest with specified arguments.
Args:
session: The nox session
test_type: Type of test ('sequential' or 'not sequential')
custom_marker: Optional pytest marker
posargs: Additional pytest arguments
report_type: Report type string for output files
"""
is_sequential = test_type == "sequential"
# Build base pytest arguments
pytest_args = ["pytest", "--disable-warnings", JUNIT_XML, "-n", "auto", "--dist", "loadgroup"]
# Add act environment filter if needed
if _is_act_environment():
pytest_args.extend(["-k", NOT_SKIP_WITH_ACT])
# Apply the appropriate marker
marker_value = f"{test_type}"
if custom_marker:
marker_value += f" and ({custom_marker})"
pytest_args.extend(["-m", marker_value])
# Add additional arguments
pytest_args.extend(posargs)
# Report output as markdown for GitHub step summaries
report_file_name = f"reports/pytest_{report_type}_{'sequential' if is_sequential else 'parallel'}.md"
pytest_args.extend(["--md-report-output", report_file_name])
# Remove report file if it exists,
# as it's only generated for failing tests on the pytest run below
report_file = Path(report_file_name)
if report_file.is_file():
report_file.unlink()
# Run pytest with the constructed arguments
session.run(*pytest_args)
# Inject headline into the report file indicating the report type
_inject_headline(f"# Failing tests with for test execution with {report_type}\n", report_file_name)
def _generate_coverage_report(session: nox.Session) -> None:
"""Generate coverage report in markdown format.
Args:
session: The nox session
"""
coverage_report_file_name = "reports/coverage.md"
with Path(coverage_report_file_name).open("w", encoding=UTF8) as outfile:
session.run("coverage", "report", "--format=markdown", stdout=outfile)
_inject_headline("# Coverage report", coverage_report_file_name)
def _cleanup_test_execution(session: nox.Session) -> None:
"""Clean up post test execution.
- Docker containers created by pytest-docker removed
Args:
session: The nox session instance
"""
session.run(
"bash",
"-c",
(
"docker compose ls --format json | jq -r '.[].Name' | "
"grep ^pytest | xargs -I {} docker compose -p {} down --remove-orphans"
),
external=True,
)
@nox.session(python=TEST_PYTHON_VERSIONS)
def test(session: nox.Session) -> None:
"""Run tests with pytest."""
_setup_venv(session)
# Conditionally clean coverage data
# Will remove .coverage file if --cov-append is not specified
_prepare_coverage(session)
# Extract custom markers from posargs if present
custom_marker, filtered_posargs = _extract_custom_marker(session.posargs)
# Determine report type from python version and custom marker
report_type = _get_report_type(session, custom_marker)
# Run parallel tests
_run_pytest(session, "not sequential", custom_marker, filtered_posargs, report_type)
# Run sequential tests
if "--cov-append" not in filtered_posargs:
filtered_posargs.extend(["--cov-append"])
_run_pytest(session, "sequential", custom_marker, filtered_posargs, report_type)
# Generate coverage report in markdown
_generate_coverage_report(session)
# Clean up post test execution
_cleanup_test_execution(session)
@nox.session(default=False)
def _build_temp_wheel(session: nox.Session, temp_wheel_dir: Path) -> tuple[str, Path]:
"""Build a wheel in a temporary directory.
Args:
session: The nox session
temp_wheel_dir: Directory to store the temporary wheel
Returns:
A tuple containing the wheel filename and path to the wheel
Raises:
SystemExit: If wheel building fails or the wheel cannot be identified
"""
wheel_output = session.run("uv", "build", "--wheel", "--out-dir", str(temp_wheel_dir), external=True, silent=True)
# Extract wheel filename
wheel_pattern = r"Successfully built .+/([^/\s]+\.whl)"
match = re.search(wheel_pattern, str(wheel_output))
if not match:
session.error("Failed to build or identify wheel file")
wheel_filename = match.group(1)
temp_wheel_path = temp_wheel_dir / wheel_filename
return wheel_filename, temp_wheel_path
def _extract_wheel(wheel_path: Path, extract_dir: Path) -> None:
"""Extract a wheel to a directory.
Args:
wheel_path: Path to the wheel file
extract_dir: Directory to extract the wheel to
"""
with zipfile.ZipFile(wheel_path, "r") as wheel_zip:
wheel_zip.extractall(extract_dir)
def _modify_metadata(session: nox.Session, unpacked_dir: Path) -> None:
"""Modify the METADATA file in the extracted wheel.
Args:
session: The nox session
unpacked_dir: Directory containing the extracted wheel
Raises:
SystemExit: If the METADATA file cannot be found
"""
# Find dist-info directory
dist_info_dirs = list(unpacked_dir.glob("*.dist-info"))
if not dist_info_dirs:
session.error("Could not find .dist-info directory in wheel")
metadata_path = dist_info_dirs[0] / "METADATA"
if not metadata_path.exists():
session.error(f"METADATA file not found in {dist_info_dirs[0]}")
# Read metadata and filter out suppressed requirements
metadata_lines = metadata_path.read_text(encoding=UTF8).splitlines()
# Process each line, excluding suppressed requirements
filtered_lines = []
for line in metadata_lines:
if line.startswith("Requires-Dist:"):
should_suppress = any(pkg in line for pkg in DIST_VERCEL_REQUIRES_DIST_SUPPRESS)
if should_suppress:
session.log(f"Suppressing requirement: {line.strip()}")
continue
filtered_lines.append(line)
# Write modified metadata back
metadata_path.write_text("\n".join(filtered_lines), encoding=UTF8)
def _repackage_wheel(src_dir: Path, output_path: Path) -> None:
"""Repackage the modified wheel.
Args:
src_dir: Directory containing the modified wheel contents
output_path: Path to write the new wheel
"""
# Remember current directory
original_dir = Path.cwd()
try:
# Change to source directory to preserve relative paths
os.chdir(src_dir)
# Create the new wheel
with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zip_file:
for path in Path().rglob("*"):
if path.is_file():
zip_file.write(path)
finally:
# Return to original directory
os.chdir(original_dir)
@nox.session(default=False)
def dist_vercel(session: nox.Session) -> None:
"""Create distribution to run API as Vercel Function.
Args:
session: The nox session instance
"""
import tempfile # noqa: PLC0415
# Create temporary directories
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
temp_wheel_dir = temp_path / "wheel"
temp_unpacked_dir = temp_path / "unpacked"
temp_unpacked_dir.mkdir()
# Build the wheel
wheel_filename, temp_wheel_path = _build_temp_wheel(session, temp_wheel_dir)
# Extract the wheel
_extract_wheel(temp_wheel_path, temp_unpacked_dir)
# Modify the metadata to remove unwanted dependencies
_modify_metadata(session, temp_unpacked_dir)
# Create a new wheel with the modified files
modified_wheel_path = temp_path / wheel_filename
_repackage_wheel(temp_unpacked_dir, modified_wheel_path)
# Ensure output directory exists and copy wheel
output_dir = Path("dist_vercel/wheels")
output_dir.mkdir(parents=True, exist_ok=True)
# Move the wheel to the destination
dest_wheel_path = output_dir / wheel_filename
modified_wheel_path.replace(dest_wheel_path)
# Create requirements.txt file
Path("dist_vercel").mkdir(exist_ok=True)
with Path(DIST_VERCEL_REQUIREMENTS).open("w", encoding=UTF8) as outfile:
outfile.write(f"./wheels/{wheel_filename}\n")
session.log(f"Created modified wheel at {dest_wheel_path}")
session.log(f"Created {DIST_VERCEL_REQUIREMENTS} pointing to the modified wheel")
@nox.session(python=["3.13"], default=False)
def setup(session: nox.Session) -> None:
"""Setup dev environment post project creation."""
_setup_venv(session)
session.run("ruff", "format", ".", external=True)
git_dir = Path(".git")
if git_dir.is_dir():
session.run("echo", "found .git directory", external=True)
session.run("touch", ".act-env-secret", external=True)
session.run("pre-commit", "install", external=True)
with Path(".secrets.baseline").open("w", encoding="utf-8") as out:
session.run("detect-secrets", "scan", stdout=out, external=True)
session.run("git", "add", ".", external=True)
try:
session.run("pre-commit", external=True)
except Exception: # noqa: BLE001
session.log("pre-commit run failed, continuing anyway")
session.run("git", "add", ".", external=True)
@nox.session(default=False)
def update_from_template(session: nox.Session) -> None:
"""Update from copier template."""
if Path("copier.yaml").is_file() or Path("copier.yml").is_file():
# Read the current version from pyproject.toml
with Path("pyproject.toml").open("rb") as f:
pyproject = tomli.load(f)
current_version = pyproject["tool"]["bumpversion"]["current_version"]
# In this case the project itself is the template
session.run("copier", "copy", "-r", "HEAD", ".", ".", "--force", "--trust", "--skip-tasks", external=True)
# Bump the version using the current version from pyproject.toml
session.run("bump-my-version", "replace", "--new-version", current_version, "--allow-dirty", external=True)
else:
# In this case the template has been generated from a template
session.run("copier", "update", "--trust", "--skip-answered", "--skip-tasks", external=True)
# Schedule the lint session to run after this session completes
session.notify("audit")
session.notify("docs")
session.notify("lint")
@nox.session(default=False)
def act(session: nox.Session) -> None:
"""Run GitHub Actions workflow locally with act."""
session.run(
"act",
"-j",
"test",
"--env-file",
".act-env-public",
"--secret-file",
".act-env-secret",
"--container-architecture",
"linux/amd64",
"-P",
"ubuntu-latest=catthehacker/ubuntu:act-latest",
"--action-offline-mode",
"--container-daemon-socket",
"-",
external=True,
)
@nox.session(default=False)
def bump(session: nox.Session) -> None:
"""Bump version and push changes to git."""
version_part = session.posargs[0] if session.posargs else "patch"
# Check if the version_part is a specific version (e.g., 1.2.3)
if re.match(r"^\d+\.\d+\.\d+$", version_part):
session.run("bump-my-version", "bump", "--new-version", version_part, external=True)
else:
session.run("bump-my-version", "bump", version_part, external=True)
# Push changes to git
session.run("git", "push", external=True)
@nox.session()
def dist(session: nox.Session) -> None:
"""Build wheel and put in dist/."""
session.run("uv", "build", external=True)