Coverage for scripts/lock_requirements.py: 100%

66 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Hash-locked requirement files (V6.6.7, #361): every install in a workflow, Dockerfile or shell script reads one. 

2 

3The OpenSSF Scorecard counts a pip install as pinned only with `--require-hashes` (or a wheel file, or `--no-deps -e .`). 

4Each profile `requirements/lock/<name>.in` compiles with uv into `<name>.txt`: exact pins, a sha256 for every file, one 

5universal resolution for CPython 3.11 on Linux and Windows (the CI interpreter). The `ci` and `runtime` profiles take 

6torch from the CPU index, so neither OS pulls the CUDA wheels. 

7 

8 python scripts/lock_requirements.py # every profile 

9 python scripts/lock_requirements.py --profile ci # one (repeatable) 

10 python scripts/lock_requirements.py --print # the commands only 

11 python scripts/lock_requirements.py --upgrade-package numpy # move one pin to its newest allowed version 

12 

13uv keeps every pin already in a `.txt` unless a floor forces it up, so a Dependabot bump of a pin (not a floor) needs 

14`--upgrade-package <name>` (`aq deps apply` passes it). 

15 

16A Dependabot floor bump in `requirements/*.txt` needs this rerun on its branch: `tests/test_requirement_locks.py` fails 

17while a lock pin is below a floor. 

18""" 

19 

20from __future__ import annotations 

21 

22import argparse 

23import shutil 

24import subprocess 

25import sys 

26from collections.abc import Callable, Sequence 

27from dataclasses import dataclass 

28from pathlib import Path 

29 

30ROOT = Path(__file__).resolve().parents[1] 

31LOCK_DIR = ROOT / "requirements" / "lock" 

32PYTHON_VERSION = "3.11" 

33CPU_INDEX = "https://download.pytorch.org/whl/cpu" 

34PYPI_INDEX = "https://pypi.org/simple" 

35 

36 

37@dataclass(frozen=True) 

38class ProfileSpec: 

39 name: str 

40 torch_cpu: bool = False 

41 python_version: str = PYTHON_VERSION 

42 

43 @property 

44 def in_path(self) -> Path: 

45 return LOCK_DIR / f"{self.name}.in" 

46 

47 @property 

48 def out_path(self) -> Path: 

49 return LOCK_DIR / f"{self.name}.txt" 

50 

51 

52PROFILES: dict[str, ProfileSpec] = { 

53 spec.name: spec 

54 for spec in ( 

55 ProfileSpec("ci", torch_cpu=True), 

56 ProfileSpec("runtime", torch_cpu=True), 

57 ProfileSpec("tools"), 

58 ProfileSpec("docs"), 

59 ProfileSpec("notebooks"), 

60 ProfileSpec("light"), 

61 ProfileSpec("dashboard"), 

62 ProfileSpec("build-ext"), 

63 ProfileSpec("lean-cli"), 

64 ProfileSpec("lean-runtime"), 

65 ProfileSpec("fuzz"), 

66 ProfileSpec("sanitize"), 

67 ProfileSpec("sbom"), 

68 ProfileSpec("compat", python_version="3.10"), 

69 ) 

70} 

71 

72 

73def header(profile: ProfileSpec) -> str: 

74 return f"# generated by scripts/lock_requirements.py --profile {profile.name}; edit {profile.name}.in, never this file\n# install: python -m pip install --require-hashes -r requirements/lock/{profile.name}.txt\n" 

75 

76 

77def build_command(profile: ProfileSpec, *, uv: str = "uv", upgrade: Sequence[str] = ()) -> list[str]: 

78 command = [ 

79 uv, "pip", "compile", str(profile.in_path), "--universal", "--python-version", profile.python_version, 

80 "--generate-hashes", "--no-header", "--quiet", "-o", str(profile.out_path), 

81 ] 

82 for package in upgrade: 

83 command += ["--upgrade-package", package] 

84 if profile.torch_cpu: 

85 # the +cpu wheels exist only on the CPU index, so the file carries both index lines for pip; the hashes make the 

86 # second index safe (a same-named upload elsewhere can't match them) 

87 command += ["--index-url", CPU_INDEX, "--extra-index-url", PYPI_INDEX, "--index-strategy", "unsafe-best-match", "--emit-index-url"] 

88 return command 

89 

90 

91def write_header(profile: ProfileSpec) -> None: 

92 body = profile.out_path.read_text(encoding="utf-8") 

93 profile.out_path.write_text(header(profile) + body, encoding="utf-8", newline="\n") 

94 

95 

96def find_uv(which: Callable[[str], str | None] = shutil.which) -> str: 

97 """uv on PATH, else the one next to this interpreter (a venv's Scripts/ or bin/).""" 

98 found = which("uv") 

99 if found: 

100 return found 

101 for name in ("uv.exe", "uv"): 

102 candidate = Path(sys.executable).with_name(name) 

103 if candidate.exists(): 

104 return str(candidate) 

105 raise SystemExit("uv not found: python -m pip install uv") 

106 

107 

108def main(argv: Sequence[str] | None = None, *, run: Callable[..., subprocess.CompletedProcess] = subprocess.run) -> int: 

109 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 

110 parser.add_argument("--profile", action="append", choices=sorted(PROFILES), help="one profile (repeatable; default every profile with an .in file)") 

111 parser.add_argument("--print", action="store_true", dest="print_only", help="print the commands, run nothing") 

112 parser.add_argument("--upgrade-package", action="append", default=[], metavar="NAME", help="let uv move this pin to its newest allowed version (repeatable)") 

113 args = parser.parse_args(argv) 

114 chosen = [PROFILES[name] for name in (args.profile or PROFILES) if PROFILES[name].in_path.exists()] 

115 uv = "uv" if args.print_only else find_uv() 

116 for profile in chosen: 

117 command = build_command(profile, uv=uv, upgrade=args.upgrade_package) 

118 print(" ".join(command), flush=True) 

119 if args.print_only: 

120 continue 

121 if run(command, cwd=ROOT, check=False).returncode != 0: 

122 print(f"lock {profile.name}: uv failed", file=sys.stderr) 

123 return 1 

124 write_header(profile) 

125 return 0 

126 

127 

128if __name__ == "__main__": 

129 raise SystemExit(main())