Orchestrate resumable draft RC releases across platforms

This commit is contained in:
supermerill 2026-11-13 20:35:04 +01:00
parent d283f00eb7
commit 5e3b716640
13 changed files with 1739 additions and 42 deletions

7
.github/release-footer.md vendored Normal file
View file

@ -0,0 +1,7 @@
## Code signing policy
Free code signing provided by [SignPath.io](https://about.signpath.io), certificate by [SignPath Foundation](https://signpath.org).
Windows EXE/DLL files built by this project and the Windows installer are signed through SignPath before packaging and upload. Third-party libraries are not re-signed with the project's certificate.
See the [code signing policy]({{CODE_SIGNING_POLICY_URL}}) for team roles, signing scope and privacy information.

127
.github/release/README.md vendored Normal file
View file

@ -0,0 +1,127 @@
# RC release pipeline
`release_rc.yml` is the **only** workflow triggered by a push to `rc`. It prepares an
immutable version tag and a draft release, then calls the five RC workflows for
platforms with missing files. No build passes through a maintainer's computer.
## Version and files
The version is `SLIC3R_RC_VERSION_DOTS` + `SLIC3R_VERSION_TAG` with `+UNKNOWN` removed.
For example, `2.7.63.0` and `-beta+UNKNOWN` produce tag `2.7.63.0-beta` and:
| Platform | Release files |
| --- | --- |
| Windows | `SuperSlicer_2.7.63.0-beta_win64.zip`, `SuperSlicer_2.7.63.0-beta_win64.msi` |
| macOS Intel | `SuperSlicer_2.7.63.0-beta_macos.dmg` |
| macOS ARM | `SuperSlicer_2.7.63.0-beta_macos_arm.dmg` |
| Linux GTK3 | `SuperSlicer-ubuntu_22.04-2.7.63.0-beta.AppImage`, `SuperSlicer_2.7.63.0-beta_linux64.tgz` |
| Linux GTK2 | `SuperSlicer-ubuntu_22.04-gtk2-2.7.63.0-beta.AppImage` |
Release names have **no date**. Nightly version/date handling is unchanged: those
workflows can replace `+UNKNOWN` with the date as before. Internal EXE/DLL names and
package layout are not changed; the portable ZIP still has a single named root folder.
DMG/MSI/AppImage/TGZ files are uploaded directly as release assets, without the ZIP
envelope used by GitHub Actions' artifact storage. Extra TGZ diagnostics remain
available in the individual macOS/GTK2 build artifacts.
## Trigger and permissions
Push the complete release pipeline and the intended version to `rc`, or manually run
**RC release orchestrator**, selecting branch `rc`. A manual run on another branch
fails before any GitHub write. GitHub only shows the manual button after the workflow
is also available on the repository's default branch.
**Deploy the workflow definitions to the default branch before the first RC run.**
GitHub can refuse release creation/update with `GITHUB_TOKEN` when the target commit's
`.github/workflows/` files differ from the default branch: that requires the separate
Workflows write permission, which `GITHUB_TOKEN` cannot have. Keep these definitions
synchronized on the default branch and `rc`; do not work around the refusal by moving
a version tag or adding a maintainer PAT. See [GitHub's create-release restrictions](https://docs.github.com/en/rest/releases/releases#create-a-release).
Preparation creates the tag at the **triggering commit SHA**. All dependency and
application jobs check out that same SHA, including Linux (never a floating `rc`).
Local `workflow_call` references also resolve to the caller's workflow revision.
The legacy independent `push rc` triggers are removed to prevent double builds.
`debug_win`, `rc-macintel` and individual manual diagnostic builds do not publish
release assets without the master's inputs.
Preparation has `contents: write` to create refs/drafts. Compilation/signing jobs have
read-only repository access and do not persist checkout credentials. Each platform's
publisher calls `release_upload.yml`, with `contents: write`, on a fresh hosted runner.
It downloads the **exact artifact ID from the same workflow run**. A manifest binds
the filenames, platform, version and source SHA and verifies each file's SHA-256 after
transfer, before posting the raw files to GitHub Releases. The manifest itself is an
internal Actions artifact, not an additional release download.
The final summary also needs `contents: write` because GitHub restricts draft-release
visibility to push-capable tokens, even for GET requests. Its `verify` command only
reads GitHub state and never changes or publishes the release.
The API helper uses only the job's `GH_TOKEN` (`github.token`). It never reads
`githubtoken.ini`, requires no maintainer PAT and never prints authentication headers.
## Required failures and safe resume
- A version tag pointing at another commit makes the build **fail**. Never move or
recreate that tag automatically. Increment the version when changing source code,
including release scripts after a tag has already been created.
- An existing **public** release makes the build **fail**, even if some assets are
missing. This pipeline only creates/completes **drafts**.
- Existing drafts must still have their matching tag. A missing tag is an error,
not an invitation to silently recreate it.
- A complete platform is skipped with a warning. A partially uploaded platform is
rebuilt, but its publisher sends only the absent names. Existing uploaded assets
are kept unchanged and never overwritten or deleted, even if a rebuild produces
different bytes. This assumes existing assets are trusted; their presence alone
is not proof of their origin or signature.
- An empty/incomplete GitHub upload (`starter`, zero bytes, etc.) is an explicit
error. Inspect/remove only that failed upload manually before retrying. The helper
does not delete remote assets on your behalf.
- If one platform fails, the others continue and can populate the draft. The final
summary lists complete/missing files and platform results and fails if files remain
missing. A complete release is **still a draft**, never published automatically.
Use **Re-run failed jobs** or re-run the workflow on the **same commit** to resume.
Release filenames do not change the next day. Intermediate Actions artifact names
include `run_attempt`; diagnostics can be replaced inside the same run, but release
assets cannot. Expired intermediate artifacts may require rebuilding their platform.
The master's concurrency group serializes RC runs and does not cancel a running
release. GitHub can replace an older *pending* run with a newer pending run. Ref and
draft state are checked again before each publication. GitHub does not offer an
atomic "upload only while draft" operation: **do not publish the draft manually
until the workflow has finished**. Never publish it while jobs are still uploading.
## Signing and notes
The Windows release worker requires `SIGNPATH_ENABLED=true`, the production policy
and a valid production certificate. It fails **before compilation** if production
signing is disabled, rather than filling a draft with unsigned final Windows files.
Other platforms are independent. Self-signed integration tests remain exclusively in
the manually opted-in nightly workflow; see [SignPath setup](../signpath/README.md).
The footer is read from [`.github/release-footer.md`](../release-footer.md) at the
release commit. `{{CODE_SIGNING_POLICY_URL}}` becomes a link to the policy at that tag.
The helper owns only its delimited footer block: handwritten release notes before
and after it are preserved across retries. You still write the release notes and
publish the release manually.
## Offline verification and migration
```powershell
python -B -m unittest discover -s .github/scripts/tests -v
```
Tests use a fake API: no credentials, real refs/releases, upload or remote builds.
Install PyYAML to include the workflow-structure tests; core release tests use only
the standard library. Also run `actionlint` on the master, publisher and five workers,
plus the local SignPath/runtime packaging smoke tests where their Windows prerequisites
are installed. These do not replace five real platform builds or a production-signing
integration test. The master runs the offline tests before its first GitHub write.
`create_release.py` is now a **legacy manual recovery tool**, not part of the release
pipeline. Do not use it to assemble the new RC drafts: it selects Actions artifacts
by branch/date rather than exact commit. Its token logging is removed, but it still
uses a local PAT if explicitly invoked. No old release/tag or local release folder
is migrated, overwritten or deleted automatically. `create_releasemacos.py` is left
untouched.

439
.github/scripts/release.py vendored Normal file
View file

@ -0,0 +1,439 @@
"""Prepare/resume draft RC releases and publish exact CI outputs. No local PAT files.
Only prepare/upload access GitHub; stage is local. Unit tests use a fake API.
All commands fail closed on a moved tag or a published release.
"""
import argparse
import hashlib
import json
import mimetypes
import os
from pathlib import Path
import re
import shutil
import sys
import urllib.error
import urllib.parse
import urllib.request
import zipfile
PLATFORMS = ("windows", "macos-intel", "macos-arm", "linux-gtk3", "linux-gtk2")
MANIFEST = "release-manifest.json"
FOOTER_START = "<!-- superslicer-release-footer:start -->"
FOOTER_END = "<!-- superslicer-release-footer:end -->"
VERSION_RE = re.compile(r"\d+\.\d+\.\d+\.\d+(?:-[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*)?(?:\+[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*)?")
class ReleaseError(Exception):
pass
class ApiError(ReleaseError):
def __init__(self, status, method, path):
self.status = status
# Do not print request headers, tokens or response bodies.
super().__init__(f"GitHub {method} {path}: HTTP {status}")
def annotation(level, message):
text = str(message).replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
print(f"::{level}::{text}")
def validate_identity(product, version, sha):
if not re.fullmatch(r"[A-Za-z0-9_-]+", product):
raise ReleaseError("Invalid product name")
if not VERSION_RE.fullmatch(version) or "UNKNOWN" in version:
raise ReleaseError("Invalid RC version (expected numeric version and optional suffix, without UNKNOWN)")
if not re.fullmatch(r"[0-9a-f]{40}", sha):
raise ReleaseError("Expected a complete, lowercase commit SHA")
def read_version(path):
content = Path(path).read_text(encoding="utf-8-sig")
def get(name):
matches = re.findall(rf'^\s*set\(\s*{name}\s+"([^"\r\n]*)"\s*\)', content, re.MULTILINE)
if len(matches) != 1:
raise ReleaseError(f"Expected exactly one literal {name} in {path}")
return matches[0]
product = get("SLIC3R_APP_KEY")
version = get("SLIC3R_RC_VERSION_DOTS") + get("SLIC3R_VERSION_TAG").replace("+UNKNOWN", "")
validate_identity(product, version, "0" * 40)
return product, version
def asset_names(product, version):
validate_identity(product, version, "0" * 40)
return {
"windows": [f"{product}_{version}_win64.zip", f"{product}_{version}_win64.msi"],
"macos-intel": [f"{product}_{version}_macos.dmg"],
"macos-arm": [f"{product}_{version}_macos_arm.dmg"],
"linux-gtk3": [f"{product}-ubuntu_22.04-{version}.AppImage", f"{product}_{version}_linux64.tgz"],
"linux-gtk2": [f"{product}-ubuntu_22.04-gtk2-{version}.AppImage"],
}
class GitHub:
def __init__(self, repository, token):
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
raise ReleaseError("Invalid GitHub repository")
if not token:
raise ReleaseError("GH_TOKEN is required")
self.repository = repository
self.token = token
def request(self, method, path, data=None, file=None):
base = "https://uploads.github.com" if file is not None else "https://api.github.com"
headers = {
"Authorization": f"Bearer {self.token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "SuperSlicer-RC-release",
}
payload = None
if file is not None:
# Stream large DMG/AppImage payloads instead of reading them into memory.
headers["Content-Type"] = mimetypes.guess_type(file.name)[0] or "application/octet-stream"
headers["Content-Length"] = str(file.stat().st_size)
payload = file.open("rb")
elif data is not None:
headers["Content-Type"] = "application/json"
payload = json.dumps(data).encode("utf-8")
request = urllib.request.Request(base + f"/repos/{self.repository}" + path,
data=payload, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=300) as response:
raw = response.read()
return json.loads(raw) if raw else None
except urllib.error.HTTPError as error:
raise ApiError(error.code, method, path) from None
except urllib.error.URLError:
raise ReleaseError(f"GitHub {method} {path}: network error") from None
finally:
if file is not None:
payload.close()
def pages(self, path):
for page in range(1, 10001):
batch = self.request("GET", f"{path}?per_page=100&page={page}")
if not isinstance(batch, list):
raise ReleaseError(f"Expected a GitHub list at {path}")
yield from batch
if len(batch) < 100:
return
raise ReleaseError("GitHub pagination limit exceeded")
def tag_sha(self, tag):
obj = self.request("GET", "/git/ref/tags/" + urllib.parse.quote(tag, safe=""))["object"]
visited = set()
while obj["type"] == "tag":
if obj["sha"] in visited or len(visited) >= 16:
raise ReleaseError("Annotated tag cycle or excessive nesting")
visited.add(obj["sha"])
obj = self.request("GET", f'/git/tags/{obj["sha"]}')["object"]
if obj["type"] != "commit":
raise ReleaseError("Release tag does not identify a commit")
return obj["sha"]
def find_release(self, tag):
# Listing authenticated releases includes drafts; do not rely on /releases/tags.
matches = [release for release in self.pages("/releases") if release["tag_name"] == tag]
if len(matches) > 1:
raise ReleaseError(f"Multiple releases for tag {tag}")
return matches[0] if matches else None
def assets(self, release_id):
result = {}
for asset in self.pages(f"/releases/{release_id}/assets"):
if asset["name"] in result:
raise ReleaseError(f'Duplicate release asset: {asset["name"]}')
result[asset["name"]] = asset
return result
def require_draft(release, tag):
if release["tag_name"] != tag:
raise ReleaseError("Release ID does not belong to the expected tag")
if not release.get("draft"):
raise ReleaseError(f"Release {tag} is already public; refusing to modify it")
def require_tag(api, tag, sha):
if api.tag_sha(tag) != sha:
raise ReleaseError(f"Tag {tag} points to a different commit; increment the version, never move the tag")
def usable_asset(asset):
return asset.get("state") == "uploaded" and asset.get("size", 0) > 0
def inspect_assets(api, release_id, names):
assets = api.assets(release_id)
expected = {name for files in names.values() for name in files}
for name in expected & assets.keys():
if not usable_asset(assets[name]):
raise ReleaseError(f"Incomplete/empty asset {name}; remove that failed upload manually before retrying")
return assets
def managed_body(body, footer, repository, tag):
policy_url = f"https://github.com/{repository}/blob/{urllib.parse.quote(tag, safe='')}/doc/Code%20signing%20policy.md"
footer = footer.replace("{{CODE_SIGNING_POLICY_URL}}", policy_url).strip()
if not footer:
raise ReleaseError("Release footer must not be empty")
if FOOTER_START in footer or FOOTER_END in footer:
raise ReleaseError("Footer template must not contain managed delimiters")
block = f"{FOOTER_START}\n{footer}\n{FOOTER_END}"
body = body or ""
if body.count(FOOTER_START) != body.count(FOOTER_END) or body.count(FOOTER_START) > 1:
raise ReleaseError("Malformed managed footer in existing draft; preserve notes and repair manually")
if FOOTER_START in body:
start, end = body.index(FOOTER_START), body.index(FOOTER_END)
if end < start:
raise ReleaseError("Malformed managed footer order")
return body[:start] + block + body[end + len(FOOTER_END):]
return body.rstrip() + ("\n\n" if body.strip() else "") + block + "\n"
def prepare(api, product, version, sha, footer):
validate_identity(product, version, sha)
tag = version
# Check published releases before creating anything or modifying notes.
release = api.find_release(tag)
if release:
require_draft(release, tag)
try:
require_tag(api, tag, sha)
except ApiError as error:
if error.status != 404:
raise
if release:
raise ReleaseError("Existing draft has lost its tag; refusing to recreate it silently") from None
try:
api.request("POST", "/git/refs", {"ref": f"refs/tags/{tag}", "sha": sha})
except ApiError as conflict:
if conflict.status != 422:
raise
require_tag(api, tag, sha) # also handles concurrent tag creation
if not release:
body = managed_body("", footer, api.repository, tag)
try:
release = api.request("POST", "/releases", {
"tag_name": tag, "target_commitish": sha, "name": version,
"draft": True, "prerelease": "-" in version.split("+", 1)[0], "body": body,
})
except ApiError as conflict:
if conflict.status != 422:
raise
release = api.find_release(tag)
if not release:
raise
require_draft(release, tag)
require_tag(api, tag, sha)
names = asset_names(product, version)
assets = inspect_assets(api, release["id"], names)
body = managed_body(release.get("body"), footer, api.repository, tag)
if body != (release.get("body") or ""):
# Recheck immediately before a write, including publication by a human.
current = api.request("GET", f'/releases/{release["id"]}')
require_draft(current, tag)
require_tag(api, tag, sha)
body = managed_body(current.get("body"), footer, api.repository, tag)
api.request("PATCH", f'/releases/{release["id"]}', {"body": body})
result = {"product": product, "version": version, "tag": tag, "source_sha": sha,
"release_id": str(release["id"])}
for platform, files in names.items():
missing = [name for name in files if name not in assets]
result[platform.replace("-", "_")] = "true" if missing else "false"
if not missing:
annotation("warning", f"{platform}: all release assets already present; skipping build")
else:
print(f"{platform}: missing {', '.join(missing)}")
return result
def sha256(path):
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def stage(platform, product, version, sha, build, destination):
validate_identity(product, version, sha)
names = asset_names(product, version)[platform]
if destination.exists() and any(destination.iterdir()):
raise ReleaseError("Release staging directory is not empty")
destination.mkdir(parents=True, exist_ok=True)
if platform == "windows":
package = build / "package"
if not package.is_dir():
raise ReleaseError("Windows package directory is missing")
prefix = names[0][:-4]
files = sorted(path for path in package.rglob("*") if path.is_file())
if not files:
raise ReleaseError("Windows package is empty")
with zipfile.ZipFile(destination / names[0], "w", zipfile.ZIP_DEFLATED, allowZip64=True) as archive:
for path in files:
# No links/junctions to files outside the generated package.
if path.is_symlink() or not path.resolve().is_relative_to(package.resolve()):
raise ReleaseError(f"Unexpected link outside Windows package: {path.name}")
archive.write(path, prefix + "/" + path.relative_to(package).as_posix())
numeric = version.split("-", 1)[0].split("+", 1)[0]
sources = [(build / f"{product}_{numeric}.msi", names[1])]
elif platform.startswith("macos-"):
arch = "intel" if platform == "macos-intel" else "arm"
sources = [(build / f"{product}-macOS-{arch}.dmg", names[0])]
else:
toolkit = "GTK3" if platform == "linux-gtk3" else "GTK2"
sources = [(build / f"{product}-linux-x64-{toolkit}.AppImage", names[0])]
if platform == "linux-gtk3":
sources.append((build / f"{product}-linux-x64-GTK3.tgz", names[1]))
for source, target in sources:
if not source.is_file() or source.is_symlink() or source.stat().st_size == 0:
raise ReleaseError(f"Missing or empty distribution file: {source.name}")
shutil.copy2(source, destination / target)
manifest = {"schema": 1, "platform": platform, "product": product, "version": version,
"tag": version, "source_sha": sha, "files": []}
for name in names:
file = destination / name
manifest["files"].append({"name": name, "size": file.stat().st_size, "sha256": sha256(file)})
(destination / MANIFEST).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
def validate_payload(platform, product, version, sha, directory):
validate_identity(product, version, sha)
manifest = json.loads((directory / MANIFEST).read_text(encoding="utf-8"))
expected = {"schema": 1, "platform": platform, "product": product,
"version": version, "tag": version, "source_sha": sha}
if any(manifest.get(key) != value for key, value in expected.items()):
raise ReleaseError("CI asset manifest does not match this release/commit/platform")
names = asset_names(product, version)[platform]
entries = manifest.get("files", [])
if sorted(entry["name"] for entry in entries) != sorted(names):
raise ReleaseError("Unexpected or missing files in the CI manifest")
if {path.name for path in directory.iterdir()} != set(names) | {MANIFEST}:
raise ReleaseError("Unexpected or missing files in the downloaded CI artifact")
for entry in entries:
path = directory / entry["name"]
if not path.is_file() or path.is_symlink() or path.stat().st_size == 0:
raise ReleaseError(f"Missing/empty CI file: {entry['name']}")
if path.stat().st_size != entry["size"] or sha256(path) != entry["sha256"]:
raise ReleaseError(f"CI file hash mismatch: {entry['name']}")
return names
def upload(api, platform, product, version, sha, release_id, directory):
names = validate_payload(platform, product, version, sha, directory)
expected = asset_names(product, version)
for name in names:
require_tag(api, version, sha)
release = api.request("GET", f"/releases/{release_id}")
require_draft(release, version)
assets = inspect_assets(api, release_id, expected)
if name in assets:
annotation("warning", f"Asset {name} already exists; keeping it unchanged")
continue
file = directory / name
require_tag(api, version, sha)
require_draft(api.request("GET", f"/releases/{release_id}"), version)
try:
result = api.request("POST", f"/releases/{release_id}/assets?name=" + urllib.parse.quote(name, safe=""), file=file)
except ApiError as conflict:
if conflict.status != 422:
raise
# A concurrent uploader may have won; never delete or clobber it.
assets = inspect_assets(api, release_id, expected)
if name not in assets:
raise
annotation("warning", f"Asset {name} was uploaded concurrently; keeping it unchanged")
continue
if result.get("name") != name or not usable_asset(result) or result["size"] != file.stat().st_size:
raise ReleaseError(f"Upload did not complete correctly: {name}")
digest = result.get("digest")
if digest and digest != "sha256:" + sha256(file):
raise ReleaseError(f"GitHub upload digest mismatch: {name}")
print(f"Uploaded {name}")
def verify(api, product, version, sha, release_id, job_results=None):
validate_identity(product, version, sha)
require_tag(api, version, sha)
release = api.request("GET", f"/releases/{release_id}")
require_draft(release, version)
names = asset_names(product, version)
assets = inspect_assets(api, release_id, names)
lines = [f"## RC release `{version}`", f"Commit: `{sha}` — release remains **draft**.", "",
"| Platform | Assets | Job |", "| --- | --- | --- |"]
missing = []
for platform, files in names.items():
absent = [name for name in files if name not in assets]
missing.extend(absent)
job = (job_results or {}).get(platform.replace("-", "_"), {}).get("result", "unknown")
lines.append(f"| {platform} | {'Missing: ' + ', '.join(absent) if absent else 'Complete'} | {job} |")
summary = "\n".join(lines) + "\n"
print(summary)
if os.environ.get("GITHUB_STEP_SUMMARY"):
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as file:
file.write(summary)
if missing:
raise ReleaseError("Draft is incomplete: " + ", ".join(missing))
return summary
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=("prepare", "stage", "upload", "verify"))
parser.add_argument("--source-sha", required=True)
parser.add_argument("--version-file", type=Path, default=Path("version.inc"))
parser.add_argument("--footer-file", type=Path, default=Path(".github/release-footer.md"))
parser.add_argument("--output", type=Path)
parser.add_argument("--platform", choices=PLATFORMS)
parser.add_argument("--product")
parser.add_argument("--version")
parser.add_argument("--release-id", type=int)
parser.add_argument("--build-directory", type=Path, default=Path("build"))
parser.add_argument("--assets-directory", type=Path, default=Path("release-assets"))
args = parser.parse_args(argv)
if args.command == "prepare":
if os.environ.get("GITHUB_REF") != "refs/heads/rc":
raise ReleaseError("The release orchestrator must run on branch rc")
if os.environ.get("GITHUB_SHA") != args.source_sha:
raise ReleaseError("Release source must be the triggering workflow commit")
product, version = read_version(args.version_file)
else:
if not args.product or not args.version:
parser.error("--product and --version are required")
product, version = args.product, args.version
if args.command in ("stage", "upload") and not args.platform:
parser.error("--platform is required")
if args.command in ("upload", "verify") and not args.release_id:
parser.error("--release-id is required")
if args.command == "stage":
stage(args.platform, product, version, args.source_sha, args.build_directory, args.assets_directory)
return
api = GitHub(os.environ.get("GITHUB_REPOSITORY", ""), os.environ.get("GH_TOKEN", ""))
if args.command == "prepare":
result = prepare(api, product, version, args.source_sha, args.footer_file.read_text(encoding="utf-8"))
if args.output:
with args.output.open("a", encoding="utf-8") as file:
for key, value in result.items():
file.write(f"{key}={value}\n")
elif args.command == "upload":
upload(api, args.platform, product, version, args.source_sha, args.release_id, args.assets_directory)
else:
verify(api, product, version, args.source_sha, args.release_id,
json.loads(os.environ.get("RELEASE_JOB_RESULTS", "{}")))
if __name__ == "__main__":
try:
main()
except (ReleaseError, OSError, ValueError, KeyError, TypeError) as error:
annotation("error", error)
sys.exit(1)

616
.github/scripts/tests/test_release.py vendored Normal file
View file

@ -0,0 +1,616 @@
"""Offline tests: no real GitHub writes, tags, releases, tokens or build runs."""
import contextlib
import copy
import importlib.util
import io
import json
import os
from pathlib import Path
import tempfile
import types
import unittest
from unittest import mock
import urllib.parse
import zipfile
SPEC = importlib.util.spec_from_file_location("rc_release", Path(__file__).parents[1] / "release.py")
release = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(release)
ROOT = Path(__file__).resolve().parents[2]
SHA = "a" * 40
OTHER_SHA = "b" * 40
VERSION = "2.7.63.0-beta"
PRODUCT = "SuperSlicer"
FOOTER = "Free code signing provided by SignPath.io. [Policy]({{CODE_SIGNING_POLICY_URL}})"
class FakeGitHub(release.GitHub):
def __init__(self):
super().__init__("example/SuperSlicer", "unused-fake-token")
self.refs = {}
self.tag_objects = {}
self.releases = []
self.files = {}
self.calls = []
self.hook = None
def add_draft(self, tag=VERSION, sha=SHA, body="Manual notes", draft=True):
self.refs[tag] = {"type": "commit", "sha": sha}
item = {"id": len(self.releases) + 1, "tag_name": tag, "draft": draft, "body": body}
self.releases.append(item)
self.files[item["id"]] = []
return item
def add_asset(self, item, name, data=b"existing file", state="uploaded"):
asset = {"id": len(self.files[item["id"]]) + 1, "name": name, "size": len(data), "state": state,
"digest": "sha256:" + release.hashlib.sha256(data).hexdigest()}
self.files[item["id"]].append(asset)
return asset
def request(self, method, path, data=None, file=None):
self.calls.append((method, path, copy.deepcopy(data), file.name if file else None))
if self.hook:
self.hook(method, path, data, file)
parsed = urllib.parse.urlsplit(path)
query = urllib.parse.parse_qs(parsed.query)
endpoint = parsed.path
result = None
if method == "GET" and endpoint.startswith("/git/ref/tags/"):
tag = urllib.parse.unquote(endpoint[len("/git/ref/tags/"):])
if tag not in self.refs:
raise release.ApiError(404, method, path)
result = {"object": self.refs[tag]}
elif method == "GET" and endpoint.startswith("/git/tags/"):
result = {"object": self.tag_objects[endpoint.rsplit("/", 1)[1]]}
elif method == "POST" and endpoint == "/git/refs":
tag = data["ref"][len("refs/tags/"):]
if tag in self.refs:
raise release.ApiError(422, method, path)
self.refs[tag] = {"type": "commit", "sha": data["sha"]}
result = {"object": self.refs[tag]}
elif method == "GET" and endpoint == "/releases":
start = (int(query["page"][0]) - 1) * 100
result = self.releases[start:start + 100]
elif method == "POST" and endpoint == "/releases":
if any(item["tag_name"] == data["tag_name"] for item in self.releases):
raise release.ApiError(422, method, path)
item = {**data, "id": len(self.releases) + 1}
self.releases.append(item)
self.files[item["id"]] = []
result = item
elif endpoint.startswith("/releases/"):
pieces = endpoint.split("/")
identifier = int(pieces[2])
item = next(item for item in self.releases if item["id"] == identifier)
if len(pieces) == 3:
if method == "PATCH":
item.update(data)
result = item
elif pieces[3] == "assets":
if method == "GET":
start = (int(query["page"][0]) - 1) * 100
result = self.files[identifier][start:start + 100]
elif method == "POST":
name = query["name"][0]
if any(asset["name"] == name for asset in self.files[identifier]):
raise release.ApiError(422, method, path)
result = self.add_asset(item, name, file.read_bytes())
if result is None:
raise AssertionError(f"Unhandled fake request: {method} {path}")
return copy.deepcopy(result)
def writes(self):
return [call for call in self.calls if call[0] != "GET"]
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.api = FakeGitHub()
self.folder = tempfile.TemporaryDirectory()
self.root = Path(self.folder.name)
self.output = io.StringIO()
self.redirect = contextlib.redirect_stdout(self.output)
self.redirect.__enter__()
def tearDown(self):
self.redirect.__exit__(None, None, None)
self.folder.cleanup()
def prepare(self):
return release.prepare(self.api, PRODUCT, VERSION, SHA, FOOTER)
def payload(self, platform):
build = self.root / "build"
build.mkdir(exist_ok=True)
if platform == "windows":
(build / "package/mesa").mkdir(parents=True)
(build / "package/superslicer.exe").write_bytes(b"verified application fixture")
(build / "package/mesa/opengl32.dll").write_bytes(b"upstream fixture")
(build / "SuperSlicer_2.7.63.0.msi").write_bytes(b"verified installer fixture")
elif platform.startswith("macos-"):
arch = "intel" if platform == "macos-intel" else "arm"
(build / f"SuperSlicer-macOS-{arch}.dmg").write_bytes(b"disk image fixture")
else:
toolkit = "GTK2" if platform == "linux-gtk2" else "GTK3"
(build / f"SuperSlicer-linux-x64-{toolkit}.AppImage").write_bytes(b"AppImage fixture")
(build / f"SuperSlicer-linux-x64-{toolkit}.tgz").write_bytes(b"archive fixture")
destination = self.root / platform
release.stage(platform, PRODUCT, VERSION, SHA, build, destination)
return destination
def test_version_strips_unknown_without_date_or_numeric_corruption(self):
product, version = release.read_version(ROOT.parent / "version.inc")
self.assertEqual(PRODUCT, product)
self.assertNotIn("UNKNOWN", version)
file = self.root / "version.inc"
file.write_text('set(SLIC3R_APP_KEY "SuperSlicer")\nset(SLIC3R_RC_VERSION_DOTS "2.7.63.12")\nset(SLIC3R_VERSION_TAG "-beta2+UNKNOWN")\n')
self.assertEqual((PRODUCT, "2.7.63.12-beta2"), release.read_version(file))
def test_all_seven_names_stable_compatible_with_updater(self):
names = release.asset_names(PRODUCT, VERSION)
self.assertEqual(7, sum(map(len, names.values())))
self.assertIn("win", names["windows"][0])
self.assertTrue(names["windows"][1].endswith(".msi"))
self.assertIn("macos", names["macos-intel"][0])
self.assertNotIn("arm", names["macos-intel"][0])
self.assertIn("macos_arm", names["macos-arm"][0])
self.assertIn("ubuntu", names["linux-gtk3"][0])
self.assertIn("gtk2", names["linux-gtk2"][0])
self.assertEqual(names, release.asset_names(PRODUCT, VERSION))
def test_new_tag_and_draft_created_at_exact_commit(self):
result = self.prepare()
self.assertEqual(SHA, self.api.tag_sha(VERSION))
self.assertTrue(self.api.releases[0]["draft"])
self.assertTrue(self.api.releases[0]["prerelease"])
self.assertEqual(SHA, self.api.releases[0]["target_commitish"])
self.assertEqual(VERSION, result["tag"])
self.assertTrue(all(result[platform.replace("-", "_")] == "true" for platform in release.PLATFORMS))
self.assertIn(f"/blob/{VERSION}/doc/", self.api.releases[0]["body"])
def test_tag_conflict_fails_without_writes(self):
self.api.refs[VERSION] = {"type": "commit", "sha": OTHER_SHA}
with self.assertRaisesRegex(release.ReleaseError, "different commit"):
self.prepare()
self.assertEqual([], self.api.writes())
def test_duplicate_releases_and_assets_fail_without_writes(self):
draft = self.api.add_draft()
self.api.add_draft()
with self.assertRaisesRegex(release.ReleaseError, "Multiple releases"):
self.prepare()
self.api.releases.pop()
name = release.asset_names(PRODUCT, VERSION)["macos-arm"][0]
self.api.add_asset(draft, name)
self.api.add_asset(draft, name)
with self.assertRaisesRegex(release.ReleaseError, "Duplicate release asset"):
self.prepare()
self.assertEqual([], self.api.writes())
def test_annotated_tag_resolves_to_matching_commit(self):
self.api.refs[VERSION] = {"type": "tag", "sha": "c" * 40}
self.api.tag_objects["c" * 40] = {"type": "tag", "sha": "d" * 40}
self.api.tag_objects["d" * 40] = {"type": "commit", "sha": SHA}
self.prepare()
self.assertFalse(any(call[1] == "/git/refs" for call in self.api.writes()))
def test_tag_cycle_fails(self):
self.api.refs[VERSION] = {"type": "tag", "sha": "c" * 40}
self.api.tag_objects["c" * 40] = {"type": "tag", "sha": "c" * 40}
with self.assertRaisesRegex(release.ReleaseError, "cycle"):
self.prepare()
def test_public_release_fails_before_any_write(self):
self.api.add_draft(draft=False)
with self.assertRaisesRegex(release.ReleaseError, "already public"):
self.prepare()
self.assertEqual([], self.api.writes())
def test_existing_draft_missing_its_tag_fails(self):
self.api.add_draft()
del self.api.refs[VERSION]
with self.assertRaisesRegex(release.ReleaseError, "lost its tag"):
self.prepare()
self.assertEqual([], self.api.writes())
def test_full_platform_skipped_partial_platform_rebuilt(self):
draft = self.api.add_draft()
names = release.asset_names(PRODUCT, VERSION)
self.api.add_asset(draft, names["windows"][0])
self.api.add_asset(draft, names["macos-intel"][0])
result = self.prepare()
self.assertEqual("true", result["windows"])
self.assertEqual("false", result["macos_intel"])
self.assertIn("::warning::macos-intel", self.output.getvalue())
def test_complete_release_skips_all_five_builds(self):
draft = self.api.add_draft()
for files in release.asset_names(PRODUCT, VERSION).values():
for name in files:
self.api.add_asset(draft, name)
result = self.prepare()
self.assertTrue(all(result[platform.replace("-", "_")] == "false" for platform in release.PLATFORMS))
def test_incomplete_asset_is_explicit_error_not_overwritten(self):
draft = self.api.add_draft()
self.api.add_asset(draft, release.asset_names(PRODUCT, VERSION)["windows"][0], b"", state="starter")
with self.assertRaisesRegex(release.ReleaseError, "Incomplete/empty"):
self.prepare()
self.assertEqual([], self.api.writes())
def test_repeated_prepare_preserves_notes_and_footer_is_not_duplicated(self):
draft = self.api.add_draft(body="User-written notes\n")
self.prepare()
body = draft["body"]
writes = len(self.api.writes())
self.prepare()
self.assertEqual(body, draft["body"])
self.assertEqual(writes, len(self.api.writes()))
self.assertTrue(body.startswith("User-written notes"))
self.assertEqual(1, body.count(release.FOOTER_START))
def test_managed_footer_update_preserves_text_on_both_sides(self):
body = f"Manual prefix\n{release.FOOTER_START}\nold\n{release.FOOTER_END}\nManual suffix"
result = release.managed_body(body, FOOTER, self.api.repository, VERSION)
self.assertTrue(result.startswith("Manual prefix\n"))
self.assertTrue(result.endswith("\nManual suffix"))
self.assertNotIn("\nold\n", result)
def test_prepare_preserves_notes_changed_during_asset_listing(self):
draft = self.api.add_draft()
def edit_notes(method, path, data, file):
if method == "GET" and "/assets?" in path:
draft["body"] = "Notes edited during preparation\n"
self.api.hook = edit_notes
self.prepare()
self.assertTrue(draft["body"].startswith("Notes edited during preparation\n"))
def test_prepare_rejects_publication_during_asset_listing(self):
draft = self.api.add_draft()
def publish(method, path, data, file):
if method == "GET" and "/assets?" in path:
draft["draft"] = False
self.api.hook = publish
with self.assertRaisesRegex(release.ReleaseError, "already public"):
self.prepare()
self.assertEqual([], self.api.writes())
def test_malformed_footer_fails(self):
with self.assertRaisesRegex(release.ReleaseError, "Malformed"):
release.managed_body(release.FOOTER_START, FOOTER, self.api.repository, VERSION)
def test_pagination_for_drafts_and_assets(self):
for index in range(100):
self.api.add_draft(tag=f"old-{index}")
draft = self.api.add_draft()
for index in range(100):
self.api.add_asset(draft, f"other-{index}.txt")
self.api.add_asset(draft, release.asset_names(PRODUCT, VERSION)["macos-arm"][0])
result = self.prepare()
self.assertEqual(str(draft["id"]), result["release_id"])
self.assertEqual("false", result["macos_arm"])
def test_concurrent_tag_and_release_creation_reuses_matching_draft(self):
def race(method, path, data, file):
if method == "POST" and path == "/git/refs":
self.api.refs[VERSION] = {"type": "commit", "sha": SHA}
if method == "POST" and path == "/releases":
self.api.add_draft()
self.api.hook = race
result = self.prepare()
self.assertEqual("1", result["release_id"])
self.assertEqual(1, len(self.api.releases))
def test_all_platforms_stage_exact_raw_files_and_manifest(self):
for platform in release.PLATFORMS:
with self.subTest(platform=platform):
directory = self.payload(platform)
names = release.validate_payload(platform, PRODUCT, VERSION, SHA, directory)
self.assertEqual(release.asset_names(PRODUCT, VERSION)[platform], names)
if platform == "windows":
with zipfile.ZipFile(directory / names[0]) as zipped:
self.assertIn(f"SuperSlicer_{VERSION}_win64/mesa/opengl32.dll", zipped.namelist())
self.assertEqual(b"verified installer fixture", (directory / names[1]).read_bytes())
def test_payload_tampering_missing_files_and_wrong_commit_fail(self):
directory = self.payload("macos-arm")
path = directory / release.asset_names(PRODUCT, VERSION)["macos-arm"][0]
path.write_bytes(b"tampered")
with self.assertRaisesRegex(release.ReleaseError, "hash mismatch"):
release.validate_payload("macos-arm", PRODUCT, VERSION, SHA, directory)
with self.assertRaisesRegex(release.ReleaseError, "does not match"):
release.validate_payload("macos-arm", PRODUCT, VERSION, OTHER_SHA, directory)
path.unlink()
with self.assertRaisesRegex(release.ReleaseError, "Unexpected or missing"):
release.validate_payload("macos-arm", PRODUCT, VERSION, SHA, directory)
def test_staging_rejects_missing_empty_files_and_nonempty_destination(self):
build = self.root / "missing-build"
build.mkdir()
destination = self.root / "stage"
with self.assertRaisesRegex(release.ReleaseError, "Missing or empty"):
release.stage("macos-arm", PRODUCT, VERSION, SHA, build, destination)
(build / "SuperSlicer-macOS-arm.dmg").write_bytes(b"")
with self.assertRaisesRegex(release.ReleaseError, "Missing or empty"):
release.stage("macos-arm", PRODUCT, VERSION, SHA, build, destination)
(destination / "preserve.txt").write_text("keep")
with self.assertRaisesRegex(release.ReleaseError, "not empty"):
release.stage("macos-arm", PRODUCT, VERSION, SHA, build, destination)
self.assertEqual("keep", (destination / "preserve.txt").read_text())
def test_payload_extra_file_is_rejected(self):
directory = self.payload("macos-intel")
(directory / "unexpected.txt").write_text("not part of release")
with self.assertRaisesRegex(release.ReleaseError, "Unexpected or missing"):
release.validate_payload("macos-intel", PRODUCT, VERSION, SHA, directory)
def test_manifest_path_traversal_is_rejected_before_open(self):
directory = self.payload("macos-intel")
path = directory / release.MANIFEST
manifest = json.loads(path.read_text())
manifest["files"][0]["name"] = "../outside"
path.write_text(json.dumps(manifest))
with self.assertRaisesRegex(release.ReleaseError, "Unexpected or missing"):
release.validate_payload("macos-intel", PRODUCT, VERSION, SHA, directory)
def test_upload_only_missing_asset_never_overwrites_existing(self):
draft = self.api.add_draft()
names = release.asset_names(PRODUCT, VERSION)["windows"]
first = copy.deepcopy(self.api.add_asset(draft, names[0]))
directory = self.payload("windows")
release.upload(self.api, "windows", PRODUCT, VERSION, SHA, draft["id"], directory)
self.assertEqual(first, self.api.files[draft["id"]][0])
uploaded = [call[3] for call in self.api.writes() if call[3]]
self.assertEqual([names[1]], uploaded)
self.assertTrue(all(call[0] != "DELETE" for call in self.api.calls))
def test_repeated_upload_does_not_upload_again(self):
draft = self.api.add_draft()
directory = self.payload("linux-gtk3")
for _ in range(2):
release.upload(self.api, "linux-gtk3", PRODUCT, VERSION, SHA, draft["id"], directory)
self.assertEqual(2, len([call for call in self.api.writes() if call[3]]))
def test_upload_rejects_public_release_or_moved_tag(self):
draft = self.api.add_draft(draft=False)
directory = self.payload("macos-arm")
with self.assertRaisesRegex(release.ReleaseError, "already public"):
release.upload(self.api, "macos-arm", PRODUCT, VERSION, SHA, draft["id"], directory)
draft["draft"] = True
self.api.refs[VERSION]["sha"] = OTHER_SHA
with self.assertRaisesRegex(release.ReleaseError, "different commit"):
release.upload(self.api, "macos-arm", PRODUCT, VERSION, SHA, draft["id"], directory)
self.assertEqual([], self.api.writes())
def test_upload_rejects_wrong_release_id_before_writing(self):
draft = self.api.add_draft(tag="another-version")
self.api.refs[VERSION] = {"type": "commit", "sha": SHA}
directory = self.payload("macos-arm")
with self.assertRaisesRegex(release.ReleaseError, "expected tag"):
release.upload(self.api, "macos-arm", PRODUCT, VERSION, SHA, draft["id"], directory)
self.assertEqual([], self.api.writes())
def test_upload_response_digest_mismatch_fails_without_deleting(self):
draft = self.api.add_draft()
directory = self.payload("macos-arm")
original_request = self.api.request
def wrong_digest(method, path, data=None, file=None):
result = original_request(method, path, data, file)
if file is not None:
result["digest"] = "sha256:" + "0" * 64
return result
self.api.request = wrong_digest
with self.assertRaisesRegex(release.ReleaseError, "digest mismatch"):
release.upload(self.api, "macos-arm", PRODUCT, VERSION, SHA, draft["id"], directory)
self.assertFalse(any(call[0] == "DELETE" for call in self.api.calls))
def test_upload_rechecks_after_asset_listing(self):
draft = self.api.add_draft()
directory = self.payload("macos-arm")
def publish(method, path, data, file):
if method == "GET" and "/assets?" in path:
draft["draft"] = False
self.api.hook = publish
with self.assertRaisesRegex(release.ReleaseError, "already public"):
release.upload(self.api, "macos-arm", PRODUCT, VERSION, SHA, draft["id"], directory)
self.assertEqual([], self.api.writes())
def test_concurrent_asset_upload_does_not_clobber(self):
draft = self.api.add_draft()
directory = self.payload("macos-arm")
def race(method, path, data, file):
if method == "POST" and "/assets?" in path:
self.api.add_asset(draft, file.name)
self.api.hook = race
release.upload(self.api, "macos-arm", PRODUCT, VERSION, SHA, draft["id"], directory)
self.assertEqual(1, len(self.api.files[draft["id"]]))
self.assertIn("uploaded concurrently", self.output.getvalue())
def test_verify_reports_all_missing_platforms_even_if_one_job_failed(self):
draft = self.api.add_draft()
self.api.add_asset(draft, release.asset_names(PRODUCT, VERSION)["macos-arm"][0])
with self.assertRaisesRegex(release.ReleaseError, "Draft is incomplete"):
release.verify(self.api, PRODUCT, VERSION, SHA, draft["id"],
{"windows": {"result": "failure"}, "macos_arm": {"result": "success"}})
self.assertIn("failure", self.output.getvalue())
self.assertIn("macos-arm | Complete", self.output.getvalue())
def test_verify_full_draft_does_not_publish(self):
draft = self.api.add_draft()
for files in release.asset_names(PRODUCT, VERSION).values():
for name in files:
self.api.add_asset(draft, name)
release.verify(self.api, PRODUCT, VERSION, SHA, draft["id"])
self.assertTrue(draft["draft"])
self.assertEqual([], self.api.writes())
def test_prepare_cli_rejects_wrong_branch_and_commit_before_api(self):
with mock.patch.dict(os.environ, {"GITHUB_REF": "refs/heads/master", "GITHUB_SHA": SHA}):
with self.assertRaisesRegex(release.ReleaseError, "branch rc"):
release.main(["prepare", "--source-sha", SHA])
with mock.patch.dict(os.environ, {"GITHUB_REF": "refs/heads/rc", "GITHUB_SHA": OTHER_SHA}):
with self.assertRaisesRegex(release.ReleaseError, "triggering"):
release.main(["prepare", "--source-sha", SHA])
def test_invalid_versions_and_paths_fail(self):
for version in ("2.7.63.0+UNKNOWN", "../2.7.63", "2.7.63", "2.7.63.0\nINJECTED=1"):
with self.subTest(version=version), self.assertRaises(release.ReleaseError):
release.asset_names(PRODUCT, version)
with self.assertRaises(release.ReleaseError):
release.validate_identity("../../SuperSlicer", VERSION, SHA)
class HttpBoundaryTests(unittest.TestCase):
"""Exercise the real HTTP adapter with urlopen mocked; no network or credentials."""
def setUp(self):
self.api = release.GitHub("example/SuperSlicer", "test-only-placeholder")
def response(self, payload):
response = mock.MagicMock()
response.__enter__.return_value.read.return_value = json.dumps(payload).encode()
return response
def test_json_request_uses_api_endpoint_and_token_header(self):
response = self.response({"id": 42})
with mock.patch.object(release.urllib.request, "urlopen", return_value=response) as urlopen:
self.assertEqual({"id": 42}, self.api.request("POST", "/releases", {"draft": True}))
request = urlopen.call_args.args[0]
self.assertEqual("https://api.github.com/repos/example/SuperSlicer/releases", request.full_url)
self.assertEqual("POST", request.method)
self.assertEqual({"draft": True}, json.loads(request.data))
self.assertEqual("Bearer test-only-placeholder", request.get_header("Authorization"))
self.assertNotIn("test-only-placeholder", request.full_url)
def test_upload_streams_file_with_content_length_and_closes_it(self):
with tempfile.TemporaryDirectory() as folder:
file = Path(folder) / "fixture.dmg"
file.write_bytes(b"disk image fixture")
def send(request, timeout):
self.assertEqual("https://uploads.github.com/repos/example/SuperSlicer/releases/1/assets?name=fixture.dmg", request.full_url)
self.assertNotIsInstance(request.data, bytes)
self.assertFalse(request.data.closed)
self.assertEqual(str(file.stat().st_size), request.get_header("Content-length"))
self.assertEqual(file.read_bytes(), request.data.read())
return self.response({"state": "uploaded"})
with mock.patch.object(release.urllib.request, "urlopen", side_effect=send) as urlopen:
self.api.request("POST", "/releases/1/assets?name=fixture.dmg", file=file)
self.assertTrue(urlopen.call_args.args[0].data.closed)
def test_http_failure_redacts_response_and_closes_upload(self):
with tempfile.TemporaryDirectory() as folder:
file = Path(folder) / "fixture.msi"
file.write_bytes(b"installer fixture")
error = release.urllib.error.HTTPError("https://api.github.com", 403,
"test-only-placeholder", {}, io.BytesIO(b"private response"))
try:
with mock.patch.object(release.urllib.request, "urlopen", side_effect=error) as urlopen:
with self.assertRaises(release.ApiError) as caught:
self.api.request("POST", "/releases/1/assets?name=fixture.msi", file=file)
self.assertEqual(403, caught.exception.status)
self.assertNotIn("test-only-placeholder", str(caught.exception))
self.assertNotIn("private response", str(caught.exception))
self.assertTrue(urlopen.call_args.args[0].data.closed)
finally:
error.close()
def test_network_failure_redacts_reason(self):
error = release.urllib.error.URLError("private diagnostic with test-only-placeholder")
with mock.patch.object(release.urllib.request, "urlopen", side_effect=error):
with self.assertRaisesRegex(release.ReleaseError, "network error") as caught:
self.api.request("GET", "/releases")
self.assertNotIn("test-only-placeholder", str(caught.exception))
try:
import yaml
except ImportError:
yaml = None
@unittest.skipIf(yaml is None, "Install PyYAML to validate workflow contracts")
class WorkflowContractTests(unittest.TestCase):
def workflow(self, name):
return yaml.load((ROOT / "workflows" / name).read_text(encoding="utf-8"), Loader=yaml.BaseLoader)
def test_single_rc_trigger_and_pinned_checkouts(self):
master = self.workflow("release_rc.yml")
self.assertEqual(["rc"], master["on"]["push"]["branches"])
self.assertEqual("false", master["concurrency"]["cancel-in-progress"])
for name in ("ccpp_win_rc.yml", "ccpp_mac_rc.yml", "ccpp_mac_arm_rc.yml", "ccpp_ubuntu_gtk3_rc.yml", "ccpp_ubuntu_gtk2_rc.yml"):
workflow = self.workflow(name)
self.assertIn("workflow_call", workflow["on"])
self.assertNotIn("rc", (workflow["on"].get("push") or {}).get("branches", []))
for job_name, job in workflow["jobs"].items():
if job_name == "publish":
self.assertIn("artifact_id", job["with"])
continue
permissions = job.get("permissions", workflow.get("permissions"))
self.assertEqual("read", permissions["contents"])
for step in job.get("steps", []):
if step.get("uses", "").startswith("actions/checkout"):
self.assertEqual("${{ inputs.source_sha || github.sha }}", step["with"]["ref"])
self.assertEqual("false", step["with"]["persist-credentials"])
def test_windows_publication_requires_production_signing(self):
workflow = self.workflow("ccpp_win_rc.yml")
steps = workflow["jobs"]["build_dep"]["steps"]
guard = next(step for step in steps if step.get("name") == "Require production signing for release assets")
self.assertIn("inputs.release_id != ''", guard["if"])
self.assertIn("env.SIGNPATH_ENABLED != 'true'", guard["if"])
self.assertIn("throw", guard["run"])
build = workflow["jobs"]["build"]["steps"]
names = [step.get("name") for step in build]
self.assertLess(names.index("verify and replace signed msi"), names.index("Stage signed release files and integrity manifest"))
version = next(step["run"] for step in build if step.get("name") == "Generate installer version")
self.assertNotIn("-replace", version)
def test_rc_signing_opt_in_truth_table(self):
workflow = self.workflow("ccpp_win_rc.yml")
expression = workflow["env"]["SIGNPATH_ENABLED"][3:-2].replace("&&", " and ").replace("||", " or ")
for enabled in ("false", "true"):
for event in ("push", "workflow_dispatch"):
for sign in (False, True):
for release_id in ("", "42"):
result = eval(expression, {"__builtins__": {}}, {
"vars": types.SimpleNamespace(SIGNPATH_ENABLED=enabled),
"github": types.SimpleNamespace(event_name=event),
"inputs": types.SimpleNamespace(sign=sign, release_id=release_id),
})
expected = enabled == "true" and (release_id != "" or (event == "workflow_dispatch" and sign))
self.assertEqual("true" if expected else "false", result)
def test_nightly_still_manual_test_only_and_dated(self):
nightly = self.workflow("ccpp_win.yml")
expression = nightly["env"]["SIGNPATH_ENABLED"][3:-2].replace("&&", " and ").replace("||", " or ")
for event in ("push", "workflow_dispatch"):
for sign in (False, True):
result = eval(expression, {"__builtins__": {}}, {
"github": types.SimpleNamespace(event_name=event),
"inputs": types.SimpleNamespace(sign=sign),
})
self.assertEqual("true" if event == "workflow_dispatch" and sign else "false", result)
commands = "\n".join(step.get("run", "") for step in nightly["jobs"]["build"]["steps"])
self.assertIn("[datetime]::Today", commands)
self.assertIn("UNKNOWN", commands)
self.assertEqual("${{ vars.SIGNPATH_TEST_SIGNING_POLICY_SLUG }}", nightly["env"]["SIGNPATH_SIGNING_POLICY_SLUG"])
def test_publisher_uses_exact_artifact_id_and_separate_write_permissions(self):
publisher = self.workflow("release_upload.yml")
job = publisher["jobs"]["upload"]
self.assertEqual("write", job["permissions"]["contents"])
download = next(step for step in job["steps"] if step.get("uses", "").startswith("actions/download-artifact"))
self.assertEqual("${{ inputs.artifact_id }}", download["with"]["artifact-ids"])
self.assertNotIn("pattern", download["with"])
def test_summary_can_read_drafts_but_uses_read_only_command(self):
summary = self.workflow("release_rc.yml")["jobs"]["summary"]
self.assertEqual("write", summary["permissions"]["contents"])
commands = [step["run"] for step in summary["steps"] if "run" in step]
self.assertEqual(1, len(commands))
self.assertIn("release.py verify", commands[0])
if __name__ == "__main__":
unittest.main()

View file

@ -1,6 +1,8 @@
# Windows code signing (SignPath)
Release signing is in `.github/workflows/ccpp_win_rc.yml` (`Release` binaries).
It is called by the [RC release orchestrator](../release/README.md), which prepares
the version tag and draft and only builds missing platforms.
`.github/workflows/ccpp_win.yml` (`RelWithDebInfo`) supports **manual test signing only**.
`ccpp_win_debug.yml` is not integrated. Signing is **off by default**.
@ -9,7 +11,7 @@ Release signing is in `.github/workflows/ccpp_win_rc.yml` (`Release` binaries).
| Ordinary nightly push (including `debug_win`) | Never submits a signing request |
| Manually dispatched nightly, `sign` unchecked | Ordinary unsigned build |
| Manually dispatched nightly, `sign` checked | Uses the pinned self-signed certificate and test policy; two requests |
| Push to `rc` | Production signing only if `SIGNPATH_ENABLED=true`; otherwise unsigned |
| Push to `rc` | The master calls Windows when its release files are missing; requires production signing, otherwise the Windows worker fails without publishing unsigned release files |
| RC workflow on `debug_win` | Never signs automatically |
| Manually dispatched RC workflow | Signs only with `sign` checked **and** `SIGNPATH_ENABLED=true` |
@ -45,7 +47,12 @@ In the selected organization, create or check these objects. Slugs must match CI
| Production Signing Policy | e.g. `release-signing` | assign the production certificate and put the slug in `SIGNPATH_SIGNING_POLICY_SLUG`; authorize the submitter and require maintainer approval |
| Artifact Configuration | `windows-binaries` | content of `artifact-configuration-binaries.xml` |
| Artifact Configuration | `windows-msi` | content of `artifact-configuration-msi.xml` |
| API token | — | user profile → API tokens, stored as the `SIGNPATH_API_TOKEN` GitHub secret |
| API token | — | token of the project's CI user, stored as the `SIGNPATH_API_TOKEN` GitHub secret |
For OSS trusted-build verification, use the existing **CI builds** technical user as
Submitter. Do not substitute an interactive administrator's personal token. A personal
account can remain an Approver; a CI user does not need a dashboard login or email
confirmation to authenticate with its token.
Use MFA for both GitHub and SignPath accounts. Restrict the project's allowed source
repository/branches to the intended SuperSlicer builds. When requested by SignPath's
@ -117,7 +124,7 @@ The MSI is signed in a second request, after `light.exe`. See the
## First run
`wait-for-completion: true` means CI waits for the signing request to be approved.
If the signing policy requires manual approval, open SignPath → *My Requests* and approve
If the signing policy requires manual approval, open SignPath → *Browse* and approve
while the workflow is running. If it times out, raise
`wait-for-completion-timeout-in-seconds` in the workflow.
@ -135,6 +142,11 @@ left by an earlier attempt. **Re-running an explicitly signed build submits new
requests**, consumes quota again and still requires approval. SignPath pipeline policies
may disallow re-runs (or cap supported attempts); use a fresh workflow run if required.
For RC draft publication, an already complete Windows platform is skipped before
building or submitting a signing request. A partial draft may rebuild Windows and
submit both signing requests again, but keeps existing release assets unchanged.
The orchestrator always keeps the tag's original SHA and never modifies a public release.
Before requesting the production review, link the [code signing policy](../../doc/Code%20signing%20policy.md)
from the actual project home/download/release pages as well, and confirm the listed
team roles and privacy statements accurately describe the project.

View file

@ -1,16 +1,34 @@
name: C/C++ Release candidate arm macos
on:
push:
branches:
- rc
workflow_dispatch:
workflow_call:
inputs:
source_sha:
type: string
required: true
release_version:
type: string
required: true
release_id:
type: string
required: true
product:
type: string
required: true
permissions:
contents: read
jobs:
build_dep:
runs-on: macos-15
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- name: New cmake
run: cmake --version
- name: Setup cmake
@ -38,7 +56,7 @@ jobs:
run: mkdir deps/build
- name: dep cache
id: cache-action
uses: actions/cache@v3
uses: actions/cache@v4
with:
key: macos_arm_2.7.63
path: deps/build/destdir
@ -49,9 +67,14 @@ jobs:
build:
runs-on: macos-15
needs: build_dep
outputs:
release_artifact_id: ${{ steps.release-artifact.outputs.artifact-id }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- name: New cmake
run: cmake --version
- name: Setup cmake
@ -62,7 +85,7 @@ jobs:
run: cmake --version
- name: dep cache
id: cache-action
uses: actions/cache@v3
uses: actions/cache@v4
with:
key: macos_arm_2.7.63
path: deps/build/destdir
@ -73,8 +96,44 @@ jobs:
with:
name: rc_${{ github.event.repository.name }}-macOS-arm.dmg
path: build/${{ github.event.repository.name }}-macOS-arm.dmg
if-no-files-found: error
overwrite: true
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: rc_${{ github.event.repository.name }}-macOS-arm.tgz
path: build/${{ github.event.repository.name }}-macOS-arm.tgz
if-no-files-found: error
overwrite: true
- name: Stage named release files and integrity manifest
if: inputs.release_id != ''
env:
RELEASE_SHA: ${{ inputs.source_sha }}
RELEASE_VERSION: ${{ inputs.release_version }}
PRODUCT: ${{ inputs.product }}
run: >-
python3 .github/scripts/release.py stage --platform macos-arm
--source-sha "$RELEASE_SHA" --version "$RELEASE_VERSION" --product "$PRODUCT"
- name: Upload exact files for the draft publisher
id: release-artifact
if: inputs.release_id != ''
uses: actions/upload-artifact@v4
with:
name: release-macos-arm-${{ github.run_attempt }}
path: release-assets/
if-no-files-found: error
publish:
needs: build
if: inputs.release_id != ''
permissions:
contents: write
actions: read
uses: ./.github/workflows/release_upload.yml
with:
source_sha: ${{ inputs.source_sha }}
release_version: ${{ inputs.release_version }}
release_id: ${{ inputs.release_id }}
product: ${{ inputs.product }}
platform: macos-arm
artifact_id: ${{ needs.build.outputs.release_artifact_id }}

View file

@ -3,15 +3,35 @@ name: C/C++ Release candidate macos
on:
push:
branches:
- rc
- rc-macintel
workflow_dispatch:
workflow_call:
inputs:
source_sha:
type: string
required: true
release_version:
type: string
required: true
release_id:
type: string
required: true
product:
type: string
required: true
permissions:
contents: read
jobs:
build_dep:
runs-on: macos-15-intel
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- name: New cmake
run: cmake --version
- name: Setup cmake
@ -41,7 +61,7 @@ jobs:
run: mkdir deps/build
- name: dep cache
id: cache-action
uses: actions/cache@v3
uses: actions/cache@v4
with:
key: macos_intel_2.7.63
path: deps/build/destdir
@ -52,9 +72,14 @@ jobs:
build:
runs-on: macos-15-intel
needs: build_dep
outputs:
release_artifact_id: ${{ steps.release-artifact.outputs.artifact-id }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- name: New cmake
run: cmake --version
- name: Setup cmake
@ -71,7 +96,7 @@ jobs:
run: autoconf --version
- name: update automake for mpfr
run: |
curl -O -L http://ftpmirror.gnu.org/automake/automake-1.16.5.tar.gz
curl -O -L https://github.com/supermerill/SuperSlicer_deps/releases/download/automake/automake-1.16.5.tar.gz
tar -xzf automake-1.16.5.tar.gz
cd automake-*
./configure
@ -82,7 +107,7 @@ jobs:
run: brew install texinfo
- name: dep cache
id: cache-action
uses: actions/cache@v3
uses: actions/cache@v4
with:
key: macos_intel_2.7.63
path: deps/build/destdir
@ -91,10 +116,46 @@ jobs:
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: rc_${{ github.event.repository.name }}-macOS.tgz
name: rc_${{ github.event.repository.name }}-macOS-intel.tgz
path: build/${{ github.event.repository.name }}-macOS-intel.tgz
if-no-files-found: error
overwrite: true
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: rc_${{ github.event.repository.name }}-macOS.dmg
name: rc_${{ github.event.repository.name }}-macOS-intel.dmg
path: build/${{ github.event.repository.name }}-macOS-intel.dmg
if-no-files-found: error
overwrite: true
- name: Stage named release files and integrity manifest
if: inputs.release_id != ''
env:
RELEASE_SHA: ${{ inputs.source_sha }}
RELEASE_VERSION: ${{ inputs.release_version }}
PRODUCT: ${{ inputs.product }}
run: >-
python3 .github/scripts/release.py stage --platform macos-intel
--source-sha "$RELEASE_SHA" --version "$RELEASE_VERSION" --product "$PRODUCT"
- name: Upload exact files for the draft publisher
id: release-artifact
if: inputs.release_id != ''
uses: actions/upload-artifact@v4
with:
name: release-macos-intel-${{ github.run_attempt }}
path: release-assets/
if-no-files-found: error
publish:
needs: build
if: inputs.release_id != ''
permissions:
contents: write
actions: read
uses: ./.github/workflows/release_upload.yml
with:
source_sha: ${{ inputs.source_sha }}
release_version: ${{ inputs.release_version }}
release_id: ${{ inputs.release_id }}
product: ${{ inputs.product }}
platform: macos-intel
artifact_id: ${{ needs.build.outputs.release_artifact_id }}

View file

@ -1,23 +1,41 @@
name: C/C++ Release candidate ubuntu-GTK2
on:
push:
branches:
- rc
workflow_dispatch:
workflow_call:
inputs:
source_sha:
type: string
required: true
release_version:
type: string
required: true
release_id:
type: string
required: true
product:
type: string
required: true
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-22.04
outputs:
release_artifact_id: ${{ steps.release-artifact.outputs.artifact-id }}
env:
EXEC_NAME: "${{ github.event.repository.name }}"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: 'rc'
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- name: Setup cmake
uses: jwlawson/actions-setup-cmake@v1.13
uses: jwlawson/actions-setup-cmake@v2
with:
cmake-version: '3.16.x'
- name: update clock
@ -30,7 +48,7 @@ jobs:
run: sudo ./BuildLinux.sh -u
- name: dep cache
id: cache-action
uses: actions/cache@v3
uses: actions/cache@v4
with:
key: ubu_gtk2_2.7.63
path: deps/build/destdir
@ -44,8 +62,44 @@ jobs:
with:
name: rc_${{ github.event.repository.name }}-linux-x64-GTK2.tgz
path: build/${{ github.event.repository.name }}-linux-x64-GTK2.tgz
if-no-files-found: error
overwrite: true
- name: Upload appimage
uses: actions/upload-artifact@v4
with:
name: rc_${{ github.event.repository.name }}-linux-x64-GTK2.AppImage
path: build/${{ github.event.repository.name }}-linux-x64-GTK2.AppImage
if-no-files-found: error
overwrite: true
- name: Stage named release files and integrity manifest
if: inputs.release_id != ''
env:
RELEASE_SHA: ${{ inputs.source_sha }}
RELEASE_VERSION: ${{ inputs.release_version }}
PRODUCT: ${{ inputs.product }}
run: >-
python3 .github/scripts/release.py stage --platform linux-gtk2
--source-sha "$RELEASE_SHA" --version "$RELEASE_VERSION" --product "$PRODUCT"
- name: Upload exact files for the draft publisher
id: release-artifact
if: inputs.release_id != ''
uses: actions/upload-artifact@v4
with:
name: release-linux-gtk2-${{ github.run_attempt }}
path: release-assets/
if-no-files-found: error
publish:
needs: build
if: inputs.release_id != ''
permissions:
contents: write
actions: read
uses: ./.github/workflows/release_upload.yml
with:
source_sha: ${{ inputs.source_sha }}
release_version: ${{ inputs.release_version }}
release_id: ${{ inputs.release_id }}
product: ${{ inputs.product }}
platform: linux-gtk2
artifact_id: ${{ needs.build.outputs.release_artifact_id }}

View file

@ -1,23 +1,41 @@
name: C/C++ Release candidate ubuntu-GTK3
on:
push:
branches:
- rc
workflow_dispatch:
workflow_call:
inputs:
source_sha:
type: string
required: true
release_version:
type: string
required: true
release_id:
type: string
required: true
product:
type: string
required: true
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-22.04
outputs:
release_artifact_id: ${{ steps.release-artifact.outputs.artifact-id }}
env:
EXEC_NAME: "${{ github.event.repository.name }}"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: 'rc'
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- name: Setup cmake
uses: jwlawson/actions-setup-cmake@v1.13
uses: jwlawson/actions-setup-cmake@v2
with:
cmake-version: '3.16.x'
- name: update clock
@ -30,7 +48,7 @@ jobs:
run: sudo ./BuildLinux.sh -u
- name: dep cache
id: cache-action
uses: actions/cache@v3
uses: actions/cache@v4
with:
key: ubu_gtk3_2.7.63
path: deps/build/destdir
@ -44,8 +62,44 @@ jobs:
with:
name: rc_${{ github.event.repository.name }}-linux-x64-GTK3.tgz
path: build/${{ github.event.repository.name }}-linux-x64-GTK3.tgz
if-no-files-found: error
overwrite: true
- name: Upload appimage
uses: actions/upload-artifact@v4
with:
name: rc_${{ github.event.repository.name }}-linux-x64-GTK3.AppImage
path: build/${{ github.event.repository.name }}-linux-x64-GTK3.AppImage
if-no-files-found: error
overwrite: true
- name: Stage named release files and integrity manifest
if: inputs.release_id != ''
env:
RELEASE_SHA: ${{ inputs.source_sha }}
RELEASE_VERSION: ${{ inputs.release_version }}
PRODUCT: ${{ inputs.product }}
run: >-
python3 .github/scripts/release.py stage --platform linux-gtk3
--source-sha "$RELEASE_SHA" --version "$RELEASE_VERSION" --product "$PRODUCT"
- name: Upload exact files for the draft publisher
id: release-artifact
if: inputs.release_id != ''
uses: actions/upload-artifact@v4
with:
name: release-linux-gtk3-${{ github.run_attempt }}
path: release-assets/
if-no-files-found: error
publish:
needs: build
if: inputs.release_id != ''
permissions:
contents: write
actions: read
uses: ./.github/workflows/release_upload.yml
with:
source_sha: ${{ inputs.source_sha }}
release_version: ${{ inputs.release_version }}
release_id: ${{ inputs.release_id }}
product: ${{ inputs.product }}
platform: linux-gtk3
artifact_id: ${{ needs.build.outputs.release_artifact_id }}

View file

@ -3,7 +3,6 @@ name: C/C++ Release candidate windows x64
on:
push:
branches:
- rc
- debug_win
workflow_dispatch:
inputs:
@ -11,10 +10,30 @@ on:
description: 'Sign this release build (requires SIGNPATH_ENABLED and production policy)'
type: boolean
default: false
workflow_call:
inputs:
source_sha:
type: string
required: true
release_version:
type: string
required: true
release_id:
type: string
required: true
product:
type: string
required: true
secrets:
SIGNPATH_API_TOKEN:
required: false
permissions:
contents: read
env:
# Automatic signing is limited to pushes to rc; debug_win never signs automatically.
SIGNPATH_ENABLED: ${{ vars.SIGNPATH_ENABLED == 'true' && ((github.event_name == 'push' && github.ref == 'refs/heads/rc') || (github.event_name == 'workflow_dispatch' && inputs.sign)) && 'true' || 'false' }}
# The orchestrator requires production signing; standalone debug pushes never sign.
SIGNPATH_ENABLED: ${{ vars.SIGNPATH_ENABLED == 'true' && (inputs.release_id != '' || (github.event_name == 'workflow_dispatch' && inputs.sign)) && 'true' || 'false' }}
SIGNPATH_ORGANIZATION_ID: ${{ vars.SIGNPATH_ORGANIZATION_ID }}
SIGNPATH_PROJECT_SLUG: ${{ vars.SIGNPATH_PROJECT_SLUG || 'superslicer' }}
SIGNPATH_SIGNING_POLICY_SLUG: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}
@ -25,6 +44,13 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- name: Require production signing for release assets
if: inputs.release_id != '' && env.SIGNPATH_ENABLED != 'true'
shell: powershell
run: throw 'RC release assets require SIGNPATH_ENABLED=true and a valid production certificate. Use the nightly workflow for self-signed tests.'
- name: check signing configuration
if: env.SIGNPATH_ENABLED == 'true'
shell: powershell
@ -60,12 +86,17 @@ jobs:
build:
runs-on: windows-2022
needs: build_dep
outputs:
release_artifact_id: ${{ steps.release-artifact.outputs.artifact-id }}
permissions:
contents: read
actions: read
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_sha || github.sha }}
persist-credentials: false
- uses: ilammy/msvc-dev-cmd@v1
- name: update submodule profiles
working-directory: ./resources/profiles
@ -208,6 +239,7 @@ jobs:
with:
name: rc_${{ github.event.repository.name }}-win64
path: build/package/
if-no-files-found: error
overwrite: true
# MSI CREATION (need files from the slic3r build, can't be its own step)
@ -244,7 +276,10 @@ jobs:
shell: powershell
run: |
$fullVersion = (Get-Content version.inc | Select-String -Pattern 'set\(SLIC3R_RC_VERSION_DOTS \"(.*?)\"\)' | ForEach-Object { $_.Matches.Groups[1].Value })
$env:InstallerVersion = "$fullVersion" -replace '\.[0-9]([+-].+)?', '.0'
if ($fullVersion -notmatch '^\d+\.\d+\.\d+\.\d+$') {
throw 'Invalid SLIC3R_RC_VERSION_DOTS; refusing to generate a mis-versioned installer'
}
$env:InstallerVersion = "$fullVersion"
echo "InstallerVersion=$env:InstallerVersion" >> $env:GITHUB_ENV
$env:ReleaseSuffix = ""
echo "ReleaseSuffix=$env:ReleaseSuffix" >> $env:GITHUB_ENV
@ -252,9 +287,7 @@ jobs:
shell: powershell
run: |
if ([string]::IsNullOrWhiteSpace($env:InstallerVersion)) {
Write-Warning "InstallerVersion is empty or null. Setting default version to 0.0.0.0"
$env:InstallerVersion = "0.0.0.0"
echo "InstallerVersion=$env:InstallerVersion" >> $env:GITHUB_ENV
throw 'InstallerVersion is empty; refusing to publish a 0.0.0.0 fallback'
}
Write-Host "Version validation passed: $env:InstallerVersion"
- name: Build MSI installer
@ -310,5 +343,39 @@ jobs:
with:
name: rc_${{ github.event.repository.name }}-win64.msi
path: build/${{ github.event.repository.name }}_${{ env.InstallerVersion }}.msi
if-no-files-found: error
overwrite: true
- name: Stage signed release files and integrity manifest
if: inputs.release_id != ''
shell: powershell
env:
RELEASE_SHA: ${{ inputs.source_sha }}
RELEASE_VERSION: ${{ inputs.release_version }}
PRODUCT: ${{ inputs.product }}
run: >-
python .github/scripts/release.py stage --platform windows
--source-sha "$env:RELEASE_SHA" --version "$env:RELEASE_VERSION" --product "$env:PRODUCT"
- name: Upload exact files for the draft publisher
id: release-artifact
if: inputs.release_id != ''
uses: actions/upload-artifact@v4
with:
name: release-windows-${{ github.run_attempt }}
path: release-assets/
if-no-files-found: error
publish:
needs: build
if: inputs.release_id != ''
permissions:
contents: write
actions: read
uses: ./.github/workflows/release_upload.yml
with:
source_sha: ${{ inputs.source_sha }}
release_version: ${{ inputs.release_version }}
release_id: ${{ inputs.release_id }}
product: ${{ inputs.product }}
platform: windows
artifact_id: ${{ needs.build.outputs.release_artifact_id }}

142
.github/workflows/release_rc.yml vendored Normal file
View file

@ -0,0 +1,142 @@
name: RC release orchestrator
on:
push:
branches: [rc]
workflow_dispatch:
permissions:
contents: read
# Do not cancel an in-progress release when rc receives another push.
# GitHub may replace a pending run with the newest pending run in this group.
concurrency:
group: rc-release-${{ github.repository }}
cancel-in-progress: false
jobs:
prepare:
runs-on: ubuntu-22.04
permissions:
contents: write
outputs:
product: ${{ steps.release.outputs.product }}
version: ${{ steps.release.outputs.version }}
tag: ${{ steps.release.outputs.tag }}
source_sha: ${{ steps.release.outputs.source_sha }}
release_id: ${{ steps.release.outputs.release_id }}
windows: ${{ steps.release.outputs.windows }}
macos_intel: ${{ steps.release.outputs.macos_intel }}
macos_arm: ${{ steps.release.outputs.macos_arm }}
linux_gtk3: ${{ steps.release.outputs.linux_gtk3 }}
linux_gtk2: ${{ steps.release.outputs.linux_gtk2 }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.sha }}
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Test release logic offline before any GitHub write
run: python -B -m unittest discover -s .github/scripts/tests -v
- name: Prepare immutable tag and draft release
id: release
env:
GH_TOKEN: ${{ github.token }}
run: python .github/scripts/release.py prepare --source-sha "$GITHUB_SHA" --output "$GITHUB_OUTPUT"
windows:
needs: prepare
if: needs.prepare.outputs.windows == 'true'
permissions:
contents: write
actions: read
uses: ./.github/workflows/ccpp_win_rc.yml
with:
source_sha: ${{ needs.prepare.outputs.source_sha }}
release_version: ${{ needs.prepare.outputs.version }}
release_id: ${{ needs.prepare.outputs.release_id }}
product: ${{ needs.prepare.outputs.product }}
secrets:
SIGNPATH_API_TOKEN: ${{ secrets.SIGNPATH_API_TOKEN }}
macos_intel:
needs: prepare
if: needs.prepare.outputs.macos_intel == 'true'
permissions:
contents: write
actions: read
uses: ./.github/workflows/ccpp_mac_rc.yml
with:
source_sha: ${{ needs.prepare.outputs.source_sha }}
release_version: ${{ needs.prepare.outputs.version }}
release_id: ${{ needs.prepare.outputs.release_id }}
product: ${{ needs.prepare.outputs.product }}
macos_arm:
needs: prepare
if: needs.prepare.outputs.macos_arm == 'true'
permissions:
contents: write
actions: read
uses: ./.github/workflows/ccpp_mac_arm_rc.yml
with:
source_sha: ${{ needs.prepare.outputs.source_sha }}
release_version: ${{ needs.prepare.outputs.version }}
release_id: ${{ needs.prepare.outputs.release_id }}
product: ${{ needs.prepare.outputs.product }}
linux_gtk3:
needs: prepare
if: needs.prepare.outputs.linux_gtk3 == 'true'
permissions:
contents: write
actions: read
uses: ./.github/workflows/ccpp_ubuntu_gtk3_rc.yml
with:
source_sha: ${{ needs.prepare.outputs.source_sha }}
release_version: ${{ needs.prepare.outputs.version }}
release_id: ${{ needs.prepare.outputs.release_id }}
product: ${{ needs.prepare.outputs.product }}
linux_gtk2:
needs: prepare
if: needs.prepare.outputs.linux_gtk2 == 'true'
permissions:
contents: write
actions: read
uses: ./.github/workflows/ccpp_ubuntu_gtk2_rc.yml
with:
source_sha: ${{ needs.prepare.outputs.source_sha }}
release_version: ${{ needs.prepare.outputs.version }}
release_id: ${{ needs.prepare.outputs.release_id }}
product: ${{ needs.prepare.outputs.product }}
summary:
needs: [prepare, windows, macos_intel, macos_arm, linux_gtk3, linux_gtk2]
if: ${{ always() && needs.prepare.result == 'success' }}
runs-on: ubuntu-22.04
permissions:
# GitHub requires push access even for GET requests on a draft release.
# The verify command itself performs no writes.
contents: write
steps:
- uses: actions/checkout@v4
with:
ref: ${{ needs.prepare.outputs.source_sha }}
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Check all assets and leave the release in draft
env:
GH_TOKEN: ${{ github.token }}
RELEASE_SHA: ${{ needs.prepare.outputs.source_sha }}
RELEASE_VERSION: ${{ needs.prepare.outputs.version }}
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
PRODUCT: ${{ needs.prepare.outputs.product }}
RELEASE_JOB_RESULTS: ${{ toJSON(needs) }}
run: >-
python .github/scripts/release.py verify --source-sha "$RELEASE_SHA"
--version "$RELEASE_VERSION" --product "$PRODUCT" --release-id "$RELEASE_ID"

59
.github/workflows/release_upload.yml vendored Normal file
View file

@ -0,0 +1,59 @@
name: Upload platform assets to an RC draft
on:
workflow_call:
inputs:
source_sha:
type: string
required: true
release_version:
type: string
required: true
release_id:
type: string
required: true
product:
type: string
required: true
platform:
type: string
required: true
artifact_id:
type: string
required: true
permissions:
contents: read
jobs:
upload:
runs-on: ubuntu-22.04
permissions:
contents: write
actions: read
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_sha }}
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Download the exact output of this platform in this workflow run
uses: actions/download-artifact@v4
with:
artifact-ids: ${{ inputs.artifact_id }}
merge-multiple: true
path: release-assets
- name: Verify manifest, tag and draft; upload only missing files
env:
GH_TOKEN: ${{ github.token }}
RELEASE_SHA: ${{ inputs.source_sha }}
RELEASE_VERSION: ${{ inputs.release_version }}
RELEASE_ID: ${{ inputs.release_id }}
PRODUCT: ${{ inputs.product }}
PLATFORM: ${{ inputs.platform }}
run: >-
python .github/scripts/release.py upload --source-sha "$RELEASE_SHA"
--version "$RELEASE_VERSION" --product "$PRODUCT" --release-id "$RELEASE_ID"
--platform "$PLATFORM" --assets-directory release-assets

View file

@ -31,7 +31,7 @@ def get_cmake_var(filepath, var_name):
return None
parser = argparse.ArgumentParser(
description="Create release folders without overwriting existing ones."
description="Legacy manual recovery tool. Prefer the RC release orchestrator in GitHub Actions."
)
parser.add_argument("branch_name", nargs="?", default="rc", help="Branch name")
@ -57,10 +57,10 @@ if githubtoken_file.exists():
for line in f:
if line.startswith("token="):
github_auth_token = line.strip().split("=", 1)[1];
print(f"file githubtoken.ini found, using token:'{github_auth_token}'");
print("file githubtoken.ini found; using configured credentials (value hidden)");
break
else:
print(f"file githubtoken.ini not found, using hardcoded token:'{github_auth_token}'");
print("file githubtoken.ini not found (credential values are never displayed)");
if(not github_auth_token):
print("For this scipt to work, please create a 'githubtoken.ini' file, and make at least a line with 'token=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'");