readme-standards 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.
- readme_standards/__init__.py +6 -0
- readme_standards/artifacts.py +124 -0
- readme_standards/check.py +252 -0
- readme_standards/cli.py +105 -0
- readme_standards/config.py +174 -0
- readme_standards/document.py +89 -0
- readme_standards/policy.py +94 -0
- readme_standards/pytest_plugin.py +61 -0
- readme_standards/render.py +359 -0
- readme_standards/schema.json +86 -0
- readme_standards-0.1.0.dist-info/METADATA +319 -0
- readme_standards-0.1.0.dist-info/RECORD +16 -0
- readme_standards-0.1.0.dist-info/WHEEL +4 -0
- readme_standards-0.1.0.dist-info/entry_points.txt +5 -0
- readme_standards-0.1.0.dist-info/licenses/LICENSE +201 -0
- readme_standards-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Built-wheel checks and explicitly requested installed-example execution."""
|
|
2
|
+
|
|
3
|
+
import email.policy
|
|
4
|
+
import os
|
|
5
|
+
import subprocess
|
|
6
|
+
import tempfile
|
|
7
|
+
import venv
|
|
8
|
+
import zipfile
|
|
9
|
+
from email.parser import BytesParser
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from packaging.utils import canonicalize_name
|
|
13
|
+
|
|
14
|
+
from .check import Diagnostic
|
|
15
|
+
from .config import Package
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def check_wheel(package: Package, wheel: Path) -> list[Diagnostic]:
|
|
19
|
+
issues = []
|
|
20
|
+
|
|
21
|
+
def fail(rule: str, message: str) -> None:
|
|
22
|
+
issues.append(Diagnostic(str(wheel), 1, rule, message))
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
with zipfile.ZipFile(wheel) as archive:
|
|
26
|
+
metadata_paths = [
|
|
27
|
+
name for name in archive.namelist() if name.endswith(".dist-info/METADATA")
|
|
28
|
+
]
|
|
29
|
+
if len(metadata_paths) != 1:
|
|
30
|
+
fail("wheel.metadata", "expected exactly one distribution METADATA")
|
|
31
|
+
return issues
|
|
32
|
+
message = BytesParser(policy=email.policy.default).parsebytes(
|
|
33
|
+
archive.read(metadata_paths[0])
|
|
34
|
+
)
|
|
35
|
+
if canonicalize_name(message.get("Name", "")) != canonicalize_name(package.name):
|
|
36
|
+
fail("wheel.name", "wheel name does not match manifest")
|
|
37
|
+
if message.get("Version") != package.project["version"]:
|
|
38
|
+
fail("wheel.version", "wheel version does not match manifest")
|
|
39
|
+
if not message.get("Description-Content-Type", "").startswith("text/markdown"):
|
|
40
|
+
fail("wheel.content-type", "wheel README must declare text/markdown")
|
|
41
|
+
body = message.get_payload(decode=True).decode("utf-8")
|
|
42
|
+
if not isinstance(body, str) or body.replace("\r\n", "\n").rstrip(
|
|
43
|
+
"\n"
|
|
44
|
+
) != package.readme.read_text("utf-8").replace("\r\n", "\n").rstrip("\n"):
|
|
45
|
+
fail("wheel.readme", "wheel description differs from source README")
|
|
46
|
+
if message.get("License-Expression") != package.project["license"]:
|
|
47
|
+
fail("wheel.license", "wheel License-Expression differs from manifest")
|
|
48
|
+
license_headers = message.get_all("License-File", [])
|
|
49
|
+
prefix = metadata_paths[0].removesuffix("METADATA") + "licenses/"
|
|
50
|
+
for key in ("license_file", "notice_file"):
|
|
51
|
+
if key not in package.settings:
|
|
52
|
+
continue
|
|
53
|
+
declared = package.settings[key]
|
|
54
|
+
if declared not in license_headers:
|
|
55
|
+
fail("wheel.legal", f"{declared} is absent from License-File metadata")
|
|
56
|
+
target = prefix + declared
|
|
57
|
+
if (
|
|
58
|
+
target not in archive.namelist()
|
|
59
|
+
or archive.read(target) != package.local(declared).read_bytes()
|
|
60
|
+
):
|
|
61
|
+
fail(
|
|
62
|
+
"wheel.legal",
|
|
63
|
+
f"{declared} is missing or differs from the package's legal document",
|
|
64
|
+
)
|
|
65
|
+
except (OSError, zipfile.BadZipFile, ValueError) as error:
|
|
66
|
+
fail("wheel.invalid", str(error))
|
|
67
|
+
return issues
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def run_examples(package: Package, wheel: Path) -> None:
|
|
71
|
+
"""Install a wheel into a new venv and assert both declared stdout fixtures.
|
|
72
|
+
|
|
73
|
+
Explicit execution, not a sandbox. Only run for trusted projects/wheels.
|
|
74
|
+
Dependencies are installed normally by pip; callers control index settings.
|
|
75
|
+
"""
|
|
76
|
+
problems = check_wheel(package, wheel)
|
|
77
|
+
if problems:
|
|
78
|
+
raise ValueError("\n".join(map(str, problems)))
|
|
79
|
+
wheel = wheel.resolve()
|
|
80
|
+
for example in package.settings["examples"].values():
|
|
81
|
+
if example.get("language", "python") != "python":
|
|
82
|
+
raise ValueError("installed example runner currently supports Python examples only")
|
|
83
|
+
with tempfile.TemporaryDirectory(prefix="readme-standards-") as directory:
|
|
84
|
+
root = Path(directory)
|
|
85
|
+
environment = root / "environment"
|
|
86
|
+
venv.EnvBuilder(with_pip=True).create(environment)
|
|
87
|
+
python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
|
88
|
+
subprocess.run(
|
|
89
|
+
[str(python), "-m", "pip", "install", "--disable-pip-version-check", str(wheel)],
|
|
90
|
+
cwd=root,
|
|
91
|
+
check=True,
|
|
92
|
+
timeout=300,
|
|
93
|
+
)
|
|
94
|
+
# Run each example without source-tree imports or inherited application credentials.
|
|
95
|
+
clean_env = {
|
|
96
|
+
key: value
|
|
97
|
+
for key, value in os.environ.items()
|
|
98
|
+
if key.upper() in {"PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "HOME", "LANG"}
|
|
99
|
+
}
|
|
100
|
+
clean_env["PYTHONUTF8"] = "1"
|
|
101
|
+
for name, example in package.settings["examples"].items():
|
|
102
|
+
script = root / f"{name}.py"
|
|
103
|
+
script.write_bytes(package.local(example["source"]).read_bytes())
|
|
104
|
+
result = subprocess.run(
|
|
105
|
+
[str(python), "-I", str(script)],
|
|
106
|
+
cwd=root,
|
|
107
|
+
env=clean_env,
|
|
108
|
+
capture_output=True,
|
|
109
|
+
text=True,
|
|
110
|
+
encoding="utf-8",
|
|
111
|
+
check=True,
|
|
112
|
+
timeout=example.get("timeout", 30),
|
|
113
|
+
)
|
|
114
|
+
expected = (
|
|
115
|
+
package.local(example["expected_stdout"]).read_text("utf-8")
|
|
116
|
+
if "expected_stdout" in example
|
|
117
|
+
else None
|
|
118
|
+
)
|
|
119
|
+
if expected is not None and result.stdout.replace("\r\n", "\n") != expected.replace(
|
|
120
|
+
"\r\n", "\n"
|
|
121
|
+
):
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"{name}: stdout differs from {example['expected_stdout']}: {result.stdout!r}"
|
|
124
|
+
)
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Read-only diagnostics for heading structure, authored presence, and derived facts."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .config import ConfigurationError, Package, load_package
|
|
10
|
+
from .document import PARSER, block, parse, visible
|
|
11
|
+
from .policy import SECTIONS, outline
|
|
12
|
+
from .render import SECTION_REGIONS, fragments, region_spans
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Diagnostic:
|
|
17
|
+
path: str
|
|
18
|
+
line: int
|
|
19
|
+
rule: str
|
|
20
|
+
message: str
|
|
21
|
+
|
|
22
|
+
def __str__(self) -> str:
|
|
23
|
+
return f"{self.path}:{self.line}: {self.rule}: {self.message}"
|
|
24
|
+
|
|
25
|
+
def as_dict(self) -> dict:
|
|
26
|
+
return asdict(self)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def check_package(root: Path) -> list[Diagnostic]:
|
|
30
|
+
try:
|
|
31
|
+
package = load_package(root)
|
|
32
|
+
except ConfigurationError as error:
|
|
33
|
+
return [Diagnostic(str(root / "pyproject.toml"), 1, "config", str(error))]
|
|
34
|
+
return check(package)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def check(package: Package) -> list[Diagnostic]:
|
|
38
|
+
path = package.readme
|
|
39
|
+
issues = []
|
|
40
|
+
|
|
41
|
+
def fail(rule: str, message: str, line: int = 1) -> None:
|
|
42
|
+
issues.append(Diagnostic(str(path), line, rule, message))
|
|
43
|
+
|
|
44
|
+
if not path.is_file():
|
|
45
|
+
fail("readme.missing", "required README does not exist; run scaffold")
|
|
46
|
+
return issues
|
|
47
|
+
text = path.read_text("utf-8-sig")
|
|
48
|
+
headings, separators = parse(text)
|
|
49
|
+
if headings and "".join(text.splitlines(keepends=True)[: headings[0].line - 1]).strip():
|
|
50
|
+
fail("heading.preamble", "the package-name H1 must be the first document element")
|
|
51
|
+
expected = outline(package.name)
|
|
52
|
+
by_title = {row["title"]: row for row in expected[1:]}
|
|
53
|
+
order = {row["id"]: i for i, row in enumerate(expected)}
|
|
54
|
+
|
|
55
|
+
def row_for(heading):
|
|
56
|
+
if heading.level == 1 and heading.title == package.name:
|
|
57
|
+
return expected[0]
|
|
58
|
+
return by_title.get(heading.title)
|
|
59
|
+
|
|
60
|
+
counts = Counter(row["id"] for h in headings if (row := row_for(h)))
|
|
61
|
+
for row in expected:
|
|
62
|
+
if not counts[row["id"]]:
|
|
63
|
+
fail(
|
|
64
|
+
"heading.missing",
|
|
65
|
+
f"missing H{row['level']} {row['title']!r} under {row['parent']!r}",
|
|
66
|
+
)
|
|
67
|
+
previous = -1
|
|
68
|
+
for heading in headings:
|
|
69
|
+
row = row_for(heading)
|
|
70
|
+
if row is None:
|
|
71
|
+
fail("heading.extra", f"unexpected heading {heading.title!r}", heading.line)
|
|
72
|
+
continue
|
|
73
|
+
if counts[row["id"]] > 1:
|
|
74
|
+
fail("heading.duplicate", f"duplicate heading {heading.title!r}", heading.line)
|
|
75
|
+
if row["level"] != heading.level:
|
|
76
|
+
fail("heading.level", f"{heading.title!r} must be H{row['level']}", heading.line)
|
|
77
|
+
parent = next((e["title"] for e in expected if e["id"] == row["parent"]), None)
|
|
78
|
+
if heading.parent != parent:
|
|
79
|
+
fail("heading.parent", f"{heading.title!r} must be under {parent!r}", heading.line)
|
|
80
|
+
rank = order[row["id"]]
|
|
81
|
+
if rank < previous:
|
|
82
|
+
fail("heading.order", f"{heading.title!r} is out of policy order", heading.line)
|
|
83
|
+
previous = max(previous, rank)
|
|
84
|
+
for i, heading in enumerate(headings):
|
|
85
|
+
if heading.level != 2 or heading.title not in by_title:
|
|
86
|
+
continue
|
|
87
|
+
lower = headings[i - 1].end_line if i else 0
|
|
88
|
+
between = [line for line in separators if lower < line < heading.line]
|
|
89
|
+
if len(between) != 1:
|
|
90
|
+
fail(
|
|
91
|
+
"separator.missing",
|
|
92
|
+
f"exactly one horizontal rule required before {heading.title!r}",
|
|
93
|
+
heading.line,
|
|
94
|
+
)
|
|
95
|
+
expected_separator_count = sum(row["level"] == 2 for row in expected)
|
|
96
|
+
if len(separators) != expected_separator_count:
|
|
97
|
+
fail(
|
|
98
|
+
"separator.count",
|
|
99
|
+
f"expected {expected_separator_count} top-level horizontal rules; found {len(separators)}",
|
|
100
|
+
)
|
|
101
|
+
lines = text.splitlines()
|
|
102
|
+
for line in separators:
|
|
103
|
+
if lines[line - 1] != "---":
|
|
104
|
+
fail("separator.style", "group separator must be exactly ---", line)
|
|
105
|
+
document_tokens = PARSER.parse(text)
|
|
106
|
+
flattened_tokens = []
|
|
107
|
+
for token in document_tokens:
|
|
108
|
+
flattened_tokens.append(token)
|
|
109
|
+
flattened_tokens.extend(token.children or [])
|
|
110
|
+
for token in flattened_tokens:
|
|
111
|
+
if token.type == "heading_open" and token.level != 0:
|
|
112
|
+
fail(
|
|
113
|
+
"heading.nested",
|
|
114
|
+
"headings must not be inside lists or blockquotes",
|
|
115
|
+
token.map[0] + 1,
|
|
116
|
+
)
|
|
117
|
+
if token.type in {"html_block", "html_inline"}:
|
|
118
|
+
html_without_comments = re.sub(r"<!--.*?-->", "", token.content, flags=re.S)
|
|
119
|
+
if re.search(r"<h[1-6](?:\s|>)", html_without_comments, re.I):
|
|
120
|
+
fail(
|
|
121
|
+
"heading.html",
|
|
122
|
+
"use policy Markdown headings, not HTML headings",
|
|
123
|
+
(token.map or [0])[0] + 1,
|
|
124
|
+
)
|
|
125
|
+
try:
|
|
126
|
+
data = fragments(package)
|
|
127
|
+
spans = region_spans(text)
|
|
128
|
+
locations = {name: (start, end) for name, start, end in spans}
|
|
129
|
+
for name, value in data.items():
|
|
130
|
+
if name not in locations:
|
|
131
|
+
fail("generated.missing", f"missing managed region {name!r}; run repair")
|
|
132
|
+
continue
|
|
133
|
+
start, end = locations[name]
|
|
134
|
+
line = text.count("\n", 0, start) + 1
|
|
135
|
+
if text[start:end] != block(name, value):
|
|
136
|
+
fail(
|
|
137
|
+
"generated.stale",
|
|
138
|
+
f"region {name!r} differs from declared inputs; run render",
|
|
139
|
+
line,
|
|
140
|
+
)
|
|
141
|
+
owner = (
|
|
142
|
+
"package"
|
|
143
|
+
if name == "branding"
|
|
144
|
+
else next(key for key, region in SECTION_REGIONS.items() if region == name)
|
|
145
|
+
)
|
|
146
|
+
owner_title = next(row["title"] for row in expected if row["id"] == owner)
|
|
147
|
+
actual_heading = next((h for h in reversed(headings) if h.line <= line), None)
|
|
148
|
+
actual_row = row_for(actual_heading) if actual_heading else None
|
|
149
|
+
if actual_row is None or actual_row["id"] != owner:
|
|
150
|
+
fail("generated.location", f"region {name!r} belongs under {owner_title!r}", line)
|
|
151
|
+
for name in locations.keys() - data.keys():
|
|
152
|
+
fail("generated.unknown", f"unknown managed region {name!r}")
|
|
153
|
+
if headings and "branding" in locations:
|
|
154
|
+
start, end = locations["branding"]
|
|
155
|
+
title_end = sum(
|
|
156
|
+
len(line) for line in text.splitlines(keepends=True)[: headings[0].end_line]
|
|
157
|
+
)
|
|
158
|
+
if text[title_end:start].strip():
|
|
159
|
+
fail(
|
|
160
|
+
"branding.position",
|
|
161
|
+
"branding must appear immediately after the package-name H1",
|
|
162
|
+
)
|
|
163
|
+
if len(headings) > 1:
|
|
164
|
+
next_start = sum(
|
|
165
|
+
len(line) for line in text.splitlines(keepends=True)[: headings[1].line - 1]
|
|
166
|
+
)
|
|
167
|
+
if visible(text[end:next_start]):
|
|
168
|
+
fail(
|
|
169
|
+
"branding.preamble",
|
|
170
|
+
"put authored introduction under Overview, not before it",
|
|
171
|
+
)
|
|
172
|
+
except (ConfigurationError, OSError, ValueError) as error:
|
|
173
|
+
fail("generated.invalid", str(error))
|
|
174
|
+
authored = {s.title: s for s in SECTIONS if s.content == "authored"}
|
|
175
|
+
seen_bodies = {}
|
|
176
|
+
for heading in headings:
|
|
177
|
+
if heading.level == 1 or heading.title not in authored:
|
|
178
|
+
continue
|
|
179
|
+
body = visible(heading.body)
|
|
180
|
+
prose = " ".join(t.content for t in PARSER.parse(body) if t.type == "inline")
|
|
181
|
+
if not prose.strip():
|
|
182
|
+
fail(
|
|
183
|
+
"content.missing",
|
|
184
|
+
f"{heading.title!r} needs authored explanation or an explicit applicability statement",
|
|
185
|
+
heading.line,
|
|
186
|
+
)
|
|
187
|
+
if (
|
|
188
|
+
re.search(r"\b(?:TODO|TBD|FIXME)\b|AUTHOR REQUIRED|\{\{[^}]+\}\}", prose, re.I)
|
|
189
|
+
or "AUTHOR REQUIRED" in heading.body
|
|
190
|
+
):
|
|
191
|
+
fail(
|
|
192
|
+
"content.placeholder",
|
|
193
|
+
f"unresolved authoring placeholder in {heading.title!r}",
|
|
194
|
+
heading.line,
|
|
195
|
+
)
|
|
196
|
+
if re.fullmatch(r"(?:N/?A|none|not applicable)[.!\s]*", prose, re.I):
|
|
197
|
+
fail("content.applicability", "explain why this section does not apply", heading.line)
|
|
198
|
+
normalized = re.sub(r"\s+", " ", prose).strip().casefold()
|
|
199
|
+
if len(normalized) >= 80:
|
|
200
|
+
if normalized in seen_bodies:
|
|
201
|
+
fail(
|
|
202
|
+
"content.duplicate",
|
|
203
|
+
f"identical authored prose also appears in {seen_bodies[normalized]!r}",
|
|
204
|
+
heading.line,
|
|
205
|
+
)
|
|
206
|
+
seen_bodies[normalized] = heading.title
|
|
207
|
+
for key, example in package.settings["examples"].items():
|
|
208
|
+
for field in ("source", "expected_stdout", "test"):
|
|
209
|
+
if field not in example:
|
|
210
|
+
continue
|
|
211
|
+
try:
|
|
212
|
+
source = package.local(example[field])
|
|
213
|
+
if not source.is_file() or (
|
|
214
|
+
field != "expected_stdout" and not source.read_text("utf-8").strip()
|
|
215
|
+
):
|
|
216
|
+
fail(
|
|
217
|
+
"example.missing",
|
|
218
|
+
f"{key}.{field} must reference an existing file (source and test must be nonempty): {example[field]}",
|
|
219
|
+
)
|
|
220
|
+
except (OSError, ConfigurationError) as error:
|
|
221
|
+
fail("example.invalid", str(error))
|
|
222
|
+
if example.get("language", "python") == "python":
|
|
223
|
+
try:
|
|
224
|
+
compile(
|
|
225
|
+
package.local(example["source"]).read_text("utf-8"), example["source"], "exec"
|
|
226
|
+
)
|
|
227
|
+
except (SyntaxError, OSError, ConfigurationError) as error:
|
|
228
|
+
fail("example.syntax", f"{key}: {error}")
|
|
229
|
+
for field in ("license_file", "notice_file"):
|
|
230
|
+
if field in package.settings:
|
|
231
|
+
source = package.local(package.settings[field])
|
|
232
|
+
if not source.is_file() or not source.read_bytes().strip():
|
|
233
|
+
fail("legal.missing", f"{field} must reference a nonempty file")
|
|
234
|
+
for key, status in package.settings["statuses"].items():
|
|
235
|
+
if "evidence_file" in status:
|
|
236
|
+
try:
|
|
237
|
+
evidence = json.loads(package.local(status["evidence_file"]).read_text("utf-8"))
|
|
238
|
+
if (
|
|
239
|
+
not isinstance(evidence, dict)
|
|
240
|
+
or evidence.get("package") != package.name
|
|
241
|
+
or evidence.get("version") != package.project["version"]
|
|
242
|
+
or evidence.get("policy") != package.settings["policy"]
|
|
243
|
+
or evidence.get("status") != "passed"
|
|
244
|
+
or not evidence.get("checks")
|
|
245
|
+
):
|
|
246
|
+
fail(
|
|
247
|
+
"evidence.mismatch",
|
|
248
|
+
f"{key}: evidence must identify this package, version, policy, passing status, and checks",
|
|
249
|
+
)
|
|
250
|
+
except (OSError, ValueError, ConfigurationError) as error:
|
|
251
|
+
fail("evidence.invalid", f"{key}: {error}")
|
|
252
|
+
return issues
|
readme_standards/cli.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Explicit commands: validation never writes; mutations require --write."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .artifacts import check_wheel, run_examples
|
|
9
|
+
from .check import check_package
|
|
10
|
+
from .config import ConfigurationError, discover, load_package, schema
|
|
11
|
+
from .policy import outline
|
|
12
|
+
from .render import diff, render, repair
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(argv: list[str] | None = None) -> int:
|
|
16
|
+
parser = argparse.ArgumentParser(prog="readme-standards")
|
|
17
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
18
|
+
for name in ("check", "scaffold", "repair", "render", "examples"):
|
|
19
|
+
command = sub.add_parser(name)
|
|
20
|
+
command.add_argument("--root", type=Path, default=Path.cwd())
|
|
21
|
+
if name in {"check", "scaffold", "repair", "render"}:
|
|
22
|
+
command.add_argument("--all", action="store_true", dest="all_packages")
|
|
23
|
+
if name in {"scaffold", "repair", "render"}:
|
|
24
|
+
command.add_argument(
|
|
25
|
+
"--write", action="store_true", help="apply changes; default prints a diff"
|
|
26
|
+
)
|
|
27
|
+
if name == "check":
|
|
28
|
+
command.add_argument("--format", choices=("text", "json"), default="text")
|
|
29
|
+
if name in {"check", "examples"}:
|
|
30
|
+
command.add_argument("--wheel", type=Path, required=name == "examples")
|
|
31
|
+
sub.add_parser("schema")
|
|
32
|
+
command = sub.add_parser("outline")
|
|
33
|
+
command.add_argument("--package", default="<package name>")
|
|
34
|
+
command.add_argument("--format", choices=("markdown", "json"), default="markdown")
|
|
35
|
+
args = parser.parse_args(argv)
|
|
36
|
+
try:
|
|
37
|
+
if args.command == "schema":
|
|
38
|
+
print(json.dumps(schema(), indent=2))
|
|
39
|
+
return 0
|
|
40
|
+
if args.command == "outline":
|
|
41
|
+
rows = outline(args.package)
|
|
42
|
+
if args.format == "json":
|
|
43
|
+
print(json.dumps(rows, indent=2))
|
|
44
|
+
else:
|
|
45
|
+
print("| Level | Heading | Parent | Content |\n| --- | --- | --- | --- |")
|
|
46
|
+
for row in rows:
|
|
47
|
+
print(
|
|
48
|
+
f"| H{row['level']} | {row['title']} | {row['parent'] or 'none'} | {row['content']} |"
|
|
49
|
+
)
|
|
50
|
+
return 0
|
|
51
|
+
if args.command == "examples":
|
|
52
|
+
package = load_package(args.root)
|
|
53
|
+
issues = check_package(args.root)
|
|
54
|
+
if issues:
|
|
55
|
+
print("\n".join(map(str, issues)), file=sys.stderr)
|
|
56
|
+
return 1
|
|
57
|
+
run_examples(package, args.wheel)
|
|
58
|
+
print("Both declared examples passed against the installed wheel.")
|
|
59
|
+
return 0
|
|
60
|
+
if args.command == "check" and args.wheel and args.all_packages:
|
|
61
|
+
raise ConfigurationError("--wheel checks one package; do not combine it with --all")
|
|
62
|
+
roots = discover(args.root, args.all_packages)
|
|
63
|
+
issues = []
|
|
64
|
+
for root in roots:
|
|
65
|
+
if args.command in {"scaffold", "repair", "render"}:
|
|
66
|
+
package = load_package(root)
|
|
67
|
+
before = package.readme.read_text("utf-8") if package.readme.exists() else ""
|
|
68
|
+
if args.command == "scaffold" and before:
|
|
69
|
+
raise ConfigurationError(f"{package.readme} already exists; use repair")
|
|
70
|
+
after = (
|
|
71
|
+
render(before, package) if args.command == "render" else repair(before, package)
|
|
72
|
+
)
|
|
73
|
+
print(diff(before, after, str(package.readme)), end="")
|
|
74
|
+
if args.write and after != before:
|
|
75
|
+
package.readme.parent.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
package.readme.write_text(after, encoding="utf-8", newline="\n")
|
|
77
|
+
# Preview must not pretend the on-disk document has been changed.
|
|
78
|
+
if not args.write:
|
|
79
|
+
continue
|
|
80
|
+
issues.extend(check_package(root))
|
|
81
|
+
if args.command == "check" and args.wheel:
|
|
82
|
+
issues.extend(check_wheel(load_package(args.root), args.wheel))
|
|
83
|
+
if args.command == "check" and args.format == "json":
|
|
84
|
+
print(
|
|
85
|
+
json.dumps(
|
|
86
|
+
{
|
|
87
|
+
"packages": len(roots),
|
|
88
|
+
"passed": not issues,
|
|
89
|
+
"diagnostics": [issue.as_dict() for issue in issues],
|
|
90
|
+
},
|
|
91
|
+
indent=2,
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
elif issues:
|
|
95
|
+
print("\n".join(map(str, issues)), file=sys.stderr)
|
|
96
|
+
elif args.command == "check":
|
|
97
|
+
print(f"README standards passed for {len(roots)} package(s).")
|
|
98
|
+
return 1 if issues else 0
|
|
99
|
+
except (ConfigurationError, OSError, ValueError) as error:
|
|
100
|
+
print(f"readme-standards: {error}", file=sys.stderr)
|
|
101
|
+
return 2
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
if __name__ == "__main__":
|
|
105
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Validated TOML inputs; no imports of the package being documented."""
|
|
2
|
+
|
|
3
|
+
import fnmatch
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import tomllib
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from importlib.resources import files
|
|
10
|
+
from pathlib import Path, PurePosixPath
|
|
11
|
+
from urllib.parse import unquote, urlsplit
|
|
12
|
+
|
|
13
|
+
from jsonschema import Draft202012Validator, FormatChecker
|
|
14
|
+
from packaging.utils import canonicalize_name
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ConfigurationError(ValueError):
|
|
18
|
+
"""A package cannot be audited until its configuration is corrected."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def schema() -> dict:
|
|
22
|
+
return json.loads(files("readme_standards").joinpath("schema.json").read_text("utf-8"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Package:
|
|
27
|
+
root: Path
|
|
28
|
+
project: dict
|
|
29
|
+
settings: dict
|
|
30
|
+
brand: dict
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def name(self) -> str:
|
|
34
|
+
return self.project["name"]
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def readme(self) -> Path:
|
|
38
|
+
return self.local(self.settings.get("readme", "README.md"))
|
|
39
|
+
|
|
40
|
+
def local(self, value: str) -> Path:
|
|
41
|
+
path = (self.root / value).resolve()
|
|
42
|
+
if not path.is_relative_to(self.root):
|
|
43
|
+
raise ConfigurationError(f"package-local path escapes package directory: {value}")
|
|
44
|
+
return path
|
|
45
|
+
|
|
46
|
+
def source_url(self, path: str, tree: bool = False) -> str:
|
|
47
|
+
from urllib.parse import quote
|
|
48
|
+
|
|
49
|
+
prefix = self.settings["package_path"].strip("/")
|
|
50
|
+
suffix = "/".join(p for p in (prefix, path) if p and p != ".")
|
|
51
|
+
return (
|
|
52
|
+
f"{self.settings['repository']}/{'tree' if tree else 'blob'}/"
|
|
53
|
+
f"{quote(self.settings['ref'], safe='')}/{quote(suffix, safe='/')}"
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def load_package(root: Path) -> Package:
|
|
58
|
+
root = root.resolve()
|
|
59
|
+
try:
|
|
60
|
+
data = tomllib.loads((root / "pyproject.toml").read_text("utf-8-sig"))
|
|
61
|
+
project = data.get("project", {})
|
|
62
|
+
settings = data.get("tool", {}).get("readme_standards")
|
|
63
|
+
if not settings:
|
|
64
|
+
raise ConfigurationError("missing [tool.readme_standards]")
|
|
65
|
+
errors = sorted(
|
|
66
|
+
Draft202012Validator(schema(), format_checker=FormatChecker()).iter_errors(settings),
|
|
67
|
+
key=lambda error: str(list(error.path)),
|
|
68
|
+
)
|
|
69
|
+
if errors:
|
|
70
|
+
raise ConfigurationError(
|
|
71
|
+
"; ".join(
|
|
72
|
+
f"{'.'.join(map(str, e.path)) or 'configuration'}: {e.message}" for e in errors
|
|
73
|
+
)
|
|
74
|
+
)
|
|
75
|
+
if not isinstance(project.get("name"), str) or not project["name"]:
|
|
76
|
+
raise ConfigurationError("[project].name is required")
|
|
77
|
+
for key in ("description", "requires-python"):
|
|
78
|
+
if not isinstance(project.get(key), str) or not project[key].strip():
|
|
79
|
+
raise ConfigurationError(f"[project].{key} must be a nonempty string")
|
|
80
|
+
if not isinstance(project.get("version"), str):
|
|
81
|
+
raise ConfigurationError(
|
|
82
|
+
"[project].version must be explicit; dynamic versions need an adapter"
|
|
83
|
+
)
|
|
84
|
+
license_value = project.get("license")
|
|
85
|
+
if not isinstance(license_value, str) or not license_value.strip():
|
|
86
|
+
raise ConfigurationError("[project].license must be an SPDX expression string")
|
|
87
|
+
readme = settings.get("readme", "README.md")
|
|
88
|
+
declared_readme = project.get("readme")
|
|
89
|
+
if isinstance(declared_readme, dict):
|
|
90
|
+
declared_readme = declared_readme.get("file")
|
|
91
|
+
if declared_readme != readme:
|
|
92
|
+
raise ConfigurationError("[project].readme must reference the configured README file")
|
|
93
|
+
if (
|
|
94
|
+
PurePosixPath(settings["package_path"]).is_absolute()
|
|
95
|
+
or ".." in PurePosixPath(settings["package_path"]).parts
|
|
96
|
+
):
|
|
97
|
+
raise ConfigurationError("package_path must be repository-relative without '..'")
|
|
98
|
+
pypi = settings["distributions"].get("pypi")
|
|
99
|
+
if pypi and canonicalize_name(pypi["name"]) != canonicalize_name(project["name"]):
|
|
100
|
+
raise ConfigurationError("PyPI badge identity must match [project].name")
|
|
101
|
+
for distribution in settings["distributions"].values():
|
|
102
|
+
for key in ("downloads_url", "downloads_image"):
|
|
103
|
+
if key in distribution:
|
|
104
|
+
target = unquote(distribution[key]).removesuffix(".svg").removesuffix(".json")
|
|
105
|
+
identity = re.escape(distribution["name"])
|
|
106
|
+
if not re.search(r"(?<![\w.@-])" + identity + r"(?![\w.@-])", target, re.I):
|
|
107
|
+
raise ConfigurationError(f"{key} must identify this exact distribution")
|
|
108
|
+
for status in settings["statuses"].values():
|
|
109
|
+
label = status["label"].casefold()
|
|
110
|
+
if (
|
|
111
|
+
label not in {"not certified", "not applicable"}
|
|
112
|
+
and re.search(r"\b(?:verified|certified|pass(?:ed|ing)?)\b", label)
|
|
113
|
+
and "evidence_file" not in status
|
|
114
|
+
):
|
|
115
|
+
raise ConfigurationError("positive status labels require an evidence_file")
|
|
116
|
+
catalog = root / settings["brand_catalog"]
|
|
117
|
+
# Catalogs may be shared above a package directory; local examples may not.
|
|
118
|
+
brands = tomllib.loads(catalog.read_text("utf-8-sig"))["brands"]
|
|
119
|
+
brand = brands[settings["brand"]]
|
|
120
|
+
if set(brand) != {"name", "homepage", "logo_url", "logo_alt"}:
|
|
121
|
+
raise ConfigurationError("brand requires exactly name, homepage, logo_url, logo_alt")
|
|
122
|
+
for key in ("homepage", "logo_url"):
|
|
123
|
+
if urlsplit(brand[key]).scheme != "https" or not urlsplit(brand[key]).netloc:
|
|
124
|
+
raise ConfigurationError(f"brand {key} must be an absolute HTTPS URL")
|
|
125
|
+
if not all(isinstance(v, str) and v.strip() for v in brand.values()):
|
|
126
|
+
raise ConfigurationError("brand fields must be nonempty strings")
|
|
127
|
+
package = Package(root, project, settings, brand)
|
|
128
|
+
package.readme # Validate containment, including symlinks.
|
|
129
|
+
for key in ("license_file", "notice_file"):
|
|
130
|
+
if key in settings:
|
|
131
|
+
package.local(settings[key])
|
|
132
|
+
return package
|
|
133
|
+
except ConfigurationError:
|
|
134
|
+
raise
|
|
135
|
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
136
|
+
raise ConfigurationError(str(error)) from error
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def discover(root: Path, all_packages: bool = False) -> list[Path]:
|
|
140
|
+
"""Discover manifests even when they omit this plugin's declaration."""
|
|
141
|
+
root = root.resolve()
|
|
142
|
+
if not all_packages:
|
|
143
|
+
return [root]
|
|
144
|
+
exclusions = []
|
|
145
|
+
manifest = root / "pyproject.toml"
|
|
146
|
+
if manifest.exists():
|
|
147
|
+
try:
|
|
148
|
+
exclusions = (
|
|
149
|
+
tomllib.loads(manifest.read_text("utf-8-sig"))
|
|
150
|
+
.get("tool", {})
|
|
151
|
+
.get("readme_standards", {})
|
|
152
|
+
.get("exclude", [])
|
|
153
|
+
)
|
|
154
|
+
except (OSError, ValueError) as error:
|
|
155
|
+
raise ConfigurationError(f"cannot read inventory settings: {error}") from error
|
|
156
|
+
found = []
|
|
157
|
+
ignored = {".git", ".venv", "venv", "node_modules", "dist", "build", "__pycache__"}
|
|
158
|
+
for current, dirs, names in os.walk(root, followlinks=False):
|
|
159
|
+
dirs[:] = sorted(d for d in dirs if d not in ignored and not d.startswith("."))
|
|
160
|
+
path = Path(current)
|
|
161
|
+
relative = path.relative_to(root).as_posix()
|
|
162
|
+
if any(fnmatch.fnmatchcase(relative, pattern) for pattern in exclusions):
|
|
163
|
+
dirs[:] = []
|
|
164
|
+
continue
|
|
165
|
+
if "pyproject.toml" in names:
|
|
166
|
+
try:
|
|
167
|
+
data = tomllib.loads((path / "pyproject.toml").read_text("utf-8-sig"))
|
|
168
|
+
except (OSError, ValueError) as error:
|
|
169
|
+
raise ConfigurationError(f"invalid manifest {path}: {error}") from error
|
|
170
|
+
if "project" in data:
|
|
171
|
+
found.append(path)
|
|
172
|
+
if not found:
|
|
173
|
+
raise ConfigurationError("inventory contains no [project] package manifests")
|
|
174
|
+
return found
|