Files
OrcaSlicer/scripts/profile_library.py
T
SoftFever a3dc6c15d8 Publish each filament's nozzle temperature range in the profile library (#18199)
Software that records a filament in a printer's slot, such as OrcaCloud's printer page, needs the
filament's nozzle temperature range, and the library carried none. Each product now carries the
range its OrcaSlicer profile gives, and readers that don't know the new fields keep working.
2026-12-06 22:20:19 +08:00

864 lines
38 KiB
Python

#!/usr/bin/env python3
"""Build the profile library (docs/HLSD/profile-library.md) from the profile validator's export.
profile_library.py fold --raw RAW --channel nightly|release --orca-version V --commit SHA
[--tag TAG] [--current FILE] --out OUT.json
profile_library.py stamp --in FOLDED.json [--recorded VERSION] [--now YYYYmmddHHMM] --out OUT[.gz]
`fold` turns `OrcaSlicer_profile_validator --export-library` output into the published format,
checks that the result decodes back to exactly the per-model, per-nozzle answers it came from, and
prints `changed=true|false` against the channel's current file. The folded file has no `version`:
`stamp` sets it, just before a publish, to a value above the one recorded for the channel, and writes
the gzip the readers download.
The other subcommands are the decisions of .github/workflows/profile_library.yml: `resolve`,
`latest-tag`, `orca-version`, `check-validator`, `tooling` and `publish`. Everything here is the
standard library only, so the unit tests in scripts/tests run with a bare python3.
"""
import argparse
import datetime
import gzip
import hashlib
import io
import json
import re
import sys
SCHEMA = "orca.profile_library.v1"
CHANNELS = ("nightly", "release")
# ASCII digits and the end of the string, as the Go and TypeScript readers match it.
VERSION_RE = re.compile(r"^([0-9]+\.[0-9]+\.[0-9]+)_([0-9]{12})\Z")
STAMP_FORMAT = "%Y%m%d%H%M"
class LibraryError(Exception):
"""The library can't be built or read as asked."""
# --- Folding -------------------------------------------------------------------------------------
def answers_by_model(raw):
"""{model: {nozzle: set of filament ids}}: a filament fits a model and nozzle when any of the
model's printer presets on that nozzle accepts it (D27)."""
answers = {}
for printer in raw["printers"]:
nozzles = answers.setdefault(printer["model"], {})
nozzles.setdefault(printer["nozzle"], set()).update(printer["filaments"])
return answers
def fold(raw, channel, orca_version, commit, tag=None):
"""The published document without `version`, folded from the raw export."""
if channel not in CHANNELS:
raise LibraryError("unknown channel %r" % channel)
if (channel == "release") != bool(tag):
raise LibraryError("a release file needs --tag, and a nightly file takes none")
known = set(raw["filaments"])
universal = set(raw["universal_filaments"])
answers = answers_by_model(raw)
missing = (universal | {i for p in raw["printers"] for i in p["filaments"]}) - known
if missing:
raise LibraryError("the export lists filaments it does not name: %s" % ", ".join(sorted(missing)))
models = {}
for name, model in raw["models"].items():
nozzles = list(model["nozzles"])
by_nozzle = answers.get(name, {})
fits_some_nozzle = set().union(*by_nozzle.values()) if by_nozzle else set()
limits = {}
for fid in fits_some_nozzle:
on = [n for n in nozzles if fid in by_nozzle.get(n, set())]
if len(on) != len(nozzles):
limits[fid] = on
models[name] = {
"vendor": model["vendor"],
"model_id": model["model_id"],
"nozzles": nozzles,
"filaments": sorted(fits_some_nozzle - universal),
"hidden": sorted(universal - fits_some_nozzle),
"nozzle_limits": limits,
}
doc = {
"schema": SCHEMA,
"channel": channel,
"filaments": {fid: raw["filaments"][fid] for fid in sorted(known)},
"universal_filaments": sorted(universal),
"printer_models": models,
"source": {"orca_version": orca_version, "commit": commit, "bundles": dict(raw["bundles"])},
}
if tag:
doc["source"]["tag"] = tag
doc["source"]["data_hash"] = data_hash(doc)
check_round_trip(doc, answers)
return doc
def data_hash(doc):
"""sha256 of the document without `version` and `source`, as compact JSON with sorted keys."""
body = {k: v for k, v in doc.items() if k not in ("version", "source")}
canonical = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def check_round_trip(doc, answers):
"""Raise unless decoding `doc` with the reading rules gives exactly `answers` for every model and nozzle."""
lib = Library(doc, stamped=False)
for name, model in doc["printer_models"].items():
for nozzle in model["nozzles"]:
want = answers.get(name, {}).get(nozzle, set())
got = lib.fits_model(name, nozzle)
if got != want:
raise LibraryError("round trip failed for %s at %s: %d extra, %d missing (%s)" % (
name, nozzle, len(got - want), len(want - got), ", ".join(sorted(got ^ want)[:5])))
# --- Writing -------------------------------------------------------------------------------------
def _is_scalar(value):
return not isinstance(value, (dict, list))
# The top level is written in this order, so a reader opening the file meets the filament catalogue
# right after the channel. Keys missing from the list follow it, sorted.
TOP_LEVEL_ORDER = ("channel", "filaments", "universal_filaments", "printer_models", "schema", "source", "version")
def _top_level_rank(item):
key = item[0]
return (TOP_LEVEL_ORDER.index(key) if key in TOP_LEVEL_ORDER else len(TOP_LEVEL_ORDER), key)
def dumps(doc):
"""Keys in TOP_LEVEL_ORDER at the top and sorted below it, with a container of scalars on one
line when short, and one entry per line otherwise, so a diff between two files reads as a list
of changes."""
def render(value, indent):
if _is_scalar(value):
return json.dumps(value, ensure_ascii=False)
if isinstance(value, dict):
items = sorted(value.items(), key=_top_level_rank if indent == 0 else None)
else:
items = list(value)
if not items:
return "{}" if isinstance(value, dict) else "[]"
children = [v for _, v in items] if isinstance(value, dict) else items
if all(_is_scalar(c) for c in children):
one_line = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(", ", ": "))
if len(one_line) + indent <= 100:
return one_line
pad = " " * (indent + 2)
if isinstance(value, dict):
lines = ["%s%s: %s" % (pad, json.dumps(k, ensure_ascii=False), render(v, indent + 2)) for k, v in items]
return "{\n" + ",\n".join(lines) + "\n" + " " * indent + "}"
lines = [pad + render(v, indent + 2) for v in items]
return "[\n" + ",\n".join(lines) + "\n" + " " * indent + "]"
return render(doc, 0) + "\n"
def gzip_bytes(text):
"""Gzip with a fixed header (no name, mtime 0), so the same text always gives the same bytes."""
buf = io.BytesIO()
with gzip.GzipFile(filename="", mode="wb", fileobj=buf, compresslevel=9, mtime=0) as gz:
gz.write(text.encode("utf-8"))
return buf.getvalue()
def read_document(path):
"""A library file, gzipped or not."""
with open(path, "rb") as f:
data = f.read()
if data[:2] == b"\x1f\x8b":
data = gzip.decompress(data)
return json.loads(data.decode("utf-8"))
# --- Versions ------------------------------------------------------------------------------------
def base_version(orca_version):
"""2.6.0 from 2.6.0-dev or 2.6.0+build."""
match = re.match(r"^(\d+\.\d+\.\d+)", orca_version)
if not match:
raise LibraryError("not an OrcaSlicer version: %r" % orca_version)
return match.group(1)
def next_version(orca_version, recorded, now):
"""`<x.y.z>_<UTC minute>`: the current minute, or one minute past the recorded stamp when that
is not earlier, so a channel's versions only go up."""
stamp = now
if recorded:
match = VERSION_RE.match(recorded)
if not match:
raise LibraryError("not a library version: %r" % recorded)
floor = datetime.datetime.strptime(match.group(2), STAMP_FORMAT)
if datetime.datetime.strptime(now, STAMP_FORMAT) <= floor:
stamp = (floor + datetime.timedelta(minutes=1)).strftime(STAMP_FORMAT)
version = "%s_%s" % (base_version(orca_version), stamp)
if not VERSION_RE.match(version):
raise LibraryError("not a library version: %r" % version)
return version
def stamp(doc, recorded, now):
"""A copy of `doc` with its `version` set. `data_hash` leaves `version` out, so the hash still
matching proves nothing else changed, and catches a document whose hash is stale."""
stamped = dict(doc)
stamped["version"] = next_version(doc["source"]["orca_version"], recorded, now)
if data_hash(stamped) != doc["source"]["data_hash"]:
raise LibraryError("the document's data_hash does not match its data")
return stamped
def changed(doc, current):
"""Whether `doc` should replace `current`: there is none, its data differs, or for the release
channel it names another stable tag (D30)."""
if not isinstance(current, dict):
return True
if current.get("source", {}).get("data_hash") != doc["source"]["data_hash"]:
return True
return doc["channel"] == "release" and current.get("source", {}).get("tag") != doc["source"].get("tag")
# --- Reading -------------------------------------------------------------------------------------
class Library:
"""One library file, read by the rules every reader follows. `stamped=False` reads a folded
document before publish has given it a version, as the round trip does."""
def __init__(self, doc, stamped=True):
if not isinstance(doc, dict) or doc.get("schema") != SCHEMA:
raise LibraryError("not an %s file" % SCHEMA)
if doc.get("channel") not in CHANNELS:
raise LibraryError("not a library channel: %r" % doc.get("channel"))
if stamped and not (isinstance(doc.get("version"), str) and VERSION_RE.match(doc["version"])):
raise LibraryError("not a library version: %r" % doc.get("version"))
self.doc = doc
self.by_id = {}
for name, model in doc.get("printer_models", {}).items():
if model.get("model_id"):
self.by_id.setdefault(model["model_id"], []).append(name)
def filament(self, fid):
return self.doc.get("filaments", {}).get(fid)
def models_with_id(self, model_id):
return sorted(self.by_id.get(model_id, [])) if model_id else []
def fits_model(self, name, nozzle):
"""The ids that fit model `name` on `nozzle`, or None when the model has no such nozzle."""
model = self.doc["printer_models"][name]
if nozzle not in model["nozzles"]:
return None
fits = (set(self.doc.get("universal_filaments", [])) - set(model.get("hidden", []))) | set(model.get("filaments", []))
limits = model.get("nozzle_limits", {})
return {fid for fid in fits if fid not in limits or nozzle in limits[fid]}
def nozzle_range(product):
"""A product's nozzle_temp_min and nozzle_temp_max when both are integers above 0 and the
minimum is not above the maximum, else nothing."""
ends = (product.get("nozzle_temp_min"), product.get("nozzle_temp_max"))
if all(type(end) is int and end > 0 for end in ends) and ends[0] <= ends[1]:
return {"nozzle_temp_min": ends[0], "nozzle_temp_max": ends[1]}
return {}
def lookup_filament(libs, order, fid):
"""The product `fid` in the first file that knows it: its vendor, name and type, and its nozzle
range when that file gives a usable one. A range is never taken from another file."""
for channel in order:
found = libs[channel].filament(fid)
if found is not None:
return {"file": channel, "vendor": found["vendor"], "name": found["name"], "type": found["type"],
**nozzle_range(found)}
return None
def lookup_model(libs, order, model_id):
"""The model with `model_id` in the first file that knows it, or a reason."""
for channel in order:
names = libs[channel].models_with_id(model_id)
if len(names) > 1:
return {"file": channel, "reason": "shared", "models": names}
if names:
model = libs[channel].doc["printer_models"][names[0]]
return {"file": channel, "name": names[0], "vendor": model["vendor"], "nozzles": model["nozzles"]}
return {"reason": "unknown_model"}
def lookup_fits(libs, order, model_id, nozzle):
"""The filaments that fit the model with `model_id` on `nozzle`, or a reason."""
found = lookup_model(libs, order, model_id)
if "reason" in found:
return found
fits = libs[found["file"]].fits_model(found["name"], nozzle)
if fits is None:
return {"file": found["file"], "reason": "unknown_nozzle", "nozzles": found["nozzles"]}
return {"file": found["file"], "filaments": sorted(fits)}
def model_list(nightly, release):
"""The model list a picker offers: nightly's models, plus release's models whose exact name
nightly lacks, with nightly's id first and empty ids left out, as [vendor, name, model_id] rows."""
rows = {}
for lib in (nightly, release):
if lib is None:
continue
for name, model in lib.doc["printer_models"].items():
if name not in rows:
rows[name] = [model["vendor"], name, model["model_id"]]
return [row for row in rows.values() if row[2]]
# --- Publishing (.github/workflows/profile_library.yml) -----------------------------------------
#
# The workflow's decisions live here so the tests can drive them with recorded GitHub API
# responses. `resolve` picks the Build all run whose validator and commit a run uses; `decide`
# makes every write decision of the publish step from the state it reads inside its one-at-a-time
# slot, so no check made earlier can go stale while the step waits for the slot.
SOURCE_REPO = "OrcaSlicer/OrcaSlicer"
PROFILES_REPO = "OrcaSlicer/orcaslicer-profiles"
RELEASE_NAME = "profile-library"
ASSETS = {"nightly": "profile-library_nightly.json.gz", "release": "profile-library_release.json.gz"}
SCHEMA_ASSET = "profile-library.schema.json"
FIXTURE_ASSET = "profile-library-fixture.json"
TOOLING = ("scripts/profile_library.py", "scripts/profile_library.schema.json",
"scripts/tests/profile_library_fixture.json", ".github/workflows/profile_library.yml")
TRUSTED_EVENTS = ("push", "schedule", "workflow_dispatch")
RERUN = "rerun Build all on main"
class Stop(Exception):
"""Nothing to do on this run, and that is fine."""
def woken_by_trusted_build(event_name, workflow_run):
"""Whether this workflow run should go on: a direct dispatch, or a Build all of this repository's
own main pushed, scheduled or started by hand. A pull request's Build all also reports
head_branch main, so the event decides."""
if event_name == "workflow_dispatch":
return True
run = workflow_run or {}
return (run.get("event") in TRUSTED_EVENTS and run.get("head_branch") == "main"
and (run.get("head_repository") or {}).get("full_name") == SOURCE_REPO)
def validator_job_prefix(self_hosted):
"""The Build all job that builds and uploads the Linux validator."""
return "build_linux (orca-lnx-server" if self_hosted else "build_linux (aarch64, "
def arch(self_hosted):
return "x86_64" if self_hosted else "aarch64"
def eligible(run, jobs, self_hosted):
"""(True, "") when the Build all `run` has a validator this workflow may use, else (False, why).
The job's result outlives the artifact, so a run stays eligible after the artifact expires."""
if (run.get("repository") or {}).get("full_name") != SOURCE_REPO:
return False, "not a run of %s" % SOURCE_REPO
if (run.get("head_repository") or {}).get("full_name") != SOURCE_REPO:
return False, "built from a fork"
if run.get("head_branch") != "main":
return False, "not built from main"
if run.get("event") not in TRUSTED_EVENTS:
return False, "started by %s" % run.get("event")
if run.get("conclusion") != "success":
return False, "did not succeed"
prefix = validator_job_prefix(self_hosted)
job = next((j for j in jobs if j.get("name", "").startswith(prefix) and j["name"].endswith("/ Build OrcaSlicer")), None)
if job is None or job.get("conclusion") != "success":
return False, "built no Linux validator (a build-deps-only run builds none)"
return True, ""
def validator_artifact(run, artifacts, self_hosted):
"""The run's unexpired validator artifact, or a LibraryError saying to rerun Build all."""
name = "%s-profile-validator-linux-%s" % (run["head_sha"], arch(self_hosted))
for artifact in artifacts:
if artifact.get("name") == name and not artifact.get("expired"):
return name
raise LibraryError("Build all run %s's validator has expired or is missing; %s" % (run["id"], RERUN))
def resolve(api, event_name, workflow_run, self_hosted):
"""{run_id, head_sha, arch, artifact} for the Build all run to use. After Build all it is the
run that woke the workflow; started by hand it is the newest eligible run on main. Raises Stop
when the waking run is not eligible, and LibraryError when no run can be used."""
def jobs_of(run_id):
jobs, page = [], 1
while True:
batch = api.get("repos/%s/actions/runs/%s/jobs" % (SOURCE_REPO, run_id), per_page=100, page=page)["jobs"]
jobs += batch
if len(batch) < 100:
return jobs
page += 1
if event_name == "workflow_run":
run = api.get("repos/%s/actions/runs/%s" % (SOURCE_REPO, workflow_run["id"]))
ok, why = eligible(run, jobs_of(run["id"]), self_hosted)
if not ok:
raise Stop("Build all run %s is not used: %s" % (run["id"], why))
else:
runs = api.get("repos/%s/actions/workflows/build_all.yml/runs" % SOURCE_REPO,
branch="main", status="success", exclude_pull_requests="true", per_page=30)["workflow_runs"]
run = next((r for r in runs if eligible(r, jobs_of(r["id"]), self_hosted)[0]), None)
if run is None:
raise LibraryError("no recent Build all run on main built a validator; %s" % RERUN)
artifacts = api.get("repos/%s/actions/runs/%s/artifacts" % (SOURCE_REPO, run["id"]), per_page=100)["artifacts"]
return {"run_id": run["id"], "head_sha": run["head_sha"], "arch": arch(self_hosted),
"artifact": validator_artifact(run, artifacts, self_hosted)}
def stable_tag(release):
"""The tag of GitHub's latest release, which is never a draft or a prerelease."""
if release.get("draft") or release.get("prerelease") or not release.get("tag_name"):
raise LibraryError("the latest release is not a stable release: %r" % release.get("tag_name"))
return release["tag_name"]
def orca_version(version_inc):
"""SoftFever_VERSION from a tree's version.inc, as post_merge_profiles.yml reads it."""
match = re.search(r'^set\(SoftFever_VERSION "([^"]+)"', version_inc, re.M)
if not match:
raise LibraryError("could not read SoftFever_VERSION from version.inc")
base_version(match.group(1))
return match.group(1)
def validator_supports_export(help_text):
return "--export-library" in help_text
def tooling_same(git_dir, other_ref):
"""Whether the publish tooling at `other_ref` equals this checkout's."""
import subprocess
result = subprocess.run(["git", "-C", git_dir, "diff", "--quiet", "HEAD", other_ref, "--", *TOOLING])
if result.returncode not in (0, 1):
raise LibraryError("git diff failed comparing the publish tooling with %s" % other_ref)
return result.returncode == 0
DESCRIPTION_HEADER = ("Written by OrcaSlicer's .github/workflows/profile_library.yml "
"(docs/HLSD/profile-library.md). The lines below record what it last published.")
# A record line's word count, its first word included.
RECORD_FIELDS = {"build": 2, "nightly": 4, "release": 5}
COMMIT_RE = re.compile(r"^[0-9a-f]{40}\Z")
def parse_description(text):
"""The record a release description holds: the last build that published, and each data file's
version, data_hash, gzip SHA-256 and, for release, tag. Only publish writes it, one line of each
kind, so a line that starts like a record without a record's fields, or a second line of a kind,
comes from a hand edit; it is refused with a message naming it, never read in a way that could
move a channel backwards."""
record = {"build": None, "nightly": None, "release": None}
for line in (text or "").splitlines():
parts = line.split()
if parts and parts[0] in RECORD_FIELDS and (
len(parts) != RECORD_FIELDS[parts[0]] or (parts[0] == "build" and not COMMIT_RE.match(parts[1]))):
raise LibraryError("the release description's line %r is not a %s record; correct it and rerun"
% (line, parts[0]))
if parts and parts[0] in RECORD_FIELDS and record[parts[0]] is not None:
raise LibraryError("the release description has a second %s line, %r; remove the one publish did not "
"write and rerun" % (parts[0], line))
if len(parts) == 2 and parts[0] == "build":
record["build"] = parts[1]
elif len(parts) == 4 and parts[0] == "nightly":
record["nightly"] = {"version": parts[1], "data_hash": parts[2], "sha256": parts[3]}
elif len(parts) == 5 and parts[0] == "release":
record["release"] = {"version": parts[1], "data_hash": parts[2], "sha256": parts[3], "tag": parts[4]}
return record
def recorded_version(channel, entry):
"""The version a description line records for `channel`, read the way `next_version` reads a
floor, or "" when there is no line. A line it can't read only comes from a hand edit, and
stamping without it could move the channel backwards, so it is refused with a message naming it."""
if not entry:
return ""
try:
next_version("0.0.0", entry["version"], "200001010000")
except (LibraryError, ValueError, OverflowError):
raise LibraryError("the release description's %s line records %r, which is not a library version "
"publish can stamp above; correct it to the published file's version and rerun"
% (channel, entry["version"])) from None
return entry["version"]
def check_record(record, held):
"""The floor each channel's line records, once the record as a whole is one publish could have
written; `held` is the channels whose data file is on the release. Publish and the dry run's
report both read the record through this, so the report warns of every stop publish would make.
Publish writes the build line with every record, so without it the build comparison that keeps
an older build from replacing newer data would be skipped; and a file whose line is gone has
no known version, so a new one could be stamped below it."""
published = [c for c in CHANNELS if record[c] is not None or c in held]
if record["build"] is None and published:
raise LibraryError("the release description has no build line but records or holds %s; restore the "
"line naming the last published build and rerun" % ", ".join(published))
for channel in CHANNELS:
if record[channel] is None and channel in held:
raise LibraryError("the release has %s but its description has no %s line, so publish can't tell "
"its version; restore the line and rerun" % (ASSETS[channel], channel))
return {channel: recorded_version(channel, record[channel]) for channel in CHANNELS}
def render_description(record):
lines = [DESCRIPTION_HEADER, ""]
if record["build"]:
lines.append("build %s" % record["build"])
for channel in CHANNELS:
entry = record[channel]
if entry:
fields = [entry["version"], entry["data_hash"], entry["sha256"]] + ([entry["tag"]] if channel == "release" else [])
lines.append(" ".join([channel] + fields))
return "\n".join(lines) + "\n"
def asset_state(asset, want_sha256):
"""Why `asset` must be uploaded again, or "" when it is the file `want_sha256` names. A missing
digest on a finished upload is not a reason (some older assets have none), only a note."""
if asset is None:
return "missing"
if asset.get("state") != "uploaded":
return "an upload that did not finish"
digest = asset.get("digest")
if digest is None:
return ""
return "" if digest == "sha256:" + want_sha256 else "not the recorded file"
def decide(release, docs, contract, candidate, latest_tag, compare, attempt, tooling_is_same, now):
"""Every write decision of the publish step, from the state read inside its slot.
release: the profile-library release ({"body", "assets"}), or None before the first publish;
docs: {"nightly": folded doc, "release": folded doc} from the build;
contract: {asset name: bytes} for the schema and the fixture;
candidate: the build's meta ({"run_attempt", "head_sha", "release_tag"});
compare: compare(base, head) -> GitHub's compare status, or None when GitHub can't compare them;
Returns {"description", "uploads": [{"name", "data", "delete_id"}], "notes"}; raises Stop or LibraryError."""
if str(candidate["run_attempt"]) != str(attempt):
raise LibraryError("this publish would use attempt %s's build; rerun all jobs" % candidate["run_attempt"])
if not tooling_is_same:
raise Stop("the publish tooling changed on main; the next run uses it")
record = parse_description(release["body"] if release else "")
assets = {a["name"]: a for a in (release["assets"] if release else [])}
floors = check_record(record, {channel for channel in CHANNELS if ASSETS[channel] in assets})
head = candidate["head_sha"]
if record["build"] and record["build"] != head:
status = compare(record["build"], head)
if status is None:
raise LibraryError("the release description's build line names %s, which GitHub can't compare with %s; "
"correct it to the last published build and rerun" % (record["build"], head))
if status == "behind":
raise Stop("build %s is older than the last one published (%s)" % (head, record["build"]))
if status not in ("ahead", "identical"):
raise LibraryError("build %s and the last one published (%s) have %s" % (head, record["build"], status))
notes, uploads = [], []
new_record = {"build": head, "nightly": record["nightly"], "release": record["release"]}
for channel in CHANNELS:
doc, rec, name = docs[channel], record[channel], ASSETS[channel]
if channel == "release" and doc["source"]["tag"] != latest_tag:
notes.append("release: built from %s, but the latest stable release is now %s; the next run publishes it"
% (doc["source"]["tag"], latest_tag))
continue
asset = assets.get(name)
if rec is None:
why = "no record"
elif rec["data_hash"] != doc["source"]["data_hash"]:
why = "new data"
elif channel == "release" and rec["tag"] != doc["source"]["tag"]:
why = "new stable release %s" % doc["source"]["tag"]
else:
why = asset_state(asset, rec["sha256"])
if asset is not None and asset.get("state") == "uploaded" and asset.get("digest") is None:
notes.append("%s: GitHub gives no digest for it" % name)
if not why:
continue
stamped = stamp(doc, floors[channel], now)
data = gzip_bytes(dumps(stamped))
entry = {"version": stamped["version"], "data_hash": doc["source"]["data_hash"],
"sha256": hashlib.sha256(data).hexdigest()}
if channel == "release":
entry["tag"] = doc["source"]["tag"]
new_record[channel] = entry
uploads.append(upload(name, data, asset))
notes.append("%s: %s, publishing %s" % (name, why, stamped["version"]))
for name, data in contract.items():
asset = assets.get(name)
why = asset_state(asset, hashlib.sha256(data).hexdigest())
if asset is not None and asset.get("state") == "uploaded" and asset.get("digest") is None:
notes.append("%s: GitHub gives no digest for it" % name)
if why:
uploads.append(upload(name, data, asset))
notes.append("%s: %s" % (name, why))
return {"description": render_description(new_record), "uploads": uploads, "notes": notes}
def upload(name, data, asset):
"""An upload, deleting first an asset whose upload never finished: --clobber may not replace it."""
starter = asset is not None and asset.get("state") != "uploaded"
return {"name": name, "data": data, "delete_id": asset["id"] if starter else None}
# --- Command line --------------------------------------------------------------------------------
def utc_minute():
return datetime.datetime.now(datetime.timezone.utc).strftime(STAMP_FORMAT)
def cmd_fold(args):
with open(args.raw, encoding="utf-8") as f:
raw = json.load(f)
doc = fold(raw, args.channel, args.orca_version, args.commit, args.tag)
with open(args.out, "w", encoding="utf-8") as f:
f.write(dumps(doc))
# The current file feeds only the report, so whatever goes wrong reading or comparing it counts
# as changed rather than stopping the build that would replace it.
is_changed = True
if args.current:
try:
is_changed = changed(doc, read_document(args.current))
except Exception as e:
print("::notice::The current file could not be read (%s: %s); the report counts it as changed."
% (type(e).__name__, e))
print("data_hash=%s" % doc["source"]["data_hash"])
print("changed=%s" % ("true" if is_changed else "false"))
return 0
def cmd_stamp(args):
with open(args.input, encoding="utf-8") as f:
doc = json.load(f)
stamped = stamp(doc, args.recorded, args.now or utc_minute())
text = dumps(stamped)
data = gzip_bytes(text) if args.out.endswith(".gz") else text.encode("utf-8")
with open(args.out, "wb") as f:
f.write(data)
print("version=%s" % stamped["version"])
print("sha256=%s" % hashlib.sha256(data).hexdigest())
return 0
def cmd_recorded(args):
"""The version the release description records for a channel: the floor publish stamps above,
so a dry run's report names the version a publish would get. It reads what publish reads, the
release's description and its asset list, from `gh release view --json body,assets`. Empty when
there is none, and when the record is one publish would stop on, which the report warns of."""
try:
with open(args.release, encoding="utf-8") as f:
release = json.load(f)
except (OSError, ValueError):
release = {}
if not isinstance(release, dict):
release = {}
names = {a.get("name") for a in release.get("assets") or [] if isinstance(a, dict)}
try:
held = {channel for channel in CHANNELS if ASSETS[channel] in names}
version = check_record(parse_description(release.get("body") or ""), held)[args.channel]
except LibraryError as e:
print("::warning::%s. A publish would stop on it." % e, file=sys.stderr)
version = ""
print("version=%s" % version)
return 0
def github(token_env):
import os
from ci_check_gcode import Api
token = os.environ.get(token_env)
if not token:
raise LibraryError("%s is not set" % token_env)
return Api(token)
def cmd_resolve(args):
import os
workflow_run = None
if args.event == "workflow_run":
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as f:
workflow_run = json.load(f)["workflow_run"]
if not woken_by_trusted_build(args.event, workflow_run):
print("skip=not woken by a trusted Build all on main")
return 0
try:
chosen = resolve(github("GH_TOKEN"), args.event, workflow_run, bool(args.self_hosted))
except Stop as e:
print("skip=%s" % e)
return 0
for key, value in chosen.items():
print("%s=%s" % (key, value))
return 0
def cmd_latest_tag(_args):
print("tag=%s" % stable_tag(github("GH_TOKEN").get("repos/%s/releases/latest" % SOURCE_REPO)))
return 0
def cmd_orca_version(args):
with open(args.version_inc, encoding="utf-8") as f:
print("version=%s" % orca_version(f.read()))
return 0
def cmd_check_validator(args):
import subprocess
result = subprocess.run([args.validator, "--help"], capture_output=True, text=True)
if not validator_supports_export(result.stdout + result.stderr):
raise LibraryError("Build all has not yet built a commit with the library export; wait for it")
return 0
def cmd_tooling(args):
print("same=%s" % ("true" if tooling_same(".", args.against) else "false"))
return 0
def cmd_publish(args):
import os
import subprocess
import tempfile
import urllib.error
folder = args.artifact_dir
with open(os.path.join(folder, "meta.json"), encoding="utf-8") as f:
candidate = json.load(f)
docs = {}
for channel in CHANNELS:
with open(os.path.join(folder, "%s.json" % channel), encoding="utf-8") as f:
docs[channel] = json.load(f)
contract = {}
for name in (SCHEMA_ASSET, FIXTURE_ASSET):
with open(os.path.join(folder, name), "rb") as f:
contract[name] = f.read()
profiles, source = github("GH_TOKEN"), github("SOURCE_TOKEN")
try:
release = profiles.get("repos/%s/releases/tags/%s" % (PROFILES_REPO, RELEASE_NAME))
except urllib.error.HTTPError as e:
if e.code != 404:
raise
release = None
def compare(base, head):
try:
return source.get("repos/%s/compare/%s...%s" % (SOURCE_REPO, base, head))["status"]
except urllib.error.HTTPError as e:
# Not a commit of this repository. Anything else, such as an outage, fails the run as is.
if e.code in (404, 422):
return None
raise
try:
plan = decide(release, docs, contract, candidate,
stable_tag(source.get("repos/%s/releases/latest" % SOURCE_REPO)), compare,
args.attempt, tooling_same(".", args.against), args.now or utc_minute())
except Stop as e:
print("Nothing to publish: %s" % e)
return 0
for note in plan["notes"]:
print(note)
if release is None:
profiles.send("POST", "repos/%s/releases" % PROFILES_REPO, {
"tag_name": RELEASE_NAME, "name": "Profile library", "body": plan["description"], "make_latest": "false"})
elif release.get("body") != plan["description"]:
profiles.send("PATCH", "repos/%s/releases/%s" % (PROFILES_REPO, release["id"]), {"body": plan["description"]})
with tempfile.TemporaryDirectory() as tmp:
for item in plan["uploads"]:
if item["delete_id"] is not None:
profiles.send("DELETE", "repos/%s/releases/assets/%s" % (PROFILES_REPO, item["delete_id"]))
path = os.path.join(tmp, item["name"])
with open(path, "wb") as f:
f.write(item["data"])
subprocess.run(["gh", "release", "upload", RELEASE_NAME, path, "--repo", PROFILES_REPO, "--clobber"], check=True)
print("uploaded %s" % item["name"])
return 0
def build_parser():
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("resolve", help="pick the Build all run to use (GH_TOKEN; reads GITHUB_EVENT_PATH)")
p.add_argument("--event", required=True)
p.add_argument("--self-hosted", default="", help="the SELF_HOSTED repository variable")
p.set_defaults(func=cmd_resolve)
p = sub.add_parser("latest-tag", help="the latest stable OrcaSlicer release's tag (GH_TOKEN)")
p.set_defaults(func=cmd_latest_tag)
p = sub.add_parser("orca-version", help="SoftFever_VERSION from a version.inc")
p.add_argument("--version-inc", required=True)
p.set_defaults(func=cmd_orca_version)
p = sub.add_parser("check-validator", help="fail unless the validator can export the library")
p.add_argument("--validator", required=True)
p.set_defaults(func=cmd_check_validator)
p = sub.add_parser("tooling", help="whether the publish tooling equals another ref's")
p.add_argument("--against", required=True)
p.set_defaults(func=cmd_tooling)
p = sub.add_parser("publish", help="publish a build's files (GH_TOKEN for the profiles repo, SOURCE_TOKEN)")
p.add_argument("--artifact-dir", required=True)
p.add_argument("--attempt", required=True, help="this run's github.run_attempt")
p.add_argument("--against", default="FETCH_HEAD", help="main's tip, fetched, for the tooling check")
p.add_argument("--now", default="", help="the UTC minute, yyyymmddHHMM (default: now)")
p.set_defaults(func=cmd_publish)
p = sub.add_parser("fold", help="fold the validator's export into the published format")
p.add_argument("--raw", required=True)
p.add_argument("--channel", required=True, choices=CHANNELS)
p.add_argument("--orca-version", required=True)
p.add_argument("--commit", required=True)
p.add_argument("--tag", default=None)
p.add_argument("--current", default=None, help="the channel's current file, if there is one")
p.add_argument("--out", required=True)
p.set_defaults(func=cmd_fold)
p = sub.add_parser("recorded", help="the version a release description records for a channel")
p.add_argument("--release", required=True, help="the release as `gh release view --json body,assets` prints it")
p.add_argument("--channel", required=True, choices=CHANNELS)
p.set_defaults(func=cmd_recorded)
p = sub.add_parser("stamp", help="set the version and write the file a publish uploads")
p.add_argument("--in", dest="input", required=True)
p.add_argument("--recorded", default="", help="the version the release records for the channel")
p.add_argument("--now", default="", help="the UTC minute, yyyymmddHHMM (default: now)")
p.add_argument("--out", required=True, help="a .json.gz is gzipped, anything else is plain JSON")
p.set_defaults(func=cmd_stamp)
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
try:
return args.func(args)
except LibraryError as e:
print("error: %s" % e, file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())