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 +1 -0
- nopt/__main__.py +5 -0
- nopt/bundle.py +297 -0
- nopt/changelog.py +37 -0
- nopt/cli.py +327 -0
- nopt/config.py +164 -0
- nopt/project.py +14 -0
- nopt/remote.py +232 -0
- nopt/source.py +110 -0
- nopt/workflow.yml +111 -0
- nopt-0.1.0.dev0.dist-info/METADATA +176 -0
- nopt-0.1.0.dev0.dist-info/RECORD +16 -0
- nopt-0.1.0.dev0.dist-info/WHEEL +5 -0
- nopt-0.1.0.dev0.dist-info/entry_points.txt +2 -0
- nopt-0.1.0.dev0.dist-info/licenses/LICENCE +21 -0
- nopt-0.1.0.dev0.dist-info/top_level.txt +1 -0
nopt/config.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Validate the deliberately small public configuration surface."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass, fields, replace
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
import tomllib
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from packaging.utils import canonicalize_name
|
|
11
|
+
from packaging.version import Version
|
|
12
|
+
|
|
13
|
+
_GROUPS = {"dev", "pre", "final"}
|
|
14
|
+
_VERSION_PATTERN = re.compile(
|
|
15
|
+
r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:(?:\.dev|a|b|rc)(?:0|[1-9][0-9]*))?"
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parse_version(value: object) -> Version:
|
|
20
|
+
"""Parse only the canonical version forms accepted by nopt release policy."""
|
|
21
|
+
if not isinstance(value, str) or not _VERSION_PATTERN.fullmatch(value):
|
|
22
|
+
raise ValueError("version must be canonical X.Y.Z with at most one .devN/aN/bN/rcN suffix")
|
|
23
|
+
parsed = Version(value)
|
|
24
|
+
if str(parsed) != value:
|
|
25
|
+
raise ValueError("version must use canonical spelling")
|
|
26
|
+
return parsed
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Config: # pylint: disable=too-many-instance-attributes
|
|
31
|
+
"""Resolved project identity and release policy."""
|
|
32
|
+
|
|
33
|
+
name: str
|
|
34
|
+
version: str
|
|
35
|
+
changelog: str | Literal[False] = "docs/changelog.md"
|
|
36
|
+
repository: str = "pypi"
|
|
37
|
+
allow_dirty: tuple[str, ...] = ("dev",)
|
|
38
|
+
final_release_branches: tuple[str, ...] = ("main",)
|
|
39
|
+
pre_release_branches: tuple[str, ...] | Literal[False] = ("main",)
|
|
40
|
+
dev_release_branches: tuple[str, ...] | Literal[False] = False
|
|
41
|
+
testpypi_username: str | None = None
|
|
42
|
+
github_release_publish: bool = True
|
|
43
|
+
github_release_types: tuple[str, ...] = ("pre", "final")
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_mapping(cls, values: Mapping[str, object]) -> "Config":
|
|
47
|
+
"""Resolve untrusted policy values into a validated immutable configuration."""
|
|
48
|
+
name = values.get("name")
|
|
49
|
+
version = values.get("version")
|
|
50
|
+
if not isinstance(name, str) or not isinstance(version, str):
|
|
51
|
+
raise ValueError("project.name and project.version must be static strings")
|
|
52
|
+
allowed = {field.name for field in fields(cls)}
|
|
53
|
+
if unknown := set(values) - allowed:
|
|
54
|
+
raise ValueError(f"unknown configuration fields: {', '.join(sorted(unknown))}")
|
|
55
|
+
policy = {key: value for key, value in values.items() if key not in {"name", "version"}}
|
|
56
|
+
return validate(cls(name, version, **policy))
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def release_type(self) -> str:
|
|
60
|
+
"""Classify the supported version subset."""
|
|
61
|
+
parsed = Version(self.version)
|
|
62
|
+
return "dev" if parsed.is_devrelease else "pre" if parsed.is_prerelease else "final"
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def distribution_name(self) -> str:
|
|
66
|
+
"""Return the index-facing distribution name."""
|
|
67
|
+
if self.repository == "testpypi":
|
|
68
|
+
return f"{self.name}-{self.testpypi_username}"
|
|
69
|
+
return self.name
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def github_release_requested(self) -> bool:
|
|
73
|
+
"""Return whether this release should be announced on GitHub."""
|
|
74
|
+
return self.github_release_publish and self.release_type in self.github_release_types
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def validate(config: Config) -> Config: # pylint: disable=too-many-branches
|
|
78
|
+
"""Reject unsupported or ambiguous configuration."""
|
|
79
|
+
if not isinstance(config.name, str) or not re.fullmatch(
|
|
80
|
+
r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?", config.name
|
|
81
|
+
):
|
|
82
|
+
raise ValueError("project.name must be a distribution name")
|
|
83
|
+
parse_version(config.version)
|
|
84
|
+
if config.changelog is not False and (
|
|
85
|
+
not isinstance(config.changelog, str) or not config.changelog
|
|
86
|
+
):
|
|
87
|
+
raise ValueError("changelog must be a path or false")
|
|
88
|
+
if not isinstance(config.repository, str) or config.repository not in {"pypi", "testpypi"}:
|
|
89
|
+
raise ValueError("repository must be pypi or testpypi")
|
|
90
|
+
for setting in ("allow_dirty", "github_release_types"):
|
|
91
|
+
value = getattr(config, setting)
|
|
92
|
+
if (
|
|
93
|
+
not isinstance(value, (tuple, list))
|
|
94
|
+
or any(not isinstance(item, str) or item not in _GROUPS for item in value)
|
|
95
|
+
or len(set(value)) != len(value)
|
|
96
|
+
):
|
|
97
|
+
raise ValueError(
|
|
98
|
+
f"{setting.replace('_', '-')} must contain unique dev/pre/final groups"
|
|
99
|
+
)
|
|
100
|
+
for group in ("final", "pre", "dev"):
|
|
101
|
+
branches = getattr(config, f"{group}_release_branches")
|
|
102
|
+
if branches is False and group != "final":
|
|
103
|
+
continue
|
|
104
|
+
if not isinstance(branches, (tuple, list)) or not branches:
|
|
105
|
+
raise ValueError(f"{group}-release-branches must be a nonempty branch list")
|
|
106
|
+
for branch in branches:
|
|
107
|
+
if (
|
|
108
|
+
not isinstance(branch, str)
|
|
109
|
+
or not branch
|
|
110
|
+
or any(
|
|
111
|
+
token in branch
|
|
112
|
+
for token in ("*", "?", "[", "..", "@{", "\\", " ", ":", "~", "^", "\n", "\r")
|
|
113
|
+
)
|
|
114
|
+
or branch.startswith(("-", "/", "."))
|
|
115
|
+
or branch.endswith(("/", ".", ".lock"))
|
|
116
|
+
):
|
|
117
|
+
raise ValueError("branches must be literal valid Git branch names, without globs")
|
|
118
|
+
if not isinstance(config.github_release_publish, bool):
|
|
119
|
+
raise ValueError("github-release-publish must be boolean")
|
|
120
|
+
if config.github_release_requested and config.changelog is False:
|
|
121
|
+
raise ValueError("GitHub release publication requires changelog-derived release notes")
|
|
122
|
+
if config.repository == "testpypi":
|
|
123
|
+
if not isinstance(config.testpypi_username, str) or not re.fullmatch(
|
|
124
|
+
r"[a-z0-9]+(?:-[a-z0-9]+)*", config.testpypi_username
|
|
125
|
+
):
|
|
126
|
+
raise ValueError(
|
|
127
|
+
"repository=testpypi requires testpypi-username with lowercase letters, "
|
|
128
|
+
"digits and single hyphens"
|
|
129
|
+
)
|
|
130
|
+
canonicalize_name(config.distribution_name, validate=True)
|
|
131
|
+
return replace(
|
|
132
|
+
config,
|
|
133
|
+
**{
|
|
134
|
+
key: tuple(value) if isinstance(value, list) else value
|
|
135
|
+
for key, value in vars(config).items()
|
|
136
|
+
},
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def load(root: Path, overrides: Mapping[str, object] | None = None) -> Config:
|
|
141
|
+
"""Read TOML with explicit CLI overrides and preserve false values."""
|
|
142
|
+
data = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
|
|
143
|
+
project = data.get("project", {})
|
|
144
|
+
if not isinstance(project, dict):
|
|
145
|
+
raise ValueError("project must be a TOML table")
|
|
146
|
+
if any(key in project.get("dynamic", []) for key in ("name", "version")):
|
|
147
|
+
raise ValueError("project name/version must be static")
|
|
148
|
+
tool = data.get("tool", {})
|
|
149
|
+
if not isinstance(tool, dict):
|
|
150
|
+
raise ValueError("tool must be a TOML table")
|
|
151
|
+
table = tool.get("nopt", {})
|
|
152
|
+
if not isinstance(table, dict):
|
|
153
|
+
raise ValueError("tool.nopt must be a TOML table")
|
|
154
|
+
allowed = {field.name for field in fields(Config)} - {"name", "version"}
|
|
155
|
+
unknown = {key for key in table if key.replace("-", "_") not in allowed}
|
|
156
|
+
if unknown:
|
|
157
|
+
raise ValueError(f"unknown tool.nopt settings: {', '.join(sorted(unknown))}")
|
|
158
|
+
values: dict[str, object] = {
|
|
159
|
+
"name": project.get("name"),
|
|
160
|
+
"version": project.get("version"),
|
|
161
|
+
**{key.replace("-", "_"): value for key, value in table.items()},
|
|
162
|
+
**(overrides or {}),
|
|
163
|
+
}
|
|
164
|
+
return Config.from_mapping(values)
|
nopt/project.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Update the distribution name for a temporary TestPyPI build."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import tomllib
|
|
5
|
+
|
|
6
|
+
import tomli_w
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def rename_distribution(path: Path, name: str) -> None:
|
|
10
|
+
"""Rename an already validated project identity for a temporary TestPyPI build."""
|
|
11
|
+
document = tomllib.loads(path.read_bytes().decode("utf-8"))
|
|
12
|
+
document["project"]["name"] = name
|
|
13
|
+
path.write_bytes(tomli_w.dumps(document).encode("utf-8"))
|
|
14
|
+
return
|
nopt/remote.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Bounded index checks and minimal GitHub release operations; no package upload."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import time
|
|
8
|
+
from urllib.error import HTTPError
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
from urllib.request import Request, urlopen
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
from .config import parse_version
|
|
14
|
+
from .source import is_latest_final
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def decode_response(raw: bytes) -> dict[str, object] | list[object]:
|
|
18
|
+
"""Decode a successful JSON response without confusing empty/null with HTTP 404."""
|
|
19
|
+
try:
|
|
20
|
+
decoded: object = json.loads(raw)
|
|
21
|
+
except ValueError:
|
|
22
|
+
raise ValueError("successful API response must contain valid JSON") from None
|
|
23
|
+
if not isinstance(decoded, (dict, list)):
|
|
24
|
+
raise ValueError("successful API response must contain a JSON object or array")
|
|
25
|
+
return decoded
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def request(
|
|
29
|
+
url: str,
|
|
30
|
+
method: str = "GET",
|
|
31
|
+
data: bytes | None = None,
|
|
32
|
+
github: bool = False,
|
|
33
|
+
content_type: str = "application/json",
|
|
34
|
+
) -> object:
|
|
35
|
+
"""Perform one request; only HTTP 404 is treated as absence."""
|
|
36
|
+
headers = {"User-Agent": "nopt/0.1", "Accept": "application/json"}
|
|
37
|
+
if github:
|
|
38
|
+
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
|
|
39
|
+
if not token:
|
|
40
|
+
raise ValueError("GitHub API access requires GH_TOKEN or GITHUB_TOKEN")
|
|
41
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
42
|
+
headers["X-GitHub-Api-Version"] = "2022-11-28"
|
|
43
|
+
if data is not None:
|
|
44
|
+
headers["Content-Type"] = content_type
|
|
45
|
+
try:
|
|
46
|
+
with urlopen(
|
|
47
|
+
Request(url, data=data, headers=headers, method=method), timeout=30
|
|
48
|
+
) as response:
|
|
49
|
+
raw = response.read()
|
|
50
|
+
return decode_response(raw)
|
|
51
|
+
except HTTPError as error:
|
|
52
|
+
if error.code == 404:
|
|
53
|
+
return None
|
|
54
|
+
# Do not expose response bodies or authenticated request headers.
|
|
55
|
+
raise ValueError(f"HTTP {error.code} from {url.split('?')[0]}") from None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class PyPIClient:
|
|
59
|
+
"""Read public package-index records without GitHub credentials."""
|
|
60
|
+
|
|
61
|
+
def index(self, target: str, name: str, version: str) -> object:
|
|
62
|
+
"""Look up exactly the target version on the chosen index."""
|
|
63
|
+
host = "pypi.org" if target == "pypi" else "test.pypi.org"
|
|
64
|
+
return request(f"https://{host}/pypi/{quote(name, safe='')}/{quote(version, safe='')}/json")
|
|
65
|
+
|
|
66
|
+
def absent(self, target: str, name: str, version: str) -> None:
|
|
67
|
+
"""Any record, even empty or yanked, prevents a new upload."""
|
|
68
|
+
if self.index(target, name, version) is not None:
|
|
69
|
+
raise ValueError(f"{target} already has a record for {name} {version}")
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
def verify_index(
|
|
73
|
+
self, target: str, name: str, version: str, expected: dict[str, str], timeout: float = 300
|
|
74
|
+
) -> None:
|
|
75
|
+
"""Wait only for missing/partial matching metadata; fail promptly on conflicts."""
|
|
76
|
+
deadline = time.monotonic() + timeout
|
|
77
|
+
while True:
|
|
78
|
+
if publication_matches(self.index(target, name, version), expected):
|
|
79
|
+
return
|
|
80
|
+
if time.monotonic() >= deadline:
|
|
81
|
+
raise ValueError(
|
|
82
|
+
f"timed out waiting for {target} filenames/hashes: expected {expected}"
|
|
83
|
+
)
|
|
84
|
+
time.sleep(min(5, max(0, deadline - time.monotonic())))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class GitHubClient:
|
|
88
|
+
"""Interact with one authenticated GitHub repository."""
|
|
89
|
+
|
|
90
|
+
def __init__(self, repository: str | None) -> None:
|
|
91
|
+
"""Bind authenticated operations to one repository."""
|
|
92
|
+
self.repository = repository
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
def github(
|
|
96
|
+
self, path: str, method: str = "GET", data: Mapping[str, object] | None = None
|
|
97
|
+
) -> object:
|
|
98
|
+
"""Use a fixed API host and validated owner/repository identity."""
|
|
99
|
+
if self.repository is None:
|
|
100
|
+
raise ValueError("GitHub repository identity is required")
|
|
101
|
+
return request(
|
|
102
|
+
f"https://api.github.com/repos/{self.repository}/{path}",
|
|
103
|
+
method,
|
|
104
|
+
None if data is None else json.dumps(data).encode(),
|
|
105
|
+
github=True,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def upload_asset(self, release_id: int, path: Path) -> None:
|
|
109
|
+
"""Attach one original bundle file and require a completed upload."""
|
|
110
|
+
if self.repository is None:
|
|
111
|
+
raise ValueError("GitHub repository identity is required")
|
|
112
|
+
result = request(
|
|
113
|
+
f"https://uploads.github.com/repos/{self.repository}"
|
|
114
|
+
f"/releases/{release_id}/assets?name={quote(path.name, safe='')}",
|
|
115
|
+
"POST",
|
|
116
|
+
path.read_bytes(),
|
|
117
|
+
github=True,
|
|
118
|
+
content_type="application/octet-stream",
|
|
119
|
+
)
|
|
120
|
+
if not isinstance(result, dict) or result.get("state") != "uploaded":
|
|
121
|
+
raise ValueError(
|
|
122
|
+
f"GitHub asset upload did not complete: {path.name}; recovery is deferred"
|
|
123
|
+
)
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
def check_tag(self, tag: str, commit: str) -> None:
|
|
127
|
+
"""Resolve the live remote tag, including annotated tags, through commits API."""
|
|
128
|
+
data = self.github(f"commits/tags/{quote(tag, safe='')}")
|
|
129
|
+
if not isinstance(data, dict) or data.get("sha") != commit:
|
|
130
|
+
raise ValueError(f"GitHub tag {tag} is missing or no longer points to {commit}")
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
def is_latest_final(self, version: str) -> bool:
|
|
134
|
+
"""Read Git tag refs and identify the highest canonical final release."""
|
|
135
|
+
parsed = parse_version(version)
|
|
136
|
+
if parsed.is_devrelease or parsed.is_prerelease:
|
|
137
|
+
return False
|
|
138
|
+
data = self.github("git/matching-refs/tags/")
|
|
139
|
+
if not isinstance(data, list):
|
|
140
|
+
raise ValueError("GitHub tag references must be an array")
|
|
141
|
+
refs: list[str] = []
|
|
142
|
+
for item in data:
|
|
143
|
+
if not isinstance(item, dict):
|
|
144
|
+
raise ValueError("malformed GitHub tag reference")
|
|
145
|
+
ref = item.get("ref")
|
|
146
|
+
if not isinstance(ref, str) or not ref.startswith("refs/tags/"):
|
|
147
|
+
raise ValueError("malformed GitHub tag reference name")
|
|
148
|
+
refs.append(ref)
|
|
149
|
+
return is_latest_final(version, refs)
|
|
150
|
+
|
|
151
|
+
def release_absent(self, tag: str) -> None:
|
|
152
|
+
"""Reject a visible published or draft release; recovery is deferred."""
|
|
153
|
+
if self.github(f"releases/tags/{quote(tag, safe='')}") is not None:
|
|
154
|
+
raise ValueError("GitHub release already exists; automatic recovery is not implemented")
|
|
155
|
+
# Tag lookup returns published releases only. Drafts require authenticated
|
|
156
|
+
# listings with push access; publication jobs have contents: write.
|
|
157
|
+
page = 1
|
|
158
|
+
while True:
|
|
159
|
+
releases = self.github(f"releases?per_page=100&page={page}")
|
|
160
|
+
if not isinstance(releases, list):
|
|
161
|
+
raise ValueError("GitHub releases listing must be an array")
|
|
162
|
+
for release in releases:
|
|
163
|
+
if not isinstance(release, dict) or not isinstance(release.get("tag_name"), str):
|
|
164
|
+
raise ValueError("malformed GitHub release listing")
|
|
165
|
+
if release["tag_name"] == tag:
|
|
166
|
+
raise ValueError(
|
|
167
|
+
"GitHub release already exists (draft or published); recovery is deferred"
|
|
168
|
+
)
|
|
169
|
+
if len(releases) < 100:
|
|
170
|
+
return
|
|
171
|
+
page += 1
|
|
172
|
+
|
|
173
|
+
def create_draft_release(self, metadata: Mapping[str, object]) -> int:
|
|
174
|
+
"""Create an unpublished release and require its identity before uploading."""
|
|
175
|
+
release = self.github(
|
|
176
|
+
"releases", "POST", {**metadata, "draft": True, "make_latest": "false"}
|
|
177
|
+
)
|
|
178
|
+
if not isinstance(release, dict):
|
|
179
|
+
raise ValueError("GitHub did not return a draft release identity")
|
|
180
|
+
release_id = release.get("id")
|
|
181
|
+
if not isinstance(release_id, int) or isinstance(release_id, bool):
|
|
182
|
+
raise ValueError("GitHub did not return an integer release identity")
|
|
183
|
+
if release.get("draft") is not True or release.get("tag_name") != metadata["tag_name"]:
|
|
184
|
+
raise ValueError("GitHub did not create the expected draft release")
|
|
185
|
+
return release_id
|
|
186
|
+
|
|
187
|
+
def publish_draft_release(self, release_id: int, latest: bool) -> str:
|
|
188
|
+
"""Publish only after uploads finish and confirm the draft became public."""
|
|
189
|
+
release = self.github(
|
|
190
|
+
f"releases/{release_id}",
|
|
191
|
+
"PATCH",
|
|
192
|
+
{"draft": False, "make_latest": "true" if latest else "false"},
|
|
193
|
+
)
|
|
194
|
+
if not isinstance(release, dict):
|
|
195
|
+
raise ValueError("GitHub did not return a published release identity")
|
|
196
|
+
observed_id = release.get("id")
|
|
197
|
+
if (
|
|
198
|
+
not isinstance(observed_id, int)
|
|
199
|
+
or isinstance(observed_id, bool)
|
|
200
|
+
or observed_id != release_id
|
|
201
|
+
or release.get("draft") is not False
|
|
202
|
+
):
|
|
203
|
+
raise ValueError("GitHub did not confirm publication of the expected release")
|
|
204
|
+
release_url = release.get("html_url")
|
|
205
|
+
if not isinstance(release_url, str) or not release_url:
|
|
206
|
+
raise ValueError("GitHub did not return a release URL")
|
|
207
|
+
return release_url
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def publication_matches(data: object, expected: Mapping[str, str]) -> bool:
|
|
211
|
+
"""Return incomplete versus complete metadata; reject malformed/conflicting data."""
|
|
212
|
+
if data is None:
|
|
213
|
+
return False
|
|
214
|
+
if not isinstance(data, dict) or not isinstance(data.get("urls"), list):
|
|
215
|
+
raise ValueError("malformed index response")
|
|
216
|
+
observed: dict[str, str] = {}
|
|
217
|
+
for item in data["urls"]:
|
|
218
|
+
if not isinstance(item, dict) or not isinstance(item.get("filename"), str):
|
|
219
|
+
raise ValueError("malformed index file metadata")
|
|
220
|
+
name = item["filename"]
|
|
221
|
+
digests = item.get("digests")
|
|
222
|
+
if not isinstance(digests, dict) or not isinstance(digests.get("sha256"), str):
|
|
223
|
+
raise ValueError("malformed index file digest metadata")
|
|
224
|
+
digest = digests["sha256"]
|
|
225
|
+
if name in observed or name not in expected or digest != expected[name]:
|
|
226
|
+
raise ValueError(
|
|
227
|
+
f"index conflict: expected {expected}; observed conflicting file {name}: {digest}"
|
|
228
|
+
)
|
|
229
|
+
if item.get("yanked", False):
|
|
230
|
+
raise ValueError(f"index file is yanked: {name}")
|
|
231
|
+
observed[name] = digest
|
|
232
|
+
return observed == expected
|
nopt/source.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Read release identity and Git working-tree status."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import subprocess
|
|
7
|
+
from typing import TypedDict
|
|
8
|
+
|
|
9
|
+
from .config import Config, parse_version
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SourceIdentity(TypedDict):
|
|
13
|
+
"""Source commit, release tag and pre-build Git status."""
|
|
14
|
+
|
|
15
|
+
commit: str
|
|
16
|
+
tag: str
|
|
17
|
+
dirty: bool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ContextData(TypedDict):
|
|
21
|
+
"""Serialized execution context stored in a release bundle."""
|
|
22
|
+
|
|
23
|
+
local: bool
|
|
24
|
+
tag: str | None
|
|
25
|
+
github_repository: str | None
|
|
26
|
+
run_id: str | None
|
|
27
|
+
run_attempt: str | None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Context:
|
|
32
|
+
"""Inputs supplied by the caller rather than guessed from another run."""
|
|
33
|
+
|
|
34
|
+
local: bool
|
|
35
|
+
tag: str | None = None
|
|
36
|
+
github_repository: str | None = None
|
|
37
|
+
run_id: str | None = None
|
|
38
|
+
run_attempt: str | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def git(root: Path, *args: str) -> str:
|
|
42
|
+
"""Run a read-only Git query."""
|
|
43
|
+
return subprocess.check_output(
|
|
44
|
+
["git", *args], cwd=root, text=True, stderr=subprocess.PIPE, timeout=60
|
|
45
|
+
).strip()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def check_branches(root: Path, config: Config, context: Context, commit: str) -> None:
|
|
49
|
+
"""Require ancestry from any existing allowed branch, never branch-tip equality."""
|
|
50
|
+
branches = getattr(config, f"{config.release_type}_release_branches")
|
|
51
|
+
if branches is False:
|
|
52
|
+
return
|
|
53
|
+
for branch in branches:
|
|
54
|
+
ref = f"refs/heads/{branch}" if context.local else f"refs/remotes/origin/{branch}"
|
|
55
|
+
exists = subprocess.run(
|
|
56
|
+
["git", "show-ref", "--verify", "--quiet", ref], cwd=root, check=False
|
|
57
|
+
)
|
|
58
|
+
if exists.returncode == 1:
|
|
59
|
+
continue
|
|
60
|
+
if exists.returncode != 0:
|
|
61
|
+
raise ValueError(f"unable to resolve branch {ref}")
|
|
62
|
+
status = subprocess.run(
|
|
63
|
+
["git", "merge-base", "--is-ancestor", commit, ref], cwd=root, check=False
|
|
64
|
+
)
|
|
65
|
+
if status.returncode == 0:
|
|
66
|
+
return
|
|
67
|
+
if status.returncode != 1:
|
|
68
|
+
raise ValueError(f"unable to establish ancestry for {ref}")
|
|
69
|
+
raise ValueError("release commit is not reachable from any existing allowed branch")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def identity(root: Path, config: Config, context: Context) -> SourceIdentity:
|
|
73
|
+
"""Verify tag/branch/dirty policy and return source identity."""
|
|
74
|
+
commit = git(root, "rev-parse", "HEAD")
|
|
75
|
+
expected = "v" + config.version
|
|
76
|
+
tag = context.tag or expected
|
|
77
|
+
if tag != expected:
|
|
78
|
+
raise ValueError(f"expected canonical tag {expected}, got {tag}")
|
|
79
|
+
if git(root, "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}") != commit:
|
|
80
|
+
raise ValueError("release tag does not point to HEAD")
|
|
81
|
+
check_branches(root, config, context, commit)
|
|
82
|
+
status = subprocess.check_output(
|
|
83
|
+
["git", "status", "--porcelain=v1", "-z", "--untracked-files=all"],
|
|
84
|
+
cwd=root,
|
|
85
|
+
timeout=60,
|
|
86
|
+
)
|
|
87
|
+
dirty = bool(status)
|
|
88
|
+
if dirty and config.release_type not in config.allow_dirty:
|
|
89
|
+
raise ValueError(f"working tree is dirty; {config.release_type} is not in allow-dirty")
|
|
90
|
+
return {"commit": commit, "tag": tag, "dirty": dirty}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def is_latest_final(version: str, refs: Iterable[str]) -> bool:
|
|
94
|
+
"""Compare canonical final-version tag refs without package-index or release-date data."""
|
|
95
|
+
current = parse_version(version)
|
|
96
|
+
if current.is_devrelease or current.is_prerelease:
|
|
97
|
+
return False
|
|
98
|
+
finals = []
|
|
99
|
+
for ref in refs:
|
|
100
|
+
if not ref.startswith("refs/tags/v"):
|
|
101
|
+
continue
|
|
102
|
+
try:
|
|
103
|
+
candidate = parse_version(ref.removeprefix("refs/tags/v"))
|
|
104
|
+
except ValueError:
|
|
105
|
+
continue
|
|
106
|
+
if not candidate.is_devrelease and not candidate.is_prerelease:
|
|
107
|
+
finals.append(candidate)
|
|
108
|
+
if current not in finals:
|
|
109
|
+
raise ValueError("current final release tag is missing from Git tag refs")
|
|
110
|
+
return current == max(finals)
|
nopt/workflow.yml
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Editable starting point. Replace the CI placeholder before enabling publishing.
|
|
2
|
+
# Pin nopt and all actions to reviewed immutable revisions before production use.
|
|
3
|
+
name: Publish release
|
|
4
|
+
on:
|
|
5
|
+
push:
|
|
6
|
+
tags: ['v*']
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read
|
|
9
|
+
concurrency:
|
|
10
|
+
group: release-${{ github.ref }}
|
|
11
|
+
cancel-in-progress: false
|
|
12
|
+
jobs:
|
|
13
|
+
preflight:
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
|
17
|
+
with:
|
|
18
|
+
fetch-depth: 0
|
|
19
|
+
persist-credentials: false
|
|
20
|
+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
|
21
|
+
with:
|
|
22
|
+
python-version: '3.13'
|
|
23
|
+
- name: Install nopt
|
|
24
|
+
run: python -m pip install 'git+https://github.com/nhairs/nicks-opinionated-python-package-publishing-tool@main'
|
|
25
|
+
- run: nopt ci-preflight
|
|
26
|
+
env:
|
|
27
|
+
GH_TOKEN: ${{ github.token }}
|
|
28
|
+
ci:
|
|
29
|
+
needs: preflight
|
|
30
|
+
runs-on: ubuntu-latest
|
|
31
|
+
steps:
|
|
32
|
+
- name: Replace with project CI
|
|
33
|
+
run: |
|
|
34
|
+
echo '<your CI goes here>'
|
|
35
|
+
exit 1
|
|
36
|
+
build:
|
|
37
|
+
needs: [preflight, ci]
|
|
38
|
+
runs-on: ubuntu-latest
|
|
39
|
+
outputs:
|
|
40
|
+
artifact_id: ${{ steps.bundle.outputs.artifact-id }}
|
|
41
|
+
steps:
|
|
42
|
+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
|
43
|
+
with:
|
|
44
|
+
fetch-depth: 0
|
|
45
|
+
persist-credentials: false
|
|
46
|
+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
|
47
|
+
with:
|
|
48
|
+
python-version: '3.13'
|
|
49
|
+
- run: python -m pip install 'git+https://github.com/nhairs/nicks-opinionated-python-package-publishing-tool@main'
|
|
50
|
+
- id: build
|
|
51
|
+
run: nopt build --output "$RUNNER_TEMP/release-bundle"
|
|
52
|
+
env:
|
|
53
|
+
GH_TOKEN: ${{ github.token }}
|
|
54
|
+
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
|
55
|
+
id: bundle
|
|
56
|
+
with:
|
|
57
|
+
name: release-bundle-${{ github.run_id }}-${{ github.run_attempt }}
|
|
58
|
+
path: ${{ runner.temp }}/release-bundle/
|
|
59
|
+
retention-days: 90
|
|
60
|
+
if-no-files-found: error
|
|
61
|
+
publish:
|
|
62
|
+
needs: build
|
|
63
|
+
runs-on: ubuntu-latest
|
|
64
|
+
environment: pypi # For TestPyPI use its environment and configure repository in pyproject.toml.
|
|
65
|
+
permissions:
|
|
66
|
+
contents: read
|
|
67
|
+
id-token: write
|
|
68
|
+
steps:
|
|
69
|
+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
|
70
|
+
with:
|
|
71
|
+
python-version: '3.13'
|
|
72
|
+
- run: python -m pip install 'git+https://github.com/nhairs/nicks-opinionated-python-package-publishing-tool@main'
|
|
73
|
+
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
|
74
|
+
with:
|
|
75
|
+
artifact-ids: ${{ needs.build.outputs.artifact_id }}
|
|
76
|
+
merge-multiple: true
|
|
77
|
+
path: ${{ runner.temp }}/release-bundle
|
|
78
|
+
- run: nopt publish-release-preflight --bundle "$RUNNER_TEMP/release-bundle"
|
|
79
|
+
env:
|
|
80
|
+
GH_TOKEN: ${{ github.token }}
|
|
81
|
+
- name: Copy verified distributions for upload and attestation generation
|
|
82
|
+
run: cp -R "$RUNNER_TEMP/release-bundle/dist" "$RUNNER_TEMP/publish-dist"
|
|
83
|
+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
|
84
|
+
with:
|
|
85
|
+
packages-dir: ${{ runner.temp }}/publish-dist/
|
|
86
|
+
# For TestPyPI add repository-url: https://test.pypi.org/legacy/
|
|
87
|
+
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
|
88
|
+
if: always()
|
|
89
|
+
with:
|
|
90
|
+
name: publication-evidence-${{ github.run_id }}-${{ github.run_attempt }}
|
|
91
|
+
path: ${{ runner.temp }}/publish-dist/
|
|
92
|
+
retention-days: 90
|
|
93
|
+
if-no-files-found: warn
|
|
94
|
+
github-release:
|
|
95
|
+
needs: [build, publish]
|
|
96
|
+
runs-on: ubuntu-latest
|
|
97
|
+
permissions:
|
|
98
|
+
contents: write
|
|
99
|
+
steps:
|
|
100
|
+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
|
101
|
+
with:
|
|
102
|
+
python-version: '3.13'
|
|
103
|
+
- run: python -m pip install 'git+https://github.com/nhairs/nicks-opinionated-python-package-publishing-tool@main'
|
|
104
|
+
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
|
105
|
+
with:
|
|
106
|
+
artifact-ids: ${{ needs.build.outputs.artifact_id }}
|
|
107
|
+
merge-multiple: true
|
|
108
|
+
path: ${{ runner.temp }}/release-bundle
|
|
109
|
+
- run: nopt publish-github-release --bundle "$RUNNER_TEMP/release-bundle"
|
|
110
|
+
env:
|
|
111
|
+
GH_TOKEN: ${{ github.token }}
|