upcheck 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
upcheck/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """upcheck: will your dependencies install on that Python?"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ from .core import check_project
8
+ from .report import PackageCheck, Report, Status
9
+ from .target import Target
10
+
11
+ __all__ = ["PackageCheck", "Report", "Status", "Target", "__version__", "check_project"]
12
+
13
+ try:
14
+ __version__ = version("upcheck")
15
+ except PackageNotFoundError: # pragma: no cover - running from a raw checkout
16
+ __version__ = "0.0.0"
upcheck/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Support ``python -m upcheck``."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
upcheck/cli.py ADDED
@@ -0,0 +1,135 @@
1
+ """Command-line interface for upcheck."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Sequence
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .core import ProjectSource, check_project
12
+ from .pypi import PyPIClient
13
+ from .report import render_json, render_text
14
+ from .requirements import RequirementsError
15
+ from .target import Target
16
+
17
+
18
+ def build_parser() -> argparse.ArgumentParser:
19
+ """Create the argument parser for the ``upcheck`` command."""
20
+ parser = argparse.ArgumentParser(
21
+ prog="upcheck",
22
+ description=(
23
+ "Check whether a project's dependencies can install on a target "
24
+ "Python version, ABI and platform."
25
+ ),
26
+ )
27
+ parser.add_argument(
28
+ "path",
29
+ nargs="?",
30
+ default=".",
31
+ help="project directory, pyproject.toml, or requirements file (default: .)",
32
+ )
33
+ parser.add_argument(
34
+ "-p",
35
+ "--python",
36
+ dest="python_version",
37
+ default=None,
38
+ metavar="VERSION",
39
+ help="target Python version, e.g. 3.15 or 3.15t (default: running interpreter)",
40
+ )
41
+ parser.add_argument(
42
+ "--platform",
43
+ default=None,
44
+ metavar="PLATFORM",
45
+ help=(
46
+ "target platform: windows-arm64, windows-x86_64, linux-x86_64, "
47
+ "linux-aarch64, macos-arm64, macos-x86_64, any "
48
+ "(default: this machine)"
49
+ ),
50
+ )
51
+ parser.add_argument(
52
+ "--free-threaded",
53
+ action="store_true",
54
+ help="target a free-threaded (GIL-disabled) build",
55
+ )
56
+ parser.add_argument(
57
+ "--no-sdist",
58
+ action="store_true",
59
+ help="treat source-only releases as blockers instead of warnings",
60
+ )
61
+ parser.add_argument(
62
+ "--no-suggest",
63
+ action="store_true",
64
+ help="do not scan older releases for a version that has a wheel",
65
+ )
66
+ parser.add_argument(
67
+ "--json",
68
+ action="store_true",
69
+ help="emit machine-readable JSON",
70
+ )
71
+ parser.add_argument(
72
+ "-j",
73
+ "--jobs",
74
+ type=int,
75
+ default=8,
76
+ metavar="N",
77
+ help="concurrent PyPI requests (default: 8)",
78
+ )
79
+ parser.add_argument(
80
+ "--timeout",
81
+ type=float,
82
+ default=20.0,
83
+ metavar="SECONDS",
84
+ help="per-request timeout (default: 20)",
85
+ )
86
+ parser.add_argument(
87
+ "-V",
88
+ "--version",
89
+ action="version",
90
+ version=f"%(prog)s {__version__}",
91
+ )
92
+ return parser
93
+
94
+
95
+ def main(
96
+ argv: Sequence[str] | None = None,
97
+ *,
98
+ client: ProjectSource | None = None,
99
+ ) -> int:
100
+ """Run upcheck. Returns 0 when nothing blocks, 1 on blockers, 2 on usage errors."""
101
+ args = build_parser().parse_args(argv)
102
+
103
+ if args.jobs < 1:
104
+ print("upcheck: --jobs must be at least 1", file=sys.stderr)
105
+ return 2
106
+
107
+ try:
108
+ target = Target.parse(
109
+ args.python_version,
110
+ args.platform,
111
+ free_threaded=True if args.free_threaded else None,
112
+ )
113
+ except ValueError as exc:
114
+ print(f"upcheck: {exc}", file=sys.stderr)
115
+ return 2
116
+
117
+ try:
118
+ report = check_project(
119
+ Path(args.path),
120
+ target,
121
+ client=client or PyPIClient(timeout=args.timeout),
122
+ jobs=args.jobs,
123
+ allow_sdist=not args.no_sdist,
124
+ suggest=not args.no_suggest,
125
+ )
126
+ except RequirementsError as exc:
127
+ print(f"upcheck: {exc}", file=sys.stderr)
128
+ return 2
129
+
130
+ print(render_json(report) if args.json else render_text(report), end="")
131
+ return 0 if report.ok else 1
132
+
133
+
134
+ if __name__ == "__main__": # pragma: no cover
135
+ raise SystemExit(main())
upcheck/core.py ADDED
@@ -0,0 +1,136 @@
1
+ """Orchestration: turn a project's requirements and a target into a report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import urllib.error
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ from pathlib import Path
8
+ from typing import Protocol
9
+
10
+ from packaging.version import Version
11
+
12
+ from .pypi import (
13
+ PackageNotFound,
14
+ Project,
15
+ PyPIClient,
16
+ all_versions,
17
+ candidate_versions,
18
+ has_sdist,
19
+ pick_wheel,
20
+ )
21
+ from .report import PackageCheck, Report, Status
22
+ from .requirements import RequirementInfo, active, discover
23
+ from .target import Target
24
+
25
+ _MAX_LOOKUPS = 50
26
+
27
+
28
+ class ProjectSource(Protocol):
29
+ """Anything that can return project metadata (the real client or a fake)."""
30
+
31
+ def project(self, name: str) -> Project: ...
32
+
33
+
34
+ def check_project(
35
+ path: str | Path,
36
+ target: Target,
37
+ *,
38
+ client: ProjectSource | None = None,
39
+ jobs: int = 8,
40
+ allow_sdist: bool = True,
41
+ suggest: bool = True,
42
+ ) -> Report:
43
+ """Check every dependency of ``path`` against ``target``.
44
+
45
+ Only direct requirements are checked; transitive dependencies are left to
46
+ the resolver. Wheel selection does not rank manylinux/macOS versions.
47
+ """
48
+ requirements = active(discover(Path(path)), target)
49
+ if not requirements:
50
+ return Report(target=target, checks=())
51
+
52
+ source: ProjectSource = client or PyPIClient()
53
+ workers = max(1, min(jobs, len(requirements)))
54
+
55
+ with ThreadPoolExecutor(max_workers=workers) as pool:
56
+ futures = [
57
+ pool.submit(_check_one, requirement, target, source, allow_sdist, suggest)
58
+ for requirement in requirements
59
+ ]
60
+ checks = [future.result() for future in as_completed(futures)]
61
+
62
+ checks.sort(key=lambda check: (check.status.rank, check.name.lower()))
63
+ return Report(target=target, checks=tuple(checks))
64
+
65
+
66
+ def _check_one(
67
+ requirement: RequirementInfo,
68
+ target: Target,
69
+ client: ProjectSource,
70
+ allow_sdist: bool,
71
+ suggest: bool,
72
+ ) -> PackageCheck:
73
+ requested = str(requirement.specifier) or "*"
74
+
75
+ try:
76
+ project = client.project(requirement.name)
77
+ except PackageNotFound:
78
+ return PackageCheck(requirement.name, requested, None, Status.UNKNOWN, "not found on PyPI")
79
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
80
+ return PackageCheck(
81
+ requirement.name, requested, None, Status.UNKNOWN, f"network error: {exc}"
82
+ )
83
+
84
+ versions = candidate_versions(project, requirement.specifier)
85
+ if not versions:
86
+ return PackageCheck(
87
+ requirement.name,
88
+ requested,
89
+ None,
90
+ Status.BLOCKER,
91
+ "no release matches the specifier",
92
+ )
93
+
94
+ version = versions[0]
95
+ wheel = pick_wheel(project, version, target)
96
+ if wheel is not None:
97
+ return PackageCheck(
98
+ requirement.name,
99
+ requested,
100
+ str(version),
101
+ Status.OK,
102
+ "wheel available",
103
+ wheel=wheel,
104
+ )
105
+
106
+ suggestion = _suggest(project, target, version) if suggest else None
107
+
108
+ if allow_sdist and has_sdist(project, version):
109
+ return PackageCheck(
110
+ requirement.name,
111
+ requested,
112
+ str(version),
113
+ Status.WARNING,
114
+ "sdist only: needs a build toolchain",
115
+ suggestion=suggestion,
116
+ )
117
+
118
+ detail = "no compatible wheel (sdist rejected)" if not allow_sdist else "no compatible wheel"
119
+ return PackageCheck(
120
+ requirement.name,
121
+ requested,
122
+ str(version),
123
+ Status.BLOCKER,
124
+ detail,
125
+ suggestion=suggestion,
126
+ )
127
+
128
+
129
+ def _suggest(project: Project, target: Target, current: Version) -> str | None:
130
+ """Find a release (inside or outside the specifier) that does ship a wheel."""
131
+ for version in all_versions(project)[:_MAX_LOOKUPS]:
132
+ if version == current:
133
+ continue
134
+ if pick_wheel(project, version, target) is not None:
135
+ return f"try {version}"
136
+ return None
upcheck/py.typed ADDED
File without changes
upcheck/pypi.py ADDED
@@ -0,0 +1,155 @@
1
+ """Minimal PyPI JSON API client and release helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from dataclasses import dataclass
10
+ from typing import Any
11
+
12
+ from packaging.specifiers import SpecifierSet
13
+ from packaging.utils import canonicalize_name
14
+ from packaging.version import InvalidVersion, Version
15
+
16
+ from .target import Target, is_wheel_compatible
17
+
18
+
19
+ class PackageNotFound(Exception):
20
+ """The project does not exist on the index."""
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class DistFile:
25
+ """One file attached to a release."""
26
+
27
+ filename: str
28
+ packagetype: str
29
+ yanked: bool
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Project:
34
+ """The parts of the PyPI JSON response that upcheck needs."""
35
+
36
+ name: str
37
+ latest: str
38
+ releases: dict[str, tuple[DistFile, ...]]
39
+
40
+
41
+ class PyPIClient:
42
+ """Fetch and cache project metadata from a PyPI-compatible index."""
43
+
44
+ def __init__(
45
+ self,
46
+ base_url: str = "https://pypi.org/pypi",
47
+ timeout: float = 20.0,
48
+ user_agent: str = "upcheck (+https://github.com/OWNER/upcheck)",
49
+ ) -> None:
50
+ self.base_url = base_url.rstrip("/")
51
+ self.timeout = timeout
52
+ self.user_agent = user_agent
53
+ self._cache: dict[str, Project] = {}
54
+
55
+ def project(self, name: str) -> Project:
56
+ key = canonicalize_name(name)
57
+ if key in self._cache:
58
+ return self._cache[key]
59
+
60
+ url = f"{self.base_url}/{urllib.parse.quote(key)}/json"
61
+ # The URL is a fixed HTTPS base plus a canonicalized project name.
62
+ request = urllib.request.Request( # noqa: S310
63
+ url,
64
+ headers={"User-Agent": self.user_agent, "Accept": "application/json"},
65
+ )
66
+ try:
67
+ with urllib.request.urlopen(request, timeout=self.timeout) as response: # noqa: S310
68
+ payload = json.load(response)
69
+ except urllib.error.HTTPError as exc:
70
+ # We never read error bodies; close so the response file is released.
71
+ exc.close()
72
+ if exc.code == 404:
73
+ raise PackageNotFound(name) from exc
74
+ raise
75
+
76
+ project = _parse_project(payload)
77
+ self._cache[key] = project
78
+ return project
79
+
80
+
81
+ def _parse_project(payload: dict[str, Any]) -> Project:
82
+ info = payload.get("info") or {}
83
+ latest = str(info.get("version") or "")
84
+ versions: dict[str, tuple[DistFile, ...]] = {}
85
+
86
+ for version, entries in (payload.get("releases") or {}).items():
87
+ versions[str(version)] = tuple(_parse_file(entry) for entry in entries)
88
+
89
+ if latest and latest in versions and payload.get("urls"):
90
+ versions[latest] = tuple(_parse_file(entry) for entry in payload["urls"])
91
+
92
+ return Project(
93
+ name=str(info.get("name") or ""),
94
+ latest=latest,
95
+ releases=versions,
96
+ )
97
+
98
+
99
+ def _parse_file(entry: dict[str, Any]) -> DistFile:
100
+ return DistFile(
101
+ filename=str(entry.get("filename") or ""),
102
+ packagetype=str(entry.get("packagetype") or ""),
103
+ yanked=bool(entry.get("yanked")),
104
+ )
105
+
106
+
107
+ def candidate_versions(project: Project, specifier: SpecifierSet) -> list[Version]:
108
+ """Every release that satisfies ``specifier``, newest first."""
109
+ versions: list[Version] = []
110
+ for raw in project.releases:
111
+ try:
112
+ version = Version(raw)
113
+ except InvalidVersion:
114
+ continue
115
+ if version.is_prerelease and not specifier.prereleases:
116
+ continue
117
+ if specifier.contains(version):
118
+ versions.append(version)
119
+ versions.sort(reverse=True)
120
+ return versions
121
+
122
+
123
+ def all_versions(project: Project) -> list[Version]:
124
+ """Every final release, newest first."""
125
+ versions: list[Version] = []
126
+ for raw in project.releases:
127
+ try:
128
+ version = Version(raw)
129
+ except InvalidVersion:
130
+ continue
131
+ if version.is_prerelease:
132
+ continue
133
+ versions.append(version)
134
+ versions.sort(reverse=True)
135
+ return versions
136
+
137
+
138
+ def pick_wheel(project: Project, version: Version, target: Target) -> str | None:
139
+ """Return the first file installable on ``target``, if any."""
140
+ for dist in project.releases.get(str(version), ()):
141
+ if dist.yanked or not dist.filename.endswith(".whl"):
142
+ continue
143
+ if is_wheel_compatible(dist.filename, target):
144
+ return dist.filename
145
+ return None
146
+
147
+
148
+ def has_sdist(project: Project, version: Version) -> bool:
149
+ """Return whether the release ships a source distribution."""
150
+ for dist in project.releases.get(str(version), ()):
151
+ if dist.yanked:
152
+ continue
153
+ if dist.packagetype == "sdist" or dist.filename.endswith((".tar.gz", ".zip")):
154
+ return True
155
+ return False
upcheck/report.py ADDED
@@ -0,0 +1,128 @@
1
+ """Result models and renderers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import Counter
7
+ from dataclasses import dataclass
8
+ from enum import StrEnum
9
+
10
+ from .target import Target
11
+
12
+
13
+ class Status(StrEnum):
14
+ """Outcome for a single package."""
15
+
16
+ BLOCKER = "blocker"
17
+ WARNING = "warning"
18
+ UNKNOWN = "unknown"
19
+ OK = "ok"
20
+
21
+ @property
22
+ def rank(self) -> int:
23
+ """Sort order: problems first."""
24
+ return {
25
+ Status.BLOCKER: 0,
26
+ Status.WARNING: 1,
27
+ Status.UNKNOWN: 2,
28
+ Status.OK: 3,
29
+ }[self]
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class PackageCheck:
34
+ """What upcheck found for one requirement."""
35
+
36
+ name: str
37
+ requested: str
38
+ version: str | None
39
+ status: Status
40
+ detail: str
41
+ wheel: str | None = None
42
+ suggestion: str | None = None
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class Report:
47
+ """All package checks for one target."""
48
+
49
+ target: Target
50
+ checks: tuple[PackageCheck, ...]
51
+
52
+ @property
53
+ def ok(self) -> bool:
54
+ """True when nothing blocks the upgrade."""
55
+ return all(check.status is not Status.BLOCKER for check in self.checks)
56
+
57
+ def counts(self) -> Counter[Status]:
58
+ return Counter(check.status for check in self.checks)
59
+
60
+
61
+ _GROUPS = (
62
+ (Status.BLOCKER, "BLOCKERS"),
63
+ (Status.WARNING, "WARNINGS"),
64
+ (Status.UNKNOWN, "UNKNOWN"),
65
+ (Status.OK, "OK"),
66
+ )
67
+
68
+
69
+ def render_text(report: Report) -> str:
70
+ """Render a human-readable report."""
71
+ counts = report.counts()
72
+ lines = [
73
+ f"target {report.target.label}",
74
+ f"packages {len(report.checks)}",
75
+ "",
76
+ ]
77
+
78
+ for status, title in _GROUPS:
79
+ group = [check for check in report.checks if check.status is status]
80
+ if not group:
81
+ continue
82
+ lines.append(f"{title} ({len(group)})")
83
+ for check in group:
84
+ name = check.name if len(check.name) <= 26 else f"{check.name[:25]}…"
85
+ version = check.version or "-"
86
+ detail = check.detail
87
+ if check.suggestion:
88
+ detail = f"{detail} -> {check.suggestion}"
89
+ lines.append(f" {name:<26} {version:<12} {detail}")
90
+ lines.append("")
91
+
92
+ lines.append(
93
+ f"result {counts[Status.OK]} ok, {counts[Status.WARNING]} warnings, "
94
+ f"{counts[Status.BLOCKER]} blockers"
95
+ )
96
+ return "\n".join(lines) + "\n"
97
+
98
+
99
+ def render_json(report: Report) -> str:
100
+ """Render a machine-readable report."""
101
+ counts = report.counts()
102
+ payload = {
103
+ "target": {
104
+ "python": f"{report.target.python[0]}.{report.target.python[1]}",
105
+ "free_threaded": report.target.free_threaded,
106
+ "platform": report.target.platform,
107
+ },
108
+ "summary": {
109
+ "ok": counts[Status.OK],
110
+ "warnings": counts[Status.WARNING],
111
+ "blockers": counts[Status.BLOCKER],
112
+ "unknown": counts[Status.UNKNOWN],
113
+ },
114
+ "packages": [
115
+ {
116
+ "name": check.name,
117
+ "requested": check.requested,
118
+ "version": check.version,
119
+ "status": check.status.value,
120
+ "detail": check.detail,
121
+ "wheel": check.wheel,
122
+ "suggestion": check.suggestion,
123
+ }
124
+ for check in report.checks
125
+ ],
126
+ "exit_code": 0 if report.ok else 1,
127
+ }
128
+ return json.dumps(payload, indent=2) + "\n"
@@ -0,0 +1,167 @@
1
+ """Discover and parse project requirements."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tomllib
7
+ import warnings
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from packaging.markers import Marker
12
+ from packaging.requirements import InvalidRequirement, Requirement
13
+ from packaging.specifiers import SpecifierSet
14
+
15
+ from .target import Target
16
+
17
+ _REQUIREMENT_FILES = (
18
+ "requirements.txt",
19
+ "requirements-dev.txt",
20
+ "requirements/all.txt",
21
+ "requirements/base.txt",
22
+ )
23
+
24
+ _INLINE_COMMENT = re.compile(r"\s+#.*$")
25
+
26
+
27
+ class RequirementsError(Exception):
28
+ """Raised when requirements cannot be discovered or parsed."""
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class RequirementInfo:
33
+ """One parsed requirement."""
34
+
35
+ name: str
36
+ specifier: SpecifierSet
37
+ marker: Marker | None
38
+ raw: str
39
+
40
+
41
+ def discover(path: Path) -> list[RequirementInfo]:
42
+ """Find and parse the requirements for a project path."""
43
+ if path.is_file():
44
+ if path.suffix == ".toml":
45
+ return from_pyproject(path)
46
+ return from_requirements(path)
47
+
48
+ if not path.is_dir():
49
+ raise RequirementsError(f"no such file or directory: {path}")
50
+
51
+ pyproject = path / "pyproject.toml"
52
+ if pyproject.is_file():
53
+ return from_pyproject(pyproject)
54
+
55
+ for name in _REQUIREMENT_FILES:
56
+ candidate = path / name
57
+ if candidate.is_file():
58
+ return from_requirements(candidate)
59
+
60
+ raise RequirementsError(f"found neither pyproject.toml nor requirements.txt in {path}")
61
+
62
+
63
+ def from_pyproject(path: Path) -> list[RequirementInfo]:
64
+ """Read ``[project].dependencies`` from a pyproject.toml."""
65
+ try:
66
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
67
+ except (OSError, tomllib.TOMLDecodeError) as exc:
68
+ raise RequirementsError(f"cannot read {path}: {exc}") from exc
69
+
70
+ project = data.get("project")
71
+ if not isinstance(project, dict):
72
+ raise RequirementsError(f"{path} has no [project] table")
73
+
74
+ dynamic = project.get("dynamic") or []
75
+ if "dependencies" in dynamic:
76
+ raise RequirementsError(
77
+ "dependencies are declared dynamic; pin them in pyproject.toml "
78
+ "or point upcheck at a requirements file"
79
+ )
80
+
81
+ raw = project.get("dependencies") or []
82
+ if not isinstance(raw, list):
83
+ raise RequirementsError(f"{path}: [project].dependencies must be an array")
84
+ return parse_all(raw, source=str(path))
85
+
86
+
87
+ def from_requirements(path: Path) -> list[RequirementInfo]:
88
+ """Parse a pip requirements file."""
89
+ try:
90
+ text = path.read_text(encoding="utf-8")
91
+ except OSError as exc:
92
+ raise RequirementsError(f"cannot read {path}: {exc}") from exc
93
+
94
+ lines: list[str] = []
95
+ for raw_line in text.splitlines():
96
+ line = _INLINE_COMMENT.sub("", raw_line).strip()
97
+ if not line or line.startswith("#"):
98
+ continue
99
+ if line.startswith("-"):
100
+ # Index options, editables, constraint files and hashes are out of scope.
101
+ continue
102
+ if "://" in line and "@" not in line:
103
+ warnings.warn(f"skipping direct URL requirement: {line}", stacklevel=2)
104
+ continue
105
+ lines.append(line)
106
+ return parse_all(lines, source=str(path))
107
+
108
+
109
+ def parse_all(raw: list[str], *, source: str) -> list[RequirementInfo]:
110
+ """Parse a list of PEP 508 requirement strings."""
111
+ parsed: list[RequirementInfo] = []
112
+ for line in raw:
113
+ try:
114
+ requirement = Requirement(line)
115
+ except InvalidRequirement as exc:
116
+ raise RequirementsError(f"{source}: invalid requirement {line!r}: {exc}") from exc
117
+ parsed.append(
118
+ RequirementInfo(
119
+ name=requirement.name,
120
+ specifier=requirement.specifier,
121
+ marker=requirement.marker,
122
+ raw=line,
123
+ )
124
+ )
125
+ return parsed
126
+
127
+
128
+ def active(requirements: list[RequirementInfo], target: Target) -> list[RequirementInfo]:
129
+ """Drop requirements whose environment marker excludes the target.
130
+
131
+ With an ``any`` platform the environment is unknown, so every marker is
132
+ kept rather than guessed.
133
+ """
134
+ if target.platform == "any":
135
+ return list(requirements)
136
+ environment = marker_environment(target)
137
+ return [r for r in requirements if r.marker is None or r.marker.evaluate(environment)]
138
+
139
+
140
+ def marker_environment(target: Target) -> dict[str, str]:
141
+ """Build a PEP 508 marker environment for a target."""
142
+ if target.platform.startswith("windows"):
143
+ os_name, sys_platform, platform_system = "nt", "win32", "Windows"
144
+ elif target.platform.startswith("macos"):
145
+ os_name, sys_platform, platform_system = "posix", "darwin", "Darwin"
146
+ else:
147
+ os_name, sys_platform, platform_system = "posix", "linux", "Linux"
148
+
149
+ arch = target.platform.split("-", 1)[1] if "-" in target.platform else ""
150
+ if target.platform.startswith("windows"):
151
+ machine = {"x86_64": "AMD64", "arm64": "ARM64", "x86": "x86"}.get(arch, arch)
152
+ else:
153
+ machine = {"x86": "i686"}.get(arch, arch)
154
+
155
+ version = f"{target.python[0]}.{target.python[1]}"
156
+ return {
157
+ "implementation_name": "cpython",
158
+ "implementation_version": f"{version}.0",
159
+ "os_name": os_name,
160
+ "platform_machine": machine,
161
+ "platform_python_implementation": "CPython",
162
+ "platform_system": platform_system,
163
+ "python_full_version": f"{version}.0",
164
+ "python_version": version,
165
+ "sys_platform": sys_platform,
166
+ "extra": "",
167
+ }
upcheck/target.py ADDED
@@ -0,0 +1,221 @@
1
+ """Target interpreter/platform description and wheel tag matching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sys
7
+ import sysconfig
8
+ from dataclasses import dataclass
9
+
10
+ from packaging.tags import Tag
11
+ from packaging.utils import InvalidWheelFilename, parse_wheel_filename
12
+
13
+ _PYTHON_RE = re.compile(r"^(?:cp)?(\d)\.?(\d+)(t)?$", re.IGNORECASE)
14
+
15
+ _PLATFORM_ALIASES = {
16
+ "any": "any",
17
+ "win": "windows",
18
+ "windows": "windows",
19
+ "win32": "windows-x86",
20
+ "win_amd64": "windows-x86_64",
21
+ "win_arm64": "windows-arm64",
22
+ "windows-x86_64": "windows-x86_64",
23
+ "windows-amd64": "windows-x86_64",
24
+ "windows-arm64": "windows-arm64",
25
+ "windows-aarch64": "windows-arm64",
26
+ "linux": "linux",
27
+ "manylinux": "linux",
28
+ "musllinux": "linux",
29
+ "linux-x86_64": "linux-x86_64",
30
+ "linux-amd64": "linux-x86_64",
31
+ "manylinux-x86_64": "linux-x86_64",
32
+ "linux-aarch64": "linux-aarch64",
33
+ "linux-arm64": "linux-aarch64",
34
+ "macos": "macos",
35
+ "macosx": "macos",
36
+ "osx": "macos",
37
+ "darwin": "macos",
38
+ "macos-arm64": "macos-arm64",
39
+ "macosx-arm64": "macos-arm64",
40
+ "macos-x86_64": "macos-x86_64",
41
+ "macosx-x86_64": "macos-x86_64",
42
+ }
43
+
44
+ _ACCEPTED_PLATFORMS = ", ".join(sorted(set(_PLATFORM_ALIASES.values())))
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class Target:
49
+ """A Python version, ABI mode and platform to test against."""
50
+
51
+ python: tuple[int, int]
52
+ platform: str = "any"
53
+ free_threaded: bool = False
54
+
55
+ @property
56
+ def label(self) -> str:
57
+ mode = "free-threaded" if self.free_threaded else "GIL"
58
+ return f"Python {self.python[0]}.{self.python[1]} ({mode}) on {self.platform}"
59
+
60
+ @classmethod
61
+ def parse(
62
+ cls,
63
+ python: str | None = None,
64
+ platform: str | None = None,
65
+ *,
66
+ free_threaded: bool | None = None,
67
+ ) -> Target:
68
+ """Build a target from CLI-style strings.
69
+
70
+ ``python`` accepts ``3.15``, ``315``, ``cp315`` and a trailing ``t``
71
+ for free-threaded builds. ``platform`` accepts wheel-style tags
72
+ (``win_arm64``) and friendlier names (``windows-arm64``).
73
+ """
74
+ if python is None:
75
+ version = (sys.version_info.major, sys.version_info.minor)
76
+ detected_free_threaded = _running_free_threaded()
77
+ else:
78
+ match = _PYTHON_RE.match(python.strip())
79
+ if match is None:
80
+ raise ValueError(f"cannot parse Python version {python!r}; try 3.15 or 3.15t")
81
+ version = (int(match.group(1)), int(match.group(2)))
82
+ detected_free_threaded = match.group(3) is not None
83
+
84
+ if free_threaded is None:
85
+ free_threaded = detected_free_threaded
86
+
87
+ return cls(
88
+ python=version,
89
+ platform=_parse_platform(platform),
90
+ free_threaded=free_threaded,
91
+ )
92
+
93
+ @classmethod
94
+ def current(cls) -> Target:
95
+ """Target the interpreter that is running this code."""
96
+ return cls.parse(None, _current_platform())
97
+
98
+
99
+ def _parse_platform(platform: str | None) -> str:
100
+ if platform is None or not platform.strip():
101
+ return _current_platform()
102
+ key = platform.strip().lower()
103
+ try:
104
+ return _PLATFORM_ALIASES[key]
105
+ except KeyError:
106
+ raise ValueError(
107
+ f"unknown platform {platform!r}; expected one of: {_ACCEPTED_PLATFORMS}"
108
+ ) from None
109
+
110
+
111
+ def _current_platform() -> str:
112
+ machine = _machine()
113
+ if sys.platform.startswith("win"):
114
+ return "windows-arm64" if machine in {"arm64", "aarch64"} else "windows-x86_64"
115
+ if sys.platform == "darwin":
116
+ return "macos-arm64" if machine in {"arm64", "aarch64"} else "macos-x86_64"
117
+ if sys.platform.startswith("linux"):
118
+ return "linux-aarch64" if machine in {"arm64", "aarch64"} else "linux-x86_64"
119
+ return "any"
120
+
121
+
122
+ def _machine() -> str:
123
+ import platform as platform_module
124
+
125
+ return platform_module.machine().lower()
126
+
127
+
128
+ def _running_free_threaded() -> bool:
129
+ return bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
130
+
131
+
132
+ def is_wheel_compatible(filename: str, target: Target) -> bool:
133
+ """Return whether a wheel filename can be installed on ``target``."""
134
+ try:
135
+ _, _, _, tags = parse_wheel_filename(filename)
136
+ except (InvalidWheelFilename, ValueError):
137
+ return False
138
+ return any(_tag_compatible(tag, target) for tag in tags)
139
+
140
+
141
+ def _tag_compatible(tag: Tag, target: Target) -> bool:
142
+ if not _platform_compatible(tag.platform, target.platform):
143
+ return False
144
+ return _abi_compatible(tag, target)
145
+
146
+
147
+ def _abi_compatible(tag: Tag, target: Target) -> bool:
148
+ abi = tag.abi
149
+ if abi == "none":
150
+ return tag.interpreter.startswith("py") and _py_tag_ok(tag.interpreter, target.python)
151
+
152
+ cp = f"cp{target.python[0]}{target.python[1]}"
153
+
154
+ if target.free_threaded:
155
+ if abi == "abi3t":
156
+ version = _cp_version(tag.interpreter)
157
+ return version is not None and version <= target.python
158
+ return abi == f"{cp}t"
159
+
160
+ if abi == "abi3":
161
+ version = _cp_version(tag.interpreter)
162
+ return version is not None and version <= target.python
163
+
164
+ # Extension modules are version-specific: cp315 wheels do not load on 3.14
165
+ # and cp314 wheels do not load on 3.15.
166
+ return abi == cp
167
+
168
+
169
+ def _py_tag_ok(interpreter: str, target: tuple[int, int]) -> bool:
170
+ for part in interpreter.split("."):
171
+ if not part.startswith("py"):
172
+ return False
173
+ digits = part[2:]
174
+ if not digits.isdigit():
175
+ return False
176
+ version = (int(digits[0]), int(digits[1:])) if len(digits) > 1 else (int(digits), 0)
177
+ if version > target:
178
+ return False
179
+ return True
180
+
181
+
182
+ def _cp_version(interpreter: str) -> tuple[int, int] | None:
183
+ if not interpreter.startswith("cp"):
184
+ return None
185
+ digits = interpreter[2:].rstrip("t")
186
+ if not digits.isdigit() or len(digits) < 2:
187
+ return None
188
+ return (int(digits[0]), int(digits[1:]))
189
+
190
+
191
+ def _platform_compatible(wheel_platform: str, target: str) -> bool:
192
+ if wheel_platform == "any" or target == "any":
193
+ return True
194
+
195
+ if target == "windows":
196
+ return wheel_platform.startswith("win")
197
+ if target.startswith("windows-"):
198
+ arch = target.split("-", 1)[1]
199
+ return wheel_platform == {
200
+ "x86_64": "win_amd64",
201
+ "arm64": "win_arm64",
202
+ "x86": "win32",
203
+ }.get(arch, f"win_{arch}")
204
+
205
+ if target == "linux":
206
+ return wheel_platform.startswith(("manylinux", "musllinux", "linux_"))
207
+ if target.startswith("linux-"):
208
+ arch = target.split("-", 1)[1]
209
+ if not wheel_platform.endswith(f"_{arch}"):
210
+ return False
211
+ return wheel_platform.startswith(("manylinux", "musllinux", "linux_"))
212
+
213
+ if target == "macos":
214
+ return wheel_platform.startswith("macosx")
215
+ if target.startswith("macos-"):
216
+ arch = target.split("-", 1)[1]
217
+ if arch == "arm64":
218
+ return wheel_platform.endswith("_arm64") or wheel_platform.endswith("universal2")
219
+ return wheel_platform.endswith(f"_{arch}") or wheel_platform.endswith("universal2")
220
+
221
+ return False
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.5
2
+ Name: upcheck
3
+ Version: 0.1.0
4
+ Summary: Check whether your dependencies install on a target Python version, ABI and platform.
5
+ Project-URL: Homepage, https://github.com/OWNER/upcheck
6
+ Project-URL: Repository, https://github.com/OWNER/upcheck
7
+ Project-URL: Issues, https://github.com/OWNER/upcheck/issues
8
+ Project-URL: Changelog, https://github.com/OWNER/upcheck/blob/main/CHANGELOG.md
9
+ Author-email: pydev88 <pydev88@proton.me>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: arm64,ci,free-threading,packaging,python-version,upgrade,wheels
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Topic :: Software Development :: Build Tools
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.11
26
+ Requires-Dist: packaging>=24.2
27
+ Description-Content-Type: text/markdown
28
+
29
+ # upcheck
30
+
31
+ [![CI](https://github.com/OWNER/upcheck/actions/workflows/ci.yml/badge.svg)](https://github.com/OWNER/upcheck/actions/workflows/ci.yml)
32
+ [![PyPI](https://img.shields.io/pypi/v/upcheck.svg)](https://pypi.org/project/upcheck/)
33
+ [![Python versions](https://img.shields.io/pypi/pyversions/upcheck.svg)](https://pypi.org/project/upcheck/)
34
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
35
+
36
+ **Will your dependencies install on that Python?** `upcheck` answers before you
37
+ upgrade, not after `pip` fails.
38
+
39
+ It reads your requirements, asks PyPI which wheels exist, and reports the
40
+ packages that have no compatible wheel for a target Python version, ABI
41
+ (free-threaded) and platform:
42
+
43
+ ```console
44
+ $ upcheck . --python 3.15 --platform windows-arm64
45
+ target Python 3.15 (GIL) on windows-arm64
46
+ packages 3
47
+
48
+ BLOCKERS (1)
49
+ grpcio 1.85.4 no compatible wheel
50
+ WARNINGS (1)
51
+ psycopg2-binary 2.9.13 sdist only: needs a build toolchain
52
+ OK (1)
53
+ packaging 26.4 wheel available
54
+
55
+ result 1 ok, 1 warnings, 1 blockers
56
+ ```
57
+
58
+ ## Install
59
+
60
+ ```console
61
+ pip install upcheck
62
+ # or
63
+ uv tool install upcheck
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ ```console
69
+ upcheck [PATH] [--python 3.15] [--platform windows-arm64] [--json]
70
+ ```
71
+
72
+ `PATH` may be a project directory (reads `pyproject.toml`, then
73
+ `requirements.txt`), a `pyproject.toml`, or a requirements file.
74
+
75
+ | Flag | Meaning |
76
+ | --- | --- |
77
+ | `-p`, `--python` | Target version: `3.15`, `315`, `cp315`, or `3.15t` for free-threaded |
78
+ | `--platform` | `windows-arm64`, `windows-x86_64`, `linux-x86_64`, `linux-aarch64`, `macos-arm64`, `macos-x86_64`, `any` |
79
+ | `--free-threaded` | Force a free-threaded (GIL-disabled) target |
80
+ | `--no-sdist` | Treat source-only releases as blockers instead of warnings |
81
+ | `--no-suggest` | Skip scanning older releases for a version that does have a wheel |
82
+ | `--json` | Machine-readable output |
83
+ | `-j`, `--jobs` | Concurrent PyPI requests (default 8) |
84
+ | `--timeout` | Per-request timeout in seconds (default 20) |
85
+
86
+ Both `--python` and `--platform` default to the interpreter and machine running
87
+ the command.
88
+
89
+ ### Exit codes
90
+
91
+ | Code | Meaning |
92
+ | --- | --- |
93
+ | `0` | Nothing blocks the target (warnings and unknown packages are allowed) |
94
+ | `1` | At least one blocker |
95
+ | `2` | Bad arguments, unreadable project, or unsupported requirements |
96
+
97
+ ### In CI
98
+
99
+ ```yaml
100
+ - name: Check the next Python
101
+ run: |
102
+ pipx run upcheck . --python 3.15 --platform linux-x86_64
103
+ ```
104
+
105
+ Use `--json` when you want to post-process the result:
106
+
107
+ ```json
108
+ {
109
+ "target": {"python": "3.15", "free_threaded": false, "platform": "windows-arm64"},
110
+ "summary": {"ok": 41, "warnings": 1, "blockers": 1, "unknown": 0},
111
+ "packages": [
112
+ {
113
+ "name": "grpcio",
114
+ "requested": ">=1.80",
115
+ "version": "1.85.4",
116
+ "status": "blocker",
117
+ "detail": "no compatible wheel",
118
+ "wheel": null,
119
+ "suggestion": null
120
+ }
121
+ ],
122
+ "exit_code": 1
123
+ }
124
+ ```
125
+
126
+ ## What it checks
127
+
128
+ 1. Direct requirements from `[project].dependencies` or a requirements file.
129
+ 2. Environment markers (`sys_platform`, `python_version`, …) against the target.
130
+ 3. The newest release satisfying each specifier.
131
+ 4. Whether that release ships a wheel whose tags fit the target:
132
+ - CPython ABI: `cp315` on 3.15, `abi3` forward-compatible, `abi3t` for
133
+ free-threaded 3.15+
134
+ - platforms: `win_arm64`, `manylinux`/`musllinux`, `macosx` + `universal2`
135
+ 5. If not, an sdist means "warning"; nothing means "blocker".
136
+ 6. Optional: the newest older release that does have a compatible wheel.
137
+
138
+ ## Limitations (v0.1)
139
+
140
+ - Direct dependencies only; transitive resolution is left to pip/uv.
141
+ - Manylinux and macOS deployment targets are not version-ranked.
142
+ - Private indexes are not configurable yet (the client supports it, the CLI
143
+ does not).
144
+ - `uv.lock`/`pylock.toml` are not read yet.
145
+ - No source-level API checks: this release answers "can it install?", not
146
+ "will it run?".
147
+
148
+ ## Development
149
+
150
+ ```console
151
+ uv sync
152
+ uv run pytest
153
+ uv run ruff check . && uv run ruff format .
154
+ uv run mypy
155
+ ```
156
+
157
+ Without uv:
158
+
159
+ ```console
160
+ python -m venv .venv
161
+ .venv\Scripts\activate # Windows (bash: source .venv/Scripts/activate)
162
+ pip install -e . --group dev
163
+ pytest
164
+ ```
165
+
166
+ ## Release
167
+
168
+ 1. Bump `version` in `pyproject.toml` and add a `CHANGELOG.md` entry.
169
+ 2. Commit, tag and push: `git tag -a v0.1.0 -m v0.1.0 && git push --tags`.
170
+ 3. The `Release` workflow builds the sdist/wheel and publishes with Trusted
171
+ Publishing (no API tokens).
172
+
173
+ Before the first release, add a GitHub publisher on PyPI:
174
+ owner `OWNER`, repository `upcheck`, workflow `release.yml`, environment `pypi`.
175
+ For a dry run, configure the same on <https://test.pypi.org> (environment
176
+ `testpypi`) and trigger the workflow manually.
177
+
178
+ Manual dry run without GitHub:
179
+
180
+ ```console
181
+ python -m build
182
+ python -m twine upload --repository testpypi dist/*
183
+ ```
184
+
185
+ ## License
186
+
187
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,14 @@
1
+ upcheck/__init__.py,sha256=JWJV2n3T8wz6M52Cr4F1uLpESXZaRuZ4cZKUELhsvmg,507
2
+ upcheck/__main__.py,sha256=M-MU8Qa4rx3i4G3euc1DGTDomnyiHLE2upa2g1BdzAY,117
3
+ upcheck/cli.py,sha256=JFZkisGEhoHyurtSkGHw_kcX29PG6C4aG3cokCCtmOk,3712
4
+ upcheck/core.py,sha256=q-ISTYMmMv7BJH5wwqyPNMLOgwsCLPEAexzE6BXHBPo,4011
5
+ upcheck/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ upcheck/pypi.py,sha256=GHZWO_fbQ7TEH-y8qnF9s2KWUFQpjMSNLMNd5LgQVWI,4803
7
+ upcheck/report.py,sha256=-h4taqfp-k9U51C4huUuwjH2k5FDtqYEv5ww1UqEBqs,3470
8
+ upcheck/requirements.py,sha256=Cc11OExyY09luHu47KNNd8S2msejuoCPLWDgYgOjie0,5556
9
+ upcheck/target.py,sha256=Bgk5J8ySFHyoPlzGi4Z8i7HxnfeYQSKYztiyyRXOdMo,7162
10
+ upcheck-0.1.0.dist-info/METADATA,sha256=ZUT16OuS6S2Em1aQUwTivMGSAny_J6W-Wwb4dtHD7Ts,6148
11
+ upcheck-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ upcheck-0.1.0.dist-info/entry_points.txt,sha256=POz1XFs1no1sz2IYHNDb4rjhQq_39H_UtXS3RQ2o5sQ,45
13
+ upcheck-0.1.0.dist-info/licenses/LICENSE,sha256=v2spsd7N1pKFFh2G8wGP_45iwe5S0DYiJzG4im8Rupc,1066
14
+ upcheck-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ upcheck = upcheck.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Your Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.