python-version-claim-audit 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.
@@ -0,0 +1,182 @@
1
+ """Offline, read-only audit of version claims."""
2
+ import argparse
3
+ import fnmatch
4
+ import io
5
+ import json
6
+ from pathlib import Path
7
+ import re
8
+ import tokenize
9
+
10
+ __version__ = "0.1.0"
11
+ V = r"3\.(?:1[0-4]|[89])(?![\d.])"
12
+ CLASSIFIER = re.compile(r"Programming Language :: Python :: (3\.\d+)(?![\d.])")
13
+
14
+
15
+ def version(value):
16
+ if not re.fullmatch(r"\d+(?:\.\d+)*", value):
17
+ raise ValueError("unsupported version: " + value)
18
+ parts = tuple(map(int, value.split(".")))
19
+ return parts + (0,) * (3 - len(parts))
20
+
21
+
22
+ def satisfies(candidate, spec):
23
+ """Evaluate our numeric subset of PEP 440, with comma conjunction."""
24
+ current = version(candidate)
25
+ outcomes = []
26
+ for item in spec.split(","):
27
+ match = re.fullmatch(r"\s*(~=|==|!=|>=|<=|>|<)\s*(\d+(?:\.\d+)*(?:\.\*)?)\s*", item)
28
+ if not match:
29
+ raise ValueError("unsupported specifier: " + item)
30
+ op, target = match.groups()
31
+ if target.endswith(".*"):
32
+ if op not in ("==", "!="):
33
+ raise ValueError("wildcards require == or !=")
34
+ prefix = tuple(map(int, target[:-2].split(".")))
35
+ equal = current[:len(prefix)] == prefix
36
+ outcomes.append(equal if op == "==" else not equal)
37
+ continue
38
+ other = version(target)
39
+ if op == "~=":
40
+ parts = list(map(int, target.split(".")))
41
+ if len(parts) < 2:
42
+ raise ValueError("compatible release needs two components")
43
+ upper = parts[:-1]
44
+ upper[-1] += 1
45
+ outcomes.append(current >= other and current < version(".".join(map(str, upper))))
46
+ else:
47
+ outcomes.append({"==": current == other, "!=": current != other,
48
+ ">=": current >= other, "<=": current <= other,
49
+ ">": current > other, "<": current < other}[op])
50
+ return all(outcomes)
51
+
52
+
53
+ def without_comments(text, is_python=False):
54
+ if is_python:
55
+ try:
56
+ return tokenize.untokenize(t for t in tokenize.generate_tokens(io.StringIO(text).readline)
57
+ if t.type != tokenize.COMMENT)
58
+ except (tokenize.TokenError, IndentationError):
59
+ raise ValueError("cannot tokenize setup.py")
60
+ # Preserve hash characters within quoted strings.
61
+ return re.sub(r"(\"[^\"\n]*\"|'[^'\n]*')|#[^\n]*", lambda m: m.group(1) or "", text)
62
+
63
+
64
+ def evidence(root):
65
+ sources = []
66
+ for name in ("pyproject.toml", "setup.py", "setup.cfg"):
67
+ path = root / name
68
+ if not path.is_file():
69
+ continue
70
+ raw = path.read_text(encoding="utf-8")
71
+ clean = without_comments(raw, name == "setup.py")
72
+ sources.append(clean)
73
+ if name == "pyproject.toml":
74
+ section = re.search(r"(?ms)^\[project\]\s*$(.*?)(?=^\[|\Z)", clean)
75
+ target = section.group(1) if section else ""
76
+ match = re.search(r"(?m)^\s*requires-python\s*=\s*['\"]([^'\"]+)['\"]", target)
77
+ elif name == "setup.py":
78
+ match = re.search(r"\bpython_requires\s*=\s*['\"]([^'\"]+)['\"]", clean)
79
+ else:
80
+ section = re.search(r"(?ms)^\[options\]\s*$(.*?)(?=^\[|\Z)", clean)
81
+ target = section.group(1) if section else ""
82
+ match = re.search(r"(?m)^\s*python_requires\s*=\s*['\"]?([^'\"\n]+)", target)
83
+ if match:
84
+ spec = match.group(1).strip()
85
+ satisfies("3.9", spec) # Validate even when there are no claims.
86
+ return spec, None
87
+ listed = set(CLASSIFIER.findall("\n".join(sources)))
88
+ return None, listed or None
89
+
90
+
91
+ def claims(text):
92
+ fence = None
93
+ for number, line in enumerate(text.splitlines(), 1):
94
+ marker = re.match(r"^\s{0,3}(`{3,}|~{3,})", line)
95
+ if marker:
96
+ run = marker.group(1)
97
+ if fence is None:
98
+ fence = run
99
+ elif run[0] == fence[0] and len(run) >= len(fence) and not line[marker.end():].strip():
100
+ fence = None
101
+ continue
102
+ if fence:
103
+ continue
104
+ occupied = []
105
+ negative = [rf"does not support Python ({V})", rf"no Python ({V}) support",
106
+ rf"not compatible with Python ({V})", rf"Python ({V}) not supported",
107
+ rf"does not work with Python ({V})", rf"drops Python ({V})", rf"dropped Python ({V})"]
108
+ positive = [rf"Python ({V}) or higher", rf"Python ({V}) or later", rf"Python ({V})\+",
109
+ rf"Python >= ({V})", rf"requires Python ({V})", rf"supports Python ({V})",
110
+ rf"works with Python ({V})", rf"runs on Python ({V})",
111
+ rf"compatible with Python ({V})", rf"Python ({V}) supported"]
112
+ found = []
113
+ for pattern in negative:
114
+ for m in re.finditer(r"(?<!\w)" + pattern + r"(?!\w)", line):
115
+ occupied.append(m.span())
116
+ found.append((m.start(), "NOSUPPORT", m.group(1)))
117
+ for m in re.finditer(rf"(?<!\w)Python ({V})(?: to |-|–)({V})(?!\w)", line):
118
+ a, b = int(m.group(1)[2:]), int(m.group(2)[2:])
119
+ if a <= b:
120
+ occupied.append(m.span())
121
+ found.extend((m.start(), "SUPPORT", "3." + str(n)) for n in range(a, b + 1))
122
+ for pattern in positive:
123
+ for m in re.finditer(r"(?<!\w)" + pattern + r"(?!\w)", line):
124
+ if not any(m.start() < end and m.end() > start for start, end in occupied):
125
+ occupied.append(m.span())
126
+ found.append((m.start(), "SUPPORT", m.group(1)))
127
+ for _, kind, value in sorted(found, key=lambda item: item[0]):
128
+ yield number, kind, value
129
+
130
+
131
+ def audit(root, ignores=()):
132
+ root = Path(root)
133
+ if not root.is_dir():
134
+ raise ValueError("root must be a directory")
135
+ spec, listed = evidence(root)
136
+ paths = [root / "README.md"] + sorted((root / "docs").rglob("*.md"))
137
+ findings = {}
138
+ for path in paths:
139
+ if not path.is_file() or path.is_symlink():
140
+ continue
141
+ relative = path.relative_to(root).as_posix()
142
+ if any(fnmatch.fnmatch(relative, pattern) for pattern in ignores):
143
+ continue
144
+ for line, kind, value in claims(path.read_text(encoding="utf-8")):
145
+ supported = satisfies(value, spec) if spec is not None else (value in listed if listed else None)
146
+ false = supported is not True if kind == "SUPPORT" else supported is True
147
+ if false:
148
+ family = "documented-version-claim-false" if kind == "SUPPORT" else "documented-no-version-claim-false"
149
+ findings.setdefault(family, {"rule": family, "severity": "MEDIUM" if "tests" in path.relative_to(root).parts[:-1] else "HIGH",
150
+ "file": relative, "line": line, "version": value, "claim": kind})
151
+ return list(findings.values())
152
+
153
+
154
+ class Parser(argparse.ArgumentParser):
155
+ def error(self, message):
156
+ self.print_usage(__import__("sys").stderr)
157
+ self.exit(1, self.prog + ": error: " + message + "\n")
158
+
159
+
160
+ def main(argv=None):
161
+ parser = Parser(description=__doc__)
162
+ parser.add_argument("root", nargs="?", default=".")
163
+ parser.add_argument("--json", action="store_true")
164
+ parser.add_argument("--verbose", action="store_true")
165
+ parser.add_argument("--ignore", nargs="+", action="extend", default=[])
166
+ parser.add_argument("--fail-on", choices=("HIGH", "MEDIUM"), default="HIGH")
167
+ parser.add_argument("--version", action="version", version=__version__)
168
+ args = parser.parse_args(argv)
169
+ try:
170
+ findings = audit(args.root, args.ignore)
171
+ except (OSError, UnicodeError, ValueError) as exc:
172
+ parser.error(str(exc))
173
+ failed = any(f["severity"] == "HIGH" or args.fail_on == "MEDIUM" for f in findings)
174
+ status = "FAIL" if failed else "PASS"
175
+ if args.json:
176
+ print(json.dumps({"status": status, "findings": findings}, sort_keys=True))
177
+ else:
178
+ print(status)
179
+ for f in findings:
180
+ detail = " {file}:{line} {claim} {version}".format(**f) if args.verbose else ""
181
+ print(f["rule"] + " " + f["severity"] + detail)
182
+ return 2 if failed else 0
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-version-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline audit of documented Python version promises
5
+ Author: python-version-claim-audit contributors
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # python-version-claim-audit
13
+
14
+ An offline static checker for documentation promises about interpreter versions.
15
+ Version 0.1.0 uses only the standard library at runtime. It reads root README.md,
16
+ docs/**/*.md and version metadata, without executing setup.py or writing to the
17
+ audited tree. It never reads .env files.
18
+
19
+ Install and run:
20
+
21
+ ```sh
22
+ python3 -m pip install .
23
+ python-version-claim-audit . --verbose
24
+ python3 -m python_version_claim_audit . --json
25
+ python3 -m unittest discover
26
+ python3 -m build
27
+ ```
28
+
29
+ The console and module interfaces accept an optional root (default: current
30
+ working directory), --json, --verbose, --ignore GLOB ... (repeatable), and
31
+ --fail-on HIGH|MEDIUM (default HIGH). Exit codes: 0 PASS, 2 findings meeting
32
+ the threshold, 1 usage or unsupported configuration error. --version prints
33
+ 0.1.0. JSON has status and findings; each finding includes rule, severity,
34
+ file, line, version and claim. Verbose text identifies the first false claim
35
+ in each family. Findings below the selected threshold remain visible.
36
+
37
+ ## Matching and evidence
38
+
39
+ Templates are case-sensitive. Inline code counts; backtick and tilde fenced
40
+ blocks do not. Recognized phrase forms (V, A, B denote minors from 3.8 to 3.14):
41
+
42
+ ```text
43
+ Python V or higher
44
+ Python V or later
45
+ Python V+
46
+ Python >= V
47
+ requires Python V
48
+ supports Python V
49
+ works with Python V
50
+ runs on Python V
51
+ compatible with Python V
52
+ Python V supported
53
+ Python A to B
54
+ Python A-B
55
+ Python A–B
56
+ does not support Python V
57
+ no Python V support
58
+ not compatible with Python V
59
+ Python V not supported
60
+ does not work with Python V
61
+ drops Python V
62
+ dropped Python V
63
+ ```
64
+
65
+ Ranges expand inclusively. Lower-bound phrases assert the named minor, rather
66
+ than expanding to every future minor. Evidence priority is project.requires-python
67
+ in pyproject.toml, then python_requires in setup.py or setup.cfg, then minor
68
+ classifiers when no specifier exists. Classifiers form a closed list. Comments
69
+ are ignored. A positive promise without evidence fails; a negative statement
70
+ without evidence passes. There is one finding per family, at the first false
71
+ claim. Findings under a tests/ directory are MEDIUM; others are HIGH.
72
+
73
+ ## Differentiation
74
+
75
+ Unlike platform-claim-audit, this checks interpreter minors rather than OS
76
+ promises. Unlike config-claim-audit, it compares documentation with support
77
+ metadata rather than general configuration. Unlike dependency-claim-audit,
78
+ it does not inspect installed dependencies. Unlike readme-claim-audit, its
79
+ vocabulary and evidence are confined to interpreter version declarations.
80
+
81
+ ## Limitations
82
+
83
+ Matching uses exact templates, not semantics. There is no generic negation
84
+ detection beyond the listed negative templates; arbitrary negated sentences
85
+ are outside the supported grammar. Range templates accept only the three
86
+ separators listed above. Pre-releases are not special-cased: unsupported
87
+ specifier syntax produces a usage error. The specifier parser is a subset of
88
+ PEP 440: numeric comparisons, compatible release, comma conjunction and equality
89
+ wildcards only; no environment markers or extras. It does not prove a version
90
+ actually runs; it only compares declared support with declared configuration.
91
+ .python-version and CI YAML are not support evidence; neither are lockfiles,
92
+ documentation itself, or classifiers without a minor version. Metadata is read
93
+ statically; dynamically computed setup.py values are not evaluated. The small
94
+ TOML reader handles a literal project table, quoted single-line specifiers and
95
+ literal classifier text; it is not a general TOML implementation.
96
+
97
+ Build and verification need setuptools and the build frontend available locally;
98
+ the audit itself never uses the network. Distribution artifacts belong in the
99
+ existing release queue only; this project does not upload or execute a drip job.
100
+
101
+ Licensed under MIT.
@@ -0,0 +1,8 @@
1
+ python_version_claim_audit/__init__.py,sha256=osUdAwe9BhgK8itxzeXBH0sU_zClJLwIc63luWgkpqY,8165
2
+ python_version_claim_audit/__main__.py,sha256=BHLi_-4Bx1gsZn-z6x7wECPn1YTxdc74y0deRea9FzY,45
3
+ python_version_claim_audit-0.1.0.dist-info/licenses/LICENSE,sha256=NnarpPFpop8Ywu-7bounYwI46an2OO5zdqpRJFM78Kg,1096
4
+ python_version_claim_audit-0.1.0.dist-info/METADATA,sha256=MXrJhpG_8zDAs00RmIO2r-DIJvUYPZjEkG9e3b5REsY,4103
5
+ python_version_claim_audit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ python_version_claim_audit-0.1.0.dist-info/entry_points.txt,sha256=T_xpSRtc_0QsTRqljHOsZlxrHIvHUBnwj7fgpQEZSqc,79
7
+ python_version_claim_audit-0.1.0.dist-info/top_level.txt,sha256=jNmiA5wM-Rf1mhit3IMP3_3gq9EJGW5VQsV3Z6mquBg,27
8
+ python_version_claim_audit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ python-version-claim-audit = python_version_claim_audit:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 python-version-claim-audit contributors
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.
@@ -0,0 +1 @@
1
+ python_version_claim_audit