nopt 0.1.0.dev0__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.
nopt/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Nicks Opinionated (Python Package) Publishing Tool."""
nopt/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Enable python -m nopt."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
nopt/bundle.py ADDED
@@ -0,0 +1,297 @@
1
+ """Build and verify immutable release bundles using archive metadata and hashes."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import asdict, fields
5
+ from email.parser import BytesParser
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tarfile
14
+ import tempfile
15
+ import zipfile
16
+ from typing import TypedDict, cast
17
+
18
+ from packaging.utils import canonicalize_name, parse_sdist_filename, parse_wheel_filename
19
+
20
+ from .config import Config, load
21
+ from .source import Context, ContextData, SourceIdentity
22
+ from .project import rename_distribution
23
+
24
+ _SCHEMA_VERSION = 1
25
+
26
+
27
+ class ReleaseManifest(TypedDict):
28
+ """Verified metadata binding release identity, source and original release bundle files."""
29
+
30
+ schema_version: int
31
+ source: SourceIdentity
32
+ distribution_name: str
33
+ context: ContextData
34
+ files: dict[str, str]
35
+
36
+
37
+ def sha256(path: Path) -> str:
38
+ """Return the digest of original bytes."""
39
+ with path.open("rb") as stream:
40
+ return hashlib.file_digest(stream, "sha256").hexdigest()
41
+
42
+
43
+ def validate_artifacts(
44
+ directory: Path, name: str, version: str
45
+ ) -> dict[str, str]: # pylint: disable=too-many-locals
46
+ """Validate exact wheel/sdist identity and metadata.
47
+
48
+ Returns:
49
+ A mapping from artifact filenames to their SHA256 sums.
50
+ """
51
+ files = sorted(directory.iterdir())
52
+ wheels = [p for p in files if p.name.endswith(".whl")]
53
+ sdists = [p for p in files if p.name.endswith(".tar.gz")]
54
+ if len(files) != 2 or len(wheels) != 1 or len(sdists) != 1:
55
+ raise ValueError("expected exactly one wheel and one .tar.gz sdist")
56
+ for path in files:
57
+ if path.is_symlink() or not path.is_file():
58
+ raise ValueError("distribution must be a regular file")
59
+ if path in wheels:
60
+ dist, parsed, _, _ = parse_wheel_filename(path.name)
61
+ with zipfile.ZipFile(path) as archive:
62
+ members = [n for n in archive.namelist() if n.endswith(".dist-info/METADATA")]
63
+ if len(members) != 1:
64
+ raise ValueError("expected one wheel METADATA")
65
+ metadata = BytesParser().parsebytes(archive.read(members[0]))
66
+ else:
67
+ dist, parsed = parse_sdist_filename(path.name)
68
+ with tarfile.open(path) as archive:
69
+ members = [
70
+ m
71
+ for m in archive.getmembers()
72
+ if len(Path(m.name).parts) == 2 and m.name.endswith("/PKG-INFO")
73
+ ]
74
+ if len(members) != 1 or not members[0].isfile():
75
+ raise ValueError("expected one top-level sdist PKG-INFO")
76
+ stream = archive.extractfile(members[0])
77
+ if stream is None:
78
+ raise ValueError("missing PKG-INFO")
79
+ metadata = BytesParser().parsebytes(stream.read())
80
+ # Catch backend output for a different project/version (for example, stale
81
+ # backend version configuration or a backend that ignores the temporary name).
82
+ if canonicalize_name(name) != dist or str(parsed) != version:
83
+ raise ValueError("distribution filename disagrees with release identity")
84
+ if (
85
+ canonicalize_name(metadata.get("Name", "")) != canonicalize_name(name)
86
+ or metadata.get("Version") != version
87
+ ):
88
+ raise ValueError("distribution metadata disagrees with release identity")
89
+ return {path.name: sha256(path) for path in sorted(files)}
90
+
91
+
92
+ def validate_build_output_path(project_path: Path, release_bundle_path: Path) -> None:
93
+ """Validate build output location without creating it."""
94
+ release_bundle_path = release_bundle_path.resolve()
95
+ if release_bundle_path.exists():
96
+ raise ValueError("release bundle output already exists; choose a new output path")
97
+ if release_bundle_path.is_relative_to(project_path):
98
+ # Avoid making our own future output an untracked source input.
99
+ ignored = subprocess.run(
100
+ ["git", "check-ignore", "-q", str(release_bundle_path)], cwd=project_path, check=False
101
+ )
102
+ if ignored.returncode != 0:
103
+ raise ValueError("release bundle output inside checkout must be Git-ignored")
104
+ return
105
+
106
+
107
+ # pylint: disable-next=too-many-locals,too-many-arguments,too-many-positional-arguments
108
+ def build_release_bundle(
109
+ project_path: Path,
110
+ release_bundle_path: Path,
111
+ config: Config,
112
+ context: Context,
113
+ source: SourceIdentity,
114
+ release_notes: str | None,
115
+ ) -> ReleaseManifest:
116
+ """Build a release bundle; the caller must first check source eligibility."""
117
+ ### The caller checks eligibility; this function builds and packages its inputs.
118
+ release_bundle_path = release_bundle_path.resolve()
119
+ validate_build_output_path(project_path, release_bundle_path)
120
+ with tempfile.TemporaryDirectory() as temporary:
121
+ release_bundle = Path(temporary) / "release_bundle"
122
+ project_file = project_path / "pyproject.toml"
123
+ original_pyproject_bytes = project_file.read_bytes()
124
+ requires_testpypi_rename = (
125
+ config.repository == "testpypi" and config.distribution_name != config.name
126
+ )
127
+ distributions = release_bundle / "dist"
128
+ try:
129
+ if requires_testpypi_rename:
130
+ # Change only build-time distribution identity, restoring the source below.
131
+ rename_distribution(project_file, config.distribution_name)
132
+ subprocess.run(
133
+ [
134
+ sys.executable,
135
+ "-m",
136
+ "build",
137
+ "--installer=uv",
138
+ "--outdir",
139
+ str(distributions),
140
+ str(project_path),
141
+ ],
142
+ check=True,
143
+ )
144
+ finally:
145
+ # Restore original comments, formatting and pre-existing uncommitted edits.
146
+ if requires_testpypi_rename:
147
+ project_file.write_bytes(original_pyproject_bytes)
148
+ ### Validate artifacts and bind them to the original project configuration.
149
+ hashes = {
150
+ "dist/" + name: digest
151
+ for name, digest in validate_artifacts(
152
+ distributions, config.distribution_name, config.version
153
+ ).items()
154
+ }
155
+ # Preserve original configuration, not the temporary TestPyPI build name.
156
+ # Publishing derives the same effective name without rebuilding distributions.
157
+ (release_bundle / "pyproject.toml").write_bytes(original_pyproject_bytes)
158
+ hashes["pyproject.toml"] = sha256(release_bundle / "pyproject.toml")
159
+ if release_notes is not None:
160
+ (release_bundle / "release-notes.md").write_text(release_notes, encoding="utf-8")
161
+ hashes["release-notes.md"] = sha256(release_bundle / "release-notes.md")
162
+ manifest: ReleaseManifest = {
163
+ "schema_version": _SCHEMA_VERSION,
164
+ "source": source,
165
+ "distribution_name": config.distribution_name,
166
+ "context": cast(ContextData, asdict(context)),
167
+ "files": hashes,
168
+ }
169
+ (release_bundle / "release.json").write_text(
170
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
171
+ )
172
+ ### Preserve checksum text and original bytes in the final local release bundle.
173
+ checksums = dict(manifest["files"])
174
+ checksums["release.json"] = sha256(release_bundle / "release.json")
175
+ (release_bundle / "SHA256SUMS").write_text(
176
+ "".join(f"{digest} {name}\n" for name, digest in sorted(checksums.items())),
177
+ encoding="utf-8",
178
+ )
179
+ release_bundle_path.parent.mkdir(parents=True, exist_ok=True)
180
+ shutil.copytree(release_bundle, release_bundle_path)
181
+ return manifest
182
+
183
+
184
+ # pylint: disable-next=too-many-branches,too-many-locals,too-many-statements
185
+ def read_and_verify_release_bundle(
186
+ release_bundle: Path, overrides: Mapping[str, object] | None = None
187
+ ) -> tuple[ReleaseManifest, Config]:
188
+ """Verify every byte and narrow decoded release metadata before using it."""
189
+ ### Verify checksums and reject paths outside the original release bundle.
190
+ release_bundle = release_bundle.resolve()
191
+ if (release_bundle / "SHA256SUMS").is_symlink():
192
+ raise ValueError("SHA256SUMS must be a regular file")
193
+ checksums: dict[str, str] = {}
194
+ for line in (release_bundle / "SHA256SUMS").read_text(encoding="utf-8").splitlines():
195
+ match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line)
196
+ if not match:
197
+ raise ValueError("invalid SHA256SUMS")
198
+ digest, name = match.groups()
199
+ if name in checksums or name.startswith("/") or "\\" in name or ".." in Path(name).parts:
200
+ raise ValueError("unsafe or duplicate release bundle path")
201
+ path = release_bundle / name
202
+ if (
203
+ not path.resolve().is_relative_to(release_bundle)
204
+ or path.is_symlink()
205
+ or not path.is_file()
206
+ ):
207
+ raise ValueError("release bundle entry must be a regular file inside release bundle")
208
+ if sha256(path) != digest:
209
+ raise ValueError(f"release bundle checksum mismatch: {name}")
210
+ checksums[name] = digest
211
+ actual = {
212
+ path.relative_to(release_bundle).as_posix()
213
+ for path in release_bundle.rglob("*")
214
+ if path.is_file() or path.is_symlink()
215
+ }
216
+ # The loop checks listed files; this inventory also detects unlisted additions,
217
+ # such as an extra wheel or temporary file copied into a downloaded artifact.
218
+ unexpected_files = actual - (set(checksums) | {"SHA256SUMS"})
219
+ missing_files = (set(checksums) | {"SHA256SUMS"}) - actual
220
+ if unexpected_files or missing_files:
221
+ raise ValueError(
222
+ "release bundle file set disagrees with SHA256SUMS: "
223
+ f"unexpected={sorted(unexpected_files)}, missing={sorted(missing_files)}"
224
+ )
225
+ if "release.json" not in checksums:
226
+ raise ValueError("release.json must be listed in SHA256SUMS")
227
+
228
+ ### Narrow untrusted JSON to the schema's configuration and identity fields.
229
+ decoded: object = json.loads((release_bundle / "release.json").read_text(encoding="utf-8"))
230
+ if not isinstance(decoded, dict):
231
+ raise ValueError("release manifest must be an object")
232
+ manifest_data = cast(dict[str, object], decoded)
233
+ schema = manifest_data.get("schema_version")
234
+ if not isinstance(schema, int) or isinstance(schema, bool) or schema != _SCHEMA_VERSION:
235
+ raise ValueError("unsupported release manifest schema")
236
+ expected_files = {name: digest for name, digest in checksums.items() if name != "release.json"}
237
+ if manifest_data.get("files") != expected_files:
238
+ raise ValueError("release manifest disagrees with checksums")
239
+ # Re-read project policy from the bundled TOML for this invocation only.
240
+ config = load(release_bundle, overrides)
241
+ distribution_name = manifest_data.get("distribution_name")
242
+ if not isinstance(distribution_name, str) or distribution_name != config.distribution_name:
243
+ raise ValueError(
244
+ "release bundle distribution name disagrees with this invocation configuration"
245
+ )
246
+
247
+ # Validate recorded source identity without repeating checkout eligibility checks.
248
+ source_data = manifest_data.get("source")
249
+ if not isinstance(source_data, dict):
250
+ raise ValueError("release source identity must be an object")
251
+ commit = source_data.get("commit")
252
+ tag = source_data.get("tag")
253
+ dirty = source_data.get("dirty")
254
+ if not isinstance(commit, str) or not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", commit):
255
+ raise ValueError("invalid release source commit")
256
+ if not isinstance(tag, str) or tag != "v" + config.version or not isinstance(dirty, bool):
257
+ raise ValueError("invalid release tag or dirty status")
258
+
259
+ # Execution identity is checked separately against the current publishing job.
260
+ context_data = manifest_data.get("context")
261
+ if not isinstance(context_data, dict) or set(context_data) != {
262
+ field.name for field in fields(Context)
263
+ }:
264
+ raise ValueError("invalid release execution context")
265
+ if not isinstance(context_data.get("local"), bool) or any(
266
+ value is not None and not isinstance(value, str)
267
+ for key, value in context_data.items()
268
+ if key != "local"
269
+ ):
270
+ raise ValueError("invalid release execution context values")
271
+
272
+ ### Trust build-time metadata checks; verify only the checked release bundle layout here.
273
+ artifact_files = {name for name in expected_files if name.startswith("dist/")}
274
+ if (
275
+ len(artifact_files) != 2
276
+ or sum(name.endswith(".whl") for name in artifact_files) != 1
277
+ or sum(name.endswith(".tar.gz") for name in artifact_files) != 1
278
+ or any(Path(name).parent.as_posix() != "dist" for name in artifact_files)
279
+ ):
280
+ raise ValueError("release bundle must contain exactly one wheel and one sdist under dist/")
281
+ if config.github_release_requested and "release-notes.md" not in expected_files:
282
+ raise ValueError("GitHub release publication requires bundled release-notes.md")
283
+ allowed_files = artifact_files | {"pyproject.toml"}
284
+ if "release-notes.md" in expected_files:
285
+ allowed_files.add("release-notes.md")
286
+ if unexpected_files := set(expected_files) - allowed_files:
287
+ raise ValueError(f"unexpected release bundle members: {sorted(unexpected_files)}")
288
+ if missing_files := allowed_files - set(expected_files):
289
+ raise ValueError(f"missing release bundle members: {sorted(missing_files)}")
290
+ manifest: ReleaseManifest = {
291
+ "schema_version": schema,
292
+ "source": {"commit": commit, "tag": tag, "dirty": dirty},
293
+ "distribution_name": distribution_name,
294
+ "context": cast(ContextData, context_data),
295
+ "files": expected_files,
296
+ }
297
+ return manifest, config
nopt/changelog.py ADDED
@@ -0,0 +1,37 @@
1
+ """Extract the full base-version changelog section without modifying it."""
2
+
3
+ from datetime import date
4
+ from pathlib import Path
5
+ import re
6
+
7
+ from packaging.version import Version
8
+
9
+ from .config import Config
10
+
11
+
12
+ def release_notes(root: Path, config: Config) -> str | None:
13
+ """Validate section count, content and the approved date policy."""
14
+ if config.changelog is False:
15
+ return None
16
+ path = (root / str(config.changelog)).resolve()
17
+ if not path.is_relative_to(root):
18
+ raise ValueError("changelog path must be inside the project")
19
+ text = path.read_text(encoding="utf-8")
20
+ base = Version(config.version).base_version
21
+ sections = re.split(r"(?m)(?=^## )", text)
22
+ matches = [
23
+ section for section in sections if re.match(rf"^## \[{re.escape(base)}\](?:\(|\s)", section)
24
+ ]
25
+ if len(matches) != 1:
26
+ raise ValueError(f"expected exactly one changelog section for {base}")
27
+ heading, _, content = matches[0].partition("\n")
28
+ stamp = heading.rsplit(" - ", 1)[-1]
29
+ if config.release_type == "final":
30
+ if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", stamp):
31
+ raise ValueError("final releases require a YYYY-MM-DD changelog date")
32
+ date.fromisoformat(stamp)
33
+ elif stamp != "UNRELEASED":
34
+ raise ValueError("dev/pre releases require an UNRELEASED changelog section")
35
+ if not any(line.strip() and not line.startswith("#") for line in content.splitlines()):
36
+ raise ValueError("changelog section requires nonempty content")
37
+ return matches[0].rstrip() + "\n"
nopt/cli.py ADDED
@@ -0,0 +1,327 @@
1
+ """Public command line; checks always precede nopt-owned actions."""
2
+
3
+ import argparse
4
+ from collections.abc import Mapping
5
+ from importlib.resources import files
6
+ from importlib.metadata import version
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+
12
+ from .bundle import (
13
+ ReleaseManifest,
14
+ build_release_bundle,
15
+ read_and_verify_release_bundle,
16
+ validate_build_output_path,
17
+ )
18
+ from .changelog import release_notes as extract_release_notes
19
+ from .config import Config, load
20
+ from .remote import GitHubClient, PyPIClient
21
+ from .source import Context, SourceIdentity, git, identity
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ """Build the agreed small CLI without speculative skip/force flags."""
26
+ parser = argparse.ArgumentParser(
27
+ prog="nopt",
28
+ formatter_class=argparse.RawDescriptionHelpFormatter,
29
+ description="Nicks Opinionated (Python Package) Publishing Tool: "
30
+ "check, build and publish releases.",
31
+ epilog="Copyright (c) 2026 Nicholas Hairs.\n"
32
+ "https://github.com/nhairs/nicks-opinionated-python-package-publishing-tool",
33
+ )
34
+ parser.add_argument("--version", action="version", version=f"%(prog)s {version('nopt')}")
35
+ commands = parser.add_subparsers(dest="command", required=True)
36
+ ### Release workflow commands share policy overrides and explicit execution mode.
37
+ for name, help_text in (
38
+ ("ci-preflight", "Check source release eligibility before user CI"),
39
+ ("build", "Check eligibility, build distributions and prepare a local release bundle"),
40
+ (
41
+ "publish-release-preflight",
42
+ "Verify the original bundle and recheck eligibility before external upload",
43
+ ),
44
+ ("publish-github-release", "Verify PyPI files and publish a GitHub release"),
45
+ ):
46
+ command = commands.add_parser(name, help=help_text)
47
+ command.add_argument(
48
+ "--project",
49
+ type=Path,
50
+ default=Path.cwd(),
51
+ help="project checkout (default: current directory)",
52
+ )
53
+ if name != "publish-github-release":
54
+ command.add_argument(
55
+ "--local", action="store_true", help="use local refs/inputs rather than GHA context"
56
+ )
57
+ if name != "publish-github-release":
58
+ command.add_argument(
59
+ "--tag", help="local-only existing tag pointing to HEAD; inferred from version"
60
+ )
61
+ if name in {"build", "publish-github-release"}:
62
+ command.add_argument(
63
+ "--check-only",
64
+ action="store_true",
65
+ help="perform checks without building or publishing",
66
+ )
67
+ if name == "build":
68
+ command.add_argument(
69
+ "--output",
70
+ type=Path,
71
+ default=Path("release-bundle"),
72
+ help="new bundle directory; must be ignored if inside checkout",
73
+ )
74
+ if name in {"publish-release-preflight", "publish-github-release"}:
75
+ command.add_argument(
76
+ "--bundle",
77
+ dest="release_bundle",
78
+ type=Path,
79
+ required=True,
80
+ help="original downloaded release bundle",
81
+ )
82
+ command.add_argument("--repository", choices=("pypi", "testpypi"), default=None)
83
+ command.add_argument("--testpypi-username")
84
+ command.add_argument("--changelog")
85
+ command.add_argument("--no-changelog", action="store_const", const=False, dest="changelog")
86
+ command.add_argument(
87
+ "--allow-dirty", nargs="*", choices=("dev", "pre", "final"), default=None
88
+ )
89
+ for group in ("final", "pre", "dev"):
90
+ command.add_argument(f"--{group}-release-branches", nargs="+", default=None)
91
+ command.add_argument(
92
+ "--no-pre-release-branches",
93
+ action="store_const",
94
+ const=False,
95
+ dest="pre_release_branches",
96
+ )
97
+ command.add_argument(
98
+ "--no-dev-release-branches",
99
+ action="store_const",
100
+ const=False,
101
+ dest="dev_release_branches",
102
+ )
103
+ toggle = command.add_mutually_exclusive_group()
104
+ toggle.add_argument("--github-release-publish", action="store_true", default=None)
105
+ toggle.add_argument(
106
+ "--no-github-release-publish", action="store_false", dest="github_release_publish"
107
+ )
108
+ command.add_argument(
109
+ "--github-release-types", nargs="*", choices=("dev", "pre", "final"), default=None
110
+ )
111
+ ### Template generation does not require workflow context.
112
+ template = commands.add_parser(
113
+ "workflow-template", help="Print or write an editable GHA release workflow"
114
+ )
115
+ template.add_argument("--output", type=Path, help="new file; never overwrite an existing file")
116
+ return parser
117
+
118
+
119
+ def build_context(args: argparse.Namespace) -> Context:
120
+ """Require GHA identity unless the caller explicitly selects local mode."""
121
+ if getattr(args, "local", False):
122
+ return Context(True, args.tag)
123
+ if os.environ.get("GITHUB_ACTIONS") != "true":
124
+ raise ValueError("outside GHA use --local; local GitHub publishing is not supported")
125
+ repository = os.environ.get("GITHUB_REPOSITORY", "")
126
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
127
+ raise ValueError("GITHUB_REPOSITORY must be owner/repository")
128
+ ref = os.environ.get("GITHUB_REF", "")
129
+ if not ref.startswith("refs/tags/"):
130
+ raise ValueError("release workflow must run from an existing tag")
131
+ tag = ref.removeprefix("refs/tags/")
132
+ if getattr(args, "tag", None) is not None:
133
+ raise ValueError("--tag is local-only; GHA reads GITHUB_REF")
134
+ run_id, attempt = os.environ.get("GITHUB_RUN_ID", ""), os.environ.get("GITHUB_RUN_ATTEMPT", "")
135
+ if not run_id.isdigit() or not attempt.isdigit():
136
+ raise ValueError("GHA run identity is required")
137
+ return Context(False, tag, repository, run_id, attempt)
138
+
139
+
140
+ def get_cli_config_overrides(args: argparse.Namespace) -> dict[str, object]:
141
+ """Only explicitly supplied options override TOML."""
142
+ keys = (
143
+ "repository",
144
+ "testpypi_username",
145
+ "changelog",
146
+ "allow_dirty",
147
+ "final_release_branches",
148
+ "pre_release_branches",
149
+ "dev_release_branches",
150
+ "github_release_publish",
151
+ "github_release_types",
152
+ )
153
+ return {key: value for key in keys if (value := getattr(args, key, None)) is not None}
154
+
155
+
156
+ def check_source(
157
+ root: Path, config: Config, execution: Context, index: PyPIClient, github: GitHubClient
158
+ ) -> tuple[SourceIdentity, str | None]:
159
+ """Refuse an existing index version before tag/GitHub diagnostics."""
160
+ index.absent(config.repository, config.distribution_name, config.version)
161
+ source = identity(root, config, execution)
162
+ release_notes = extract_release_notes(root, config)
163
+ if not execution.local:
164
+ if os.environ.get("GITHUB_SHA") != source["commit"]:
165
+ raise ValueError("HEAD disagrees with GITHUB_SHA")
166
+ github.check_tag(source["tag"], source["commit"])
167
+ if config.github_release_requested:
168
+ github.release_absent(source["tag"])
169
+ return source, release_notes
170
+
171
+
172
+ def check_bundle_context(data: Mapping[str, object], execution: Context) -> None:
173
+ """Bind downloaded bytes to this exact workflow run, including reruns."""
174
+ original = data.get("context")
175
+ if not isinstance(original, dict):
176
+ raise ValueError("bundle context must be an object")
177
+ if execution.local:
178
+ return
179
+ for key in ("github_repository", "run_id", "run_attempt"):
180
+ if original.get(key) != getattr(execution, key):
181
+ raise ValueError(f"bundle belongs to a different workflow {key}")
182
+ if original.get("local") is not False:
183
+ raise ValueError("local build bundles cannot be published by the GHA workflow")
184
+ return
185
+
186
+
187
+ def check_publish_bundle(
188
+ release_bundle: Path,
189
+ execution: Context,
190
+ commit: str,
191
+ policy: Mapping[str, object] | None = None,
192
+ ) -> tuple[ReleaseManifest, Config]:
193
+ """Verify the checked build handoff against independently supplied identity."""
194
+ data, config = read_and_verify_release_bundle(release_bundle, policy)
195
+ check_bundle_context(data, execution)
196
+ if data["source"]["commit"] != commit:
197
+ raise ValueError("bundle source disagrees with current commit")
198
+ if execution.tag is not None and data["source"]["tag"] != execution.tag:
199
+ raise ValueError("bundle source disagrees with current tag")
200
+ return data, config
201
+
202
+
203
+ def publish_preflight(
204
+ args: argparse.Namespace, execution: Context, index: PyPIClient, github: GitHubClient
205
+ ) -> dict[str, str | bool]:
206
+ """Trust checked bundle policy and repeat only mutable external-system checks."""
207
+ commit = (
208
+ git(args.project.resolve(), "rev-parse", "HEAD^{commit}")
209
+ if execution.local
210
+ else os.environ.get("GITHUB_SHA", "")
211
+ )
212
+ data, config = check_publish_bundle(
213
+ args.release_bundle, execution, commit, get_cli_config_overrides(args)
214
+ )
215
+ index.absent(config.repository, config.distribution_name, config.version)
216
+ if not execution.local:
217
+ github.check_tag(data["source"]["tag"], data["source"]["commit"])
218
+ if config.github_release_requested:
219
+ github.release_absent(data["source"]["tag"])
220
+ return {
221
+ "version": config.version,
222
+ "distribution_name": config.distribution_name,
223
+ "tag": data["source"]["tag"],
224
+ "github_release_requested": config.github_release_requested,
225
+ }
226
+
227
+
228
+ def publish_github(
229
+ args: argparse.Namespace, execution: Context, index: PyPIClient, github: GitHubClient
230
+ ) -> dict[str, str | int | bool]:
231
+ """Gate announcement on exact index bytes; existing releases always fail."""
232
+ ### Validate the original bundle and workflow identity before network checks.
233
+ data, config = check_publish_bundle(
234
+ args.release_bundle,
235
+ execution,
236
+ os.environ.get("GITHUB_SHA", ""),
237
+ get_cli_config_overrides(args),
238
+ )
239
+ if not config.github_release_requested:
240
+ return {"github_release": "skipped"}
241
+ github.check_tag(data["source"]["tag"], data["source"]["commit"])
242
+ github.release_absent(data["source"]["tag"])
243
+ expected = {
244
+ name.removeprefix("dist/"): digest
245
+ for name, digest in data["files"].items()
246
+ if name.startswith("dist/")
247
+ }
248
+ ### Gate GitHub publication on exact index filenames and hashes.
249
+ index.verify_index(config.repository, config.distribution_name, config.version, expected)
250
+ # Index visibility can take minutes; another actor may move the tag or create
251
+ # a release while we wait. Refresh those external checks before the first write.
252
+ github.check_tag(data["source"]["tag"], data["source"]["commit"])
253
+ github.release_absent(data["source"]["tag"])
254
+ if args.check_only:
255
+ return {
256
+ "checked": "publish-github-release",
257
+ "latest": github.is_latest_final(config.version),
258
+ }
259
+ release_notes = (args.release_bundle / "release-notes.md").read_text(encoding="utf-8")
260
+ ### Stage the release privately so immutable publication includes every asset.
261
+ release_id = github.create_draft_release(
262
+ {
263
+ "tag_name": data["source"]["tag"],
264
+ "target_commitish": data["source"]["commit"],
265
+ "name": data["source"]["tag"],
266
+ "body": release_notes,
267
+ "prerelease": config.release_type != "final",
268
+ }
269
+ )
270
+ assets = [p for p in args.release_bundle.rglob("*") if p.is_file()]
271
+ for path in sorted(assets):
272
+ github.upload_asset(release_id, path)
273
+ # Uploads can take time too. Recheck the tag and latest ranking immediately
274
+ # before publication. Upload/check failures leave a draft; an unconfirmed
275
+ # publication request requires manual inspection of the remote state.
276
+ github.check_tag(data["source"]["tag"], data["source"]["commit"])
277
+ latest = github.is_latest_final(config.version)
278
+ release_url = github.publish_draft_release(release_id, latest)
279
+ return {"github_release": release_url, "assets": len(assets)}
280
+
281
+
282
+ def execute(args: argparse.Namespace) -> dict[str, str | int | bool]:
283
+ """Run a selected command and return machine-readable result metadata."""
284
+ if args.command == "workflow-template":
285
+ content = files("nopt").joinpath("workflow.yml").read_text(encoding="utf-8")
286
+ if args.output:
287
+ args.output.parent.mkdir(parents=True, exist_ok=True)
288
+ with args.output.open("x", encoding="utf-8") as stream:
289
+ stream.write(content)
290
+ return {"workflow": str(args.output)}
291
+ print(content, end="")
292
+ return {}
293
+ execution = build_context(args)
294
+ github = GitHubClient(execution.github_repository)
295
+ if args.command == "publish-github-release":
296
+ return publish_github(args, execution, PyPIClient(), github)
297
+ if args.command == "publish-release-preflight":
298
+ return publish_preflight(args, execution, PyPIClient(), github)
299
+ root = args.project.resolve()
300
+ config = load(root, get_cli_config_overrides(args))
301
+ source, release_notes = check_source(root, config, execution, PyPIClient(), github)
302
+ result: dict[str, str | int | bool] = {
303
+ "version": config.version,
304
+ "distribution_name": config.distribution_name,
305
+ "tag": source["tag"],
306
+ "github_release_requested": config.github_release_requested,
307
+ }
308
+ if args.command == "build":
309
+ validate_build_output_path(root, args.output)
310
+ if args.command == "build" and not args.check_only:
311
+ build_release_bundle(root, args.output, config, execution, source, release_notes)
312
+ result["bundle"] = str(args.output.resolve())
313
+ output = os.environ.get("GITHUB_OUTPUT") if not execution.local else None
314
+ if output:
315
+ with open(output, "a", encoding="utf-8") as stream:
316
+ for key, value in result.items():
317
+ stream.write(f"{key}={str(value).lower() if isinstance(value, bool) else value}\n")
318
+ return result
319
+
320
+
321
+ def main(argv: list[str] | None = None) -> int:
322
+ """Run the CLI and preserve exception tracebacks for failures."""
323
+ args = build_parser().parse_args(argv)
324
+ result = execute(args)
325
+ if result:
326
+ print(json.dumps(result, sort_keys=True))
327
+ return 0