-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnoxfile.py
More file actions
1556 lines (1258 loc) · 47.9 KB
/
noxfile.py
File metadata and controls
1556 lines (1258 loc) · 47.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
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import os
import shutil
from functools import wraps
import pathlib
import urllib.request
import json
import re
import nox
import nox.command as nox_command
from nox import session as nox_session
from nox.project import load_toml
from nox.sessions import Session
try:
import tomli as tomllib
_ = tomllib
except ImportError:
pass
TYPE_CHECKING = False
TYPE_EXTENSIONS_IMPORTED = False
if TYPE_CHECKING:
from typing import (
Any,
Callable,
Dict,
Literal,
Optional,
Sequence,
TypedDict,
Union,
overload,
)
try:
from typing_extensions import NotRequired
TYPE_EXTENSIONS_IMPORTED = True
except ImportError:
pass
if TYPE_EXTENSIONS_IMPORTED and TYPE_CHECKING:
from nox.sessions import Func
from typing_extensions import ParamSpec
P = ParamSpec("P")
class NoxSessionParams(TypedDict):
"""Type hints for Nox session parameters.
Attributes:
func: The function to be executed in the session
python: Python version(s) to use
py: Alias for python parameter
reuse_venv: Whether to reuse the virtual environment
name: Name of the session
venv_backend: Backend to use for virtual environment
venv_params: Additional parameters for virtual environment creation
tags: Tags associated with the session
default: Whether this is a default session
requires: Required dependencies for the session
"""
func: NotRequired[Optional[Union[Callable[..., Any], "Func"]]] # type: ignore
python: NotRequired[Optional["PythonVersion"]] # type: ignore
py: NotRequired[Optional["PythonVersion"]] # type: ignore
reuse_venv: NotRequired[Optional[bool]]
name: NotRequired[Optional[str]]
venv_backend: NotRequired[Optional[Any]]
venv_params: NotRequired[Sequence[str]]
tags: NotRequired[Optional[Sequence[str]]]
default: NotRequired[bool]
requires: NotRequired[Optional[Sequence[str]]]
PythonVersion = Literal["3.8", "3.9", "3.10", "3.11", "3.12"]
class ExtraSessionParams(TypedDict):
"""Type hints for extra session parameters.
Attributes:
dependency_group: Group to run the session in
"""
dependency_group: NotRequired[Optional[str]]
environment_mapping: NotRequired[Optional[Dict[str, str]]]
default_posargs: NotRequired[Optional[Sequence[str]]]
class SessionParams(NoxSessionParams, ExtraSessionParams):
"""Type hints for **all** session parameters."""
@overload
def session(
f: Callable[..., Any],
/,
dependency_group: str = None,
environment_mapping: "Dict[str, str]" = {},
default_posargs: "Sequence[str]" = (),
**kwargs: NoxSessionParams,
) -> Callable[[], Any]: ...
@overload
def session(
f: None = None,
/,
dependency_group: str = None,
environment_mapping: "Dict[str, str]" = {},
default_posargs: "Sequence[str]" = (),
**kwargs: NoxSessionParams,
) -> Callable[[Callable[..., Any]], Callable[..., Any]]: ...
# Fundamental Variables
ROOT_DIR: str = os.path.dirname(os.path.abspath(__file__))
MANIFEST_FILENAME = "pyproject.toml"
PROJECT_MANIFEST = load_toml(MANIFEST_FILENAME)
PROJECT_NAME: str = PROJECT_MANIFEST["project"]["name"]
PROJECT_NAME_NORMALIZED: str = PROJECT_NAME.replace("-", "_").replace(" ", "_")
SRC_DIR_NAME = "src"
SRC_DIR_PATH = pathlib.Path(SRC_DIR_NAME)
NOXFILE_NAME = "noxfile"
NOXFILE_WITH_EXT_NAME = f"{NOXFILE_NAME}.py"
_PROJECT_CODES_DIR: str = os.path.join("src", PROJECT_NAME_NORMALIZED)
PROJECT_CODES_DIR: str = (
_PROJECT_CODES_DIR if os.path.exists(_PROJECT_CODES_DIR) else "."
)
DIST_DIR: str = os.path.join(ROOT_DIR, "dist")
BUILD_DIR: str = os.path.join(ROOT_DIR, "build")
TEST_DIR: str = os.path.join(ROOT_DIR, "tests")
EXAMPLES_DIR: str = os.path.join(ROOT_DIR, "examples")
# Statics
DEFAULT_SESSION_KWARGS: "NoxSessionParams" = {
"reuse_venv": True, # probably want to reuse it so that you don't keep recreating it
"venv_backend": "uv",
# you can also pass in other kwargs to nox_session, e.g. pinning a python version
}
Session.log(
object.__new__(Session),
{
"FUNDAMENTAL VARIABLES": {
"PROJECT_NAME": PROJECT_NAME,
"PROJECT_NAME_NORMALIZED": PROJECT_NAME_NORMALIZED,
"PROJECT_CODES_DIR": PROJECT_CODES_DIR,
"DIST_DIR": DIST_DIR,
"BUILD_DIR": BUILD_DIR,
"TEST_DIR": TEST_DIR,
"EXAMPLES_DIR": EXAMPLES_DIR,
}
},
)
# --- FastAPI compatibility matrix helpers ---
PYPI_JSON_URL_TEMPLATE = "https://pypi.org/pypi/{package}/json"
def _parse_strict_version_tuple(ver_str: str):
"""Parse a strict semantic version 'X.Y.Z' into a tuple of ints.
Returns None if version doesn't match strict pattern (filters out pre-releases).
"""
m = re.match(r"^(\d+)\.(\d+)\.(\d+)$", ver_str)
if not m:
return None
return int(m.group(1)), int(m.group(2)), int(m.group(3))
def _version_tuple_to_str(t):
return f"{t[0]}.{t[1]}.{t[2]}"
def _cmp_major_minor(a, b):
"""Compare (major, minor) tuples only."""
if a[0] != b[0]:
return a[0] - b[0]
return a[1] - b[1]
def _get_min_supported_version_from_pyproject(
package_name: str, manifest: dict = PROJECT_MANIFEST
):
"""Extract minimum supported version from pyproject for given package.
Supports entries like 'fastapi>=0.100.1' and 'fastapi[standard]>=0.100.1'.
Returns a version tuple (major, minor, patch) or None if not found.
"""
deps = manifest.get("project", {}).get("dependencies", [])
patterns = [
rf"^{re.escape(package_name)}>=([0-9]+\.[0-9]+\.[0-9]+)$",
rf"^{re.escape(package_name)}\[[^\]]+\]>=([0-9]+\.[0-9]+\.[0-9]+)$",
]
for dep in deps:
for pat in patterns:
m = re.match(pat, dep)
if m:
vt = _parse_strict_version_tuple(m.group(1))
if vt:
return vt
return None
def _fetch_pypi_latest_and_releases(package_name: str):
"""Fetch latest version and releases list from PyPI JSON.
Returns (latest_version_tuple, releases_dict) where releases_dict maps
(major, minor) -> max patch available for that minor.
"""
url = PYPI_JSON_URL_TEMPLATE.format(package=package_name)
try:
with urllib.request.urlopen(url) as resp:
data = json.loads(resp.read().decode("utf-8"))
except Exception:
return None, {}
latest_str = data.get("info", {}).get("version")
latest_tuple = _parse_strict_version_tuple(latest_str) if latest_str else None
releases = data.get("releases", {})
minor_to_max_patch = {}
for ver_str in releases.keys():
vt = _parse_strict_version_tuple(ver_str)
if not vt:
# skip pre-release or non-strict versions
continue
major, minor, patch = vt
key = (major, minor)
prev = minor_to_max_patch.get(key)
if prev is None or patch > prev:
minor_to_max_patch[key] = patch
return latest_tuple, minor_to_max_patch
def _build_minor_matrix(min_vt, latest_vt, minor_to_max_patch):
"""Build a list of version strings representing the highest patch in each minor
from min_vt to latest_vt inclusive. Only includes minors that exist in releases.
"""
if not min_vt or not latest_vt:
return []
result = []
# Collect and sort available minor keys
available_minors = sorted(minor_to_max_patch.keys(), key=lambda k: (k[0], k[1]))
for major, minor in available_minors:
# range filter: min <= (major, minor) <= latest
if _cmp_major_minor((major, minor), (min_vt[0], min_vt[1])) < 0:
continue
if _cmp_major_minor((major, minor), (latest_vt[0], latest_vt[1])) > 0:
continue
patch = minor_to_max_patch[(major, minor)]
result.append(_version_tuple_to_str((major, minor, patch)))
return result
def _compute_fastapi_minor_matrix():
package = "fastapi"
min_vt = _get_min_supported_version_from_pyproject(package)
latest_vt, minor_to_max_patch = _fetch_pypi_latest_and_releases(package)
matrix = _build_minor_matrix(min_vt, latest_vt, minor_to_max_patch)
# Fallbacks if network fails or parsing issues
if not matrix:
vals = []
if min_vt:
vals.append(_version_tuple_to_str(min_vt))
if latest_vt and latest_vt != min_vt:
vals.append(_version_tuple_to_str(latest_vt))
matrix = vals or ["0.100.1"]
return matrix
FASTAPI_MINOR_MATRIX = _compute_fastapi_minor_matrix()
def uv_install_group_dependencies(session: Session, dependency_group: str):
pyproject = nox.project.load_toml(MANIFEST_FILENAME)
dependencies = nox.project.dependency_groups(pyproject, dependency_group)
session.install(*dependencies)
session.log(f"Installed dependencies: {dependencies} for {dependency_group}")
class AlteredSession(Session):
__slots__ = (
"session",
"dependency_group",
"environment_mapping",
"default_posargs",
)
def __init__(
self,
session: Session,
dependency_group: str,
environment_mapping: "Dict[str, str]",
default_posargs: "Sequence[str]",
):
super().__init__(session._runner)
self.dependency_group = dependency_group
self.environment_mapping = environment_mapping
self.default_posargs = default_posargs
self.session = session
def run(self, *args, **kwargs):
if self.dependency_group is not None:
uv_install_group_dependencies(self, self.dependency_group)
if self.session.posargs is not None:
args = (*args, *(self.session.posargs or self.default_posargs))
env: "Dict[str, str]" = kwargs.pop("env", {})
env.update(self.environment_mapping)
kwargs["env"] = env
return self.session.run(*args, **kwargs)
def session(
f: "Optional[Callable[..., Any]]" = None,
/,
dependency_group: "Optional[str]" = None,
environment_mapping: "Dict[str, str]" = {},
default_posargs: "Sequence[str]" = (),
**kwargs: "NoxSessionParams",
) -> "Callable[..., Any]":
if f is None:
return lambda f: session(
f,
dependency_group=dependency_group,
environment_mapping=environment_mapping,
default_posargs=default_posargs,
**kwargs,
)
session_name = kwargs.get("name", f.__name__.replace("_", "-"))
nox_session_kwargs = {
**DEFAULT_SESSION_KWARGS,
"name": session_name,
**kwargs,
}
@wraps(f)
def wrapper(session: Session, *args, **kwargs):
altered_session = AlteredSession(
session, dependency_group, environment_mapping, default_posargs
)
return f(altered_session, *args, **kwargs)
return nox_session(wrapper, **nox_session_kwargs)
# you can either run `nox -s test` or `nox -s test -- tests/test_cfg.py -s -vv`
# former will run all tests (default being: `tests -s -vv`, i.e. test the entire test suite)
# latter will run a single test, e.g. a specific test file (tests/test_cfg.py), or a specific test function, etc.
# dependency_group is used to install the dependencies for the test session
# default_posargs is used to pass additional arguments to the test session
@session(
dependency_group="dev",
default_posargs=[TEST_DIR, "-s", "-vv", "-n", "auto", "--dist", "worksteal"],
)
def test(session: AlteredSession):
command = [
shutil.which("uv"),
"run",
"python",
"-m",
"pytest",
# by default will run all tests, e.g. appending `tests -s -vv` to the command
# but you can also run a single test file, e.g. `nox -s test -- tests/test_cfg.py -s -vv`
# override the default by appending different `-- <args>` to `nox -s test`
# save you some time from writing different nox sessions
]
if "--build" in session.posargs:
session.posargs.remove("--build")
with alter_session(session, dependency_group="build"):
build(session)
session.run(*command)
@session(
dependency_group=None,
default_posargs=[TEST_DIR, "-s", "-vv", "-n", "auto", "--dist", "worksteal"],
reuse_venv=False,
)
@nox.parametrize("fastapi_version", FASTAPI_MINOR_MATRIX)
def test_compat_fastapi(session: AlteredSession, fastapi_version: str):
"""Run tests against a matrix of FastAPI minor versions.
The matrix is computed from pyproject's minimum supported version and
PyPI's latest release, selecting the highest patch per minor.
"""
session.log(f"Testing compatibility with FastAPI versions: {FASTAPI_MINOR_MATRIX}")
# Pin FastAPI (and extras) to the target minor's highest patch before running tests.
# Install dev dependencies excluding FastAPI to avoid overriding the pinned version.
pyproject = load_toml(MANIFEST_FILENAME)
dev_deps = nox.project.dependency_groups(pyproject, "dev")
filtered_dev_deps = [d for d in dev_deps if not d.startswith("fastapi")]
if filtered_dev_deps:
session.install(*filtered_dev_deps)
# Pin FastAPI (and extras) to the target minor's highest patch before running tests.
session.install(f"fastapi[standard]=={fastapi_version}")
with alter_session(session, dependency_group=None) as session:
session.install(f".")
session.run(
*(
"python",
"-c",
f'from fastapi import __version__; assert __version__ == "{fastapi_version}", __version__',
)
)
# Run pytest using the Nox-managed virtualenv (avoid external interpreter).
session.run("pytest")
@contextlib.contextmanager
def alter_session(
session: AlteredSession,
dependency_group: str = None,
environment_mapping: "Dict[str, str]" = {},
default_posargs: "Sequence[str]" = (),
**kwargs: "NoxSessionParams",
):
old_dependency_group = session.dependency_group
old_environment_mapping = session.environment_mapping
old_default_posargs = session.default_posargs
old_kwargs = {}
for key, value in kwargs.items():
old_kwargs[key] = getattr(session, key)
session.dependency_group = dependency_group
session.environment_mapping = environment_mapping
session.default_posargs = default_posargs
for key, value in kwargs.items():
setattr(session, key, value)
yield session
session.dependency_group = old_dependency_group
session.environment_mapping = old_environment_mapping
session.default_posargs = old_default_posargs
for key, value in old_kwargs.items():
setattr(session, key, value)
@session(
dependency_group="dev",
)
def clean(session: Session):
# Try to clean uv cache, but don't fail if it's locked by other processes
session.run("rm", "-rf", BUILD_DIR, DIST_DIR, "*.egg-info")
import glob
import os
import shutil
from pathlib import Path
# Define patterns that match any compiled Python extensions
extensions_patterns = [
# Linux .so files (matches any .so file from Python extensions)
"**/*.cpython-*.so",
"**/*.abi3.so",
"**/*.so",
# Windows .pyd files (matches any .pyd extension)
"**/*.pyd",
# Specific directories if needed
f"{PROJECT_CODES_DIR}/**/*.so",
f"{PROJECT_CODES_DIR}/**/*.pyd",
# Build directory extensions
f"{BUILD_DIR}/**/*.so",
f"{BUILD_DIR}/**/*.pyd",
]
# Remove dist directory
if os.path.exists(DIST_DIR):
shutil.rmtree(DIST_DIR)
# Remove build directory
if os.path.exists(BUILD_DIR):
shutil.rmtree(BUILD_DIR)
for pattern in extensions_patterns:
for file in glob.glob(pattern, recursive=True):
try:
os.remove(file)
session.log(f"Removed: {file}")
except OSError as e:
session.log(f"Error removing {file}: {e}")
# Remove __pycache__ directories and .pyc files
for root, dirs, files in os.walk(ROOT_DIR):
# Remove __pycache__ directories
for dir in dirs:
if dir == "__pycache__":
cache_dir = Path(root) / dir
try:
shutil.rmtree(cache_dir)
session.log(f"Removed cache directory: {cache_dir}")
except OSError as e:
session.log(f"Error removing {cache_dir}: {e}")
# Remove .pyc files
for file in files:
if file.endswith(".pyc"):
pyc_file = Path(root) / file
try:
os.remove(pyc_file)
session.log(f"Removed: {pyc_file}")
except OSError as e:
session.log(f"Error removing {pyc_file}: {e}")
@session(
dependency_group="examples",
)
def fastapi_auth(session: Session):
test_development(session)
# test the staging environment
# change the environment key to "staging"
with alter_session(session, environment_mapping={"ENVIRONMENT_KEY": "staging"}):
test_staging(session)
# test the production environment
# change the environment key to "production"
with alter_session(session, environment_mapping={"ENVIRONMENT_KEY": "production"}):
test_production(session)
# test the development environment again with the environment key set to "development"
test_development(session)
@session(
dependency_group="examples",
default_posargs=[
f"{EXAMPLES_DIR}/scratchpad.py",
],
)
def scratchpad(session: Session):
command = [
shutil.which("uv"),
"run",
"--group",
"examples",
"python",
]
session.run(*command)
@session(
dependency_group="examples",
environment_mapping={"ENVIRONMENT_KEY": "staging"},
default_posargs=[f"{EXAMPLES_DIR}/fastapi_auth_staging.py", "-s", "-vv"],
)
def test_staging(session: Session):
session.run(
"uv",
"run",
"--group",
"examples",
"python",
"-m",
"pytest",
)
@session(
dependency_group="examples",
environment_mapping={"ENVIRONMENT_KEY": "production"},
default_posargs=[f"{EXAMPLES_DIR}/fastapi_auth_prod.py", "-s", "-vv"],
)
def test_production(session: Session):
session.run(
"uv",
"run",
"--group",
"examples",
"python",
"-m",
"pytest",
)
@session(
dependency_group="examples",
environment_mapping={"ENVIRONMENT_KEY": "development"},
default_posargs=[f"{EXAMPLES_DIR}/fastapi_auth_dev.py", "-s", "-vv"],
)
def test_development(session: Session):
session.run(
"uv",
"run",
"--group",
"examples",
"python",
"-m",
"pytest",
)
@session(
dependency_group="dev",
default_posargs=[
pathlib.Path(PROJECT_CODES_DIR),
pathlib.Path(TEST_DIR),
pathlib.Path(NOXFILE_WITH_EXT_NAME),
],
)
def format(session: Session):
# clang-format only c files
# use glob to find all c files
import glob
import os
# Check if the directory exists before trying to format files
# Find the src directory or use parent directory
# Look for src directory
format_dir = pathlib.Path(PROJECT_CODES_DIR)
session.log(f"Using {format_dir} as the directory for formatting")
# Format python files first
session.run("uv", "tool", "run", "ruff", "format")
# Format c files
c_files_path = format_dir
if not os.path.exists(c_files_path):
session.log(f"Directory {c_files_path} does not exist, skipping clang-format")
return
# Check if there are any C files to format
c_files = glob.glob(f"{c_files_path}/*.c", recursive=True)
if not c_files:
session.log(f"No C files found in {c_files_path}, skipping clang-format")
return
nox_command.run(("uv", "tool", "run", "clang-format", "-i", *c_files))
@session(dependency_group="dev")
def check(session: Session):
check_ruff(session)
check_mypy(session)
check_pyright(session)
@session(dependency_group="dev", default_posargs=["check", ".", "--fix"])
def check_ruff(session: Session):
session.run("uv", "tool", "run", "ruff")
@session(dependency_group="dev", default_posargs=["src", "--rcfile", MANIFEST_FILENAME])
def lint(session: Session):
session.run("uv", "tool", "run", "pylint")
@session(dependency_group="dev")
def build(session: Session):
# for c extension which is now defuncted
# command = [
# shutil.which("uv"),
# "run",
# "setup.py",
# "build",
# ]
# session.run(*command)
# # copy from ./build to ./{PROJECT_CODES_DIR}/_lib.c
# shutil.copy(
# "./build/lib.linux-x86_64-cpython-38/_lib.cpython-38-x86_64-linux-gnu.so",
# "./{PROJECT_CODES_DIR}/_lib.cpython-38-x86_64-linux-gnu.so",
# )
session.run("uv", "build")
@session(dependency_group="test", default_posargs=[f"{TEST_DIR}/benchmark.py", "-v"])
def benchmark(session: Session):
session.run(
"uv",
"run",
"--group",
"test",
"python",
"-m",
"pytest",
)
@session(dependency_group="dev")
def list_dist_files(session: Session):
"""List all files packaged in the latest distribution."""
import glob
import os
import zipfile
from pathlib import Path
# Find the latest wheel file in the dist directory
wheel_files = sorted(
glob.glob(f"{DIST_DIR}/*.whl"), key=os.path.getmtime, reverse=True
)
tarball_files = sorted(
glob.glob(f"{DIST_DIR}/*.tar.gz"), key=os.path.getmtime, reverse=True
)
if not wheel_files and not tarball_files:
session.error("No distribution files found in dist/ directory")
return
# Process wheel file if available
if wheel_files:
latest_wheel = wheel_files[0]
session.log(f"Examining contents of {latest_wheel}")
# Wheel files are zip files, so we can use zipfile to list contents
with zipfile.ZipFile(latest_wheel, "r") as wheel:
file_list = wheel.namelist()
# Print the files in a readable format
session.log(f"Contents of {Path(latest_wheel).name}:")
for file in sorted(file_list):
session.log(f" - {file}")
session.log(f"Total files in wheel: {len(file_list)}")
# Process tarball file if available
if tarball_files:
latest_tarball = tarball_files[0]
session.log(f"Examining contents of {latest_tarball}")
# Tarball files can be opened with tarfile
import tarfile
with tarfile.open(latest_tarball, "r:gz") as tar:
file_list = tar.getnames()
# Print the files in a readable format
session.log(f"Contents of {Path(latest_tarball).name}:")
for file in sorted(file_list):
session.log(f" - {file}")
session.log(f"Total files in tarball: {len(file_list)}")
@session(
dependency_group="dev", default_posargs=[PROJECT_CODES_DIR, "--check-untyped-defs"]
)
def check_mypy(session: Session):
session.run("uv", "tool", "run", "mypy")
@session(dependency_group="dev", default_posargs=[SRC_DIR_NAME])
def check_pyright(session: Session):
session.run("uv", "tool", "run", "pyright")
@session(dependency_group="dev")
def dev(session: Session):
clean(session)
format(session)
check(session)
build(session)
list_dist_files(session)
test(session)
@session(dependency_group="dev")
def ci(session: Session):
list_dist_files(session)
test(session)
@session(reuse_venv=False)
def install_latest_tarball(session: Session):
import glob
import re
from packaging import version
# Get all tarball files
tarball_files = glob.glob(f"{DIST_DIR}/{PROJECT_NAME_NORMALIZED}-*.tar.gz")
if not tarball_files:
session.error("No tarball files found in dist/ directory")
# Extract version numbers using regex
version_pattern = re.compile(
rf"{PROJECT_NAME_NORMALIZED}-([0-9]+\.[0-9]+\.[0-9]+(?:\.[0-9]+)?(?:(?:a|b|rc)[0-9]+)?(?:\.post[0-9]+)?(?:\.dev[0-9]+)?).tar.gz"
)
# Create a list of (file_path, version) tuples
versioned_files = []
for file_path in tarball_files:
match = version_pattern.search(file_path)
if match:
ver_str = match.group(1)
versioned_files.append((file_path, version.parse(ver_str)))
if not versioned_files:
session.error("Could not extract version information from tarball files")
# Sort by version (highest first) and get the path
latest_tarball = sorted(versioned_files, key=lambda x: x[1], reverse=True)[0][0]
session.log(f"Installing latest version: {latest_tarball}")
session.run("uv", "run", "pip", "uninstall", f"{PROJECT_NAME}", "-y")
session.install(latest_tarball)
@session(reuse_venv=False)
def test_client_install_run(session: Session):
with alter_session(session, dependency_group="dev"):
clean(session)
build(session)
with alter_session(session, dependency_group="dev"):
list_dist_files(session)
session.run("pip", "uninstall", f"{PROJECT_NAME}", "-y")
# Find the tarball with the largest semver version
import glob
import re
from packaging import version
# Get all tarball files
tarball_files = glob.glob(f"{DIST_DIR}/{PROJECT_NAME_NORMALIZED}-*.tar.gz")
if not tarball_files:
session.error("No tarball files found in dist/ directory")
# Extract version numbers using regex
version_pattern = re.compile(
rf"{PROJECT_NAME_NORMALIZED}-([0-9]+\.[0-9]+\.[0-9]+(?:\.[0-9]+)?(?:(?:a|b|rc)[0-9]+)?(?:\.post[0-9]+)?(?:\.dev[0-9]+)?).tar.gz"
)
# Create a list of (file_path, version) tuples
versioned_files = []
for file_path in tarball_files:
match = version_pattern.search(file_path)
if match:
ver_str = match.group(1)
versioned_files.append((file_path, version.parse(ver_str)))
if not versioned_files:
session.error("Could not extract version information from tarball files")
# Sort by version (highest first) and get the path
latest_tarball = sorted(versioned_files, key=lambda x: x[1], reverse=True)[0][0]
session.log(f"Installing latest version: {latest_tarball}")
session.run(
"uv",
"run",
"pip",
"install",
latest_tarball,
)
session.run(
"uv",
"run",
"python",
"-c",
f"from {PROJECT_NAME_NORMALIZED} import Shield, __version__; print(f'Shield imported, version: {{__version__}}')",
)
session.run("uv", "run", "pip", "uninstall", f"{PROJECT_NAME}", "-y")
with alter_session(session, dependency_group="dev"):
test(session)
@session
def run_examples(session: Session):
import glob
if session.posargs:
examples_scripts = glob.glob(f"{EXAMPLES_DIR}/{session.posargs[0]}")
else:
examples_scripts = glob.glob(f"{EXAMPLES_DIR}/*.py")
for script in examples_scripts:
session.run("uv", "run", script)
@session(dependency_group="dev", default_posargs=[PROJECT_CODES_DIR])
def no_print(session: Session):
output = session.run(
"grep",
"-rn",
"print",
silent=True,
success_codes=[1],
)
if output:
session.error("Found print statements in the code")
raise SystemExit(1)
@session(reuse_venv=False)
def test_all_vers(session: Session):
session.run("bash", "tests/build_test_pyvers_docker_images.sh", external=True)
@session(dependency_group="dev")
def version_sync(session: Session):
"""Sync version between pyproject.toml and __init__.py."""
import re
# Read version from pyproject.toml
with open("pyproject.toml", "r") as f:
pyproject_content = f.read()
version_match = re.search(r'version = "([^"]+)"', pyproject_content)
if not version_match:
session.error("Could not find version in pyproject.toml")
pyproject_version = version_match.group(1)
session.log(f"Found version in pyproject.toml: {pyproject_version}")
# Update __init__.py
init_file = f"{PROJECT_CODES_DIR}/__init__.py"
with open(init_file, "r") as f:
init_content = f.read()
updated_content = re.sub(
r'__version__ = "[^"]+"', f'__version__ = "{pyproject_version}"', init_content
)
with open(init_file, "w") as f:
f.write(updated_content)
session.log(f"SUCCESS: Synced version to {pyproject_version} in {init_file}")
@session(dependency_group="dev")
def bump_version(session: Session):
"""Bump version (minor by default, or specify: patch, minor, major)."""
import re
# Get bump type from posargs, default to patch
bump_type = "patch"
if session.posargs:
bump_type = session.posargs[0].lower()
if bump_type not in ["patch", "minor", "major"]:
session.error(
f"Invalid bump type: {bump_type}. Use: patch, minor, or major"
)
session.log(f"Bumping {bump_type} version...")
# Read current version from pyproject.toml
with open("pyproject.toml", "r") as f:
content = f.read()
version_match = re.search(r'version = "([^"]+)"', content)
if not version_match:
session.error("Could not find version in pyproject.toml")
current_version = version_match.group(1)
session.log(f"Current version: {current_version}")
# Parse version
version_parts = current_version.split(".")
if len(version_parts) != 3:
session.error(f"Invalid version format: {current_version}. Expected: X.Y.Z")
major, minor, patch = map(int, version_parts)
# Bump version
if bump_type == "major":
major += 1
minor = 0
patch = 0
elif bump_type == "minor":
minor += 1
patch = 0
elif bump_type == "patch":
patch += 1
new_version = f"{major}.{minor}.{patch}"
session.log(f"New version: {new_version}")
# Update pyproject.toml
updated_content = re.sub(
r'version = "[^"]+"', f'version = "{new_version}"', content
)
with open("pyproject.toml", "w") as f:
f.write(updated_content)
session.log(f"SUCCESS: Updated pyproject.toml to version {new_version}")
# Sync to __init__.py
version_sync(session)
return new_version
@session(dependency_group="dev")
def git_check(session: Session):
"""Check git status and ensure clean working directory."""
# Check if git repo
result = session.run(
"git",
"status",
"--porcelain",
silent=True,
external=True,
success_codes=[0, 128],
)