Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

release tooling: one-command bump and release scripts; skip the PyPI build when the version is already published

Preetham Pemmasani5dd869e49304
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 3f24ac0..84f814e 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -21,8 +21,31 @@ on:
default: false
jobs:
+ # Only build and publish what is missing: a tag whose version is already on PyPI (say a release
+ # that only changed the npm packages, or a re-run after PyPI succeeded) does no work at all.
+ plan:
+ name: is this version on PyPI?
+ runs-on: ubuntu-latest
+ outputs:
+ build: ${{ steps.plan.outputs.build }}
+ steps:
+ - id: plan
+ run: |
+ build=true
+ if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
+ version="${GITHUB_REF_NAME#v}"
+ code=$(curl -s -o /dev/null -w '%{http_code}' "https://pypi.org/pypi/blenderui/$version/json")
+ if [ "$code" = 200 ]; then
+ echo "::notice::blenderui $version is already on PyPI; nothing to build or publish"
+ build=false
+ fi
+ fi
+ echo "build=$build" >> "$GITHUB_OUTPUT"
+
wheels:
name: wheels (${{ matrix.os }})
+ needs: plan
+ if: needs.plan.outputs.build == 'true'
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
@@ -65,6 +88,8 @@ jobs:
path: wheelhouse/*.whl
sdist:
+ needs: plan
+ if: needs.plan.outputs.build == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -81,6 +106,8 @@ jobs:
# Full test suites on the source build (Windows: the native window host).
tests:
+ needs: plan
+ if: needs.plan.outputs.build == 'true'
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
@@ -101,8 +128,8 @@ jobs:
ctest --test-dir build --output-on-failure
publish:
- needs: [wheels, sdist, tests]
- if: startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.testpypi)
+ needs: [plan, wheels, sdist, tests]
+ if: needs.plan.outputs.build == 'true' && (startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.testpypi))
runs-on: ubuntu-latest
environment: ${{ startsWith(github.ref, 'refs/tags/v') && 'pypi' || 'testpypi' }}
permissions:
diff --git a/docs/publishing.md b/docs/publishing.md
index 8f4c63a..28ccfb3 100644
--- a/docs/publishing.md
+++ b/docs/publishing.md
@@ -78,12 +78,36 @@ No API tokens are stored anywhere.
## Releasing everything at once
-One tag publishes all of it:
+One command does the whole release:
```sh
-git tag v0.2.0 && git push --tags
+python tools/release.py minor # or patch, major, X.Y.Z; add --npm patch for the npm packages
```
+It checks you are on a clean, up-to-date `main`, bumps every version and pushes that commit, waits
+for the `ci` and `wheels` workflows to go green on it, tags and pushes the tag, waits for the
+publish, then checks crates.io, npm and PyPI for the new version. It never tags a red commit.
+`--dry-run` shows the plan; if a publish step fails, fix it, use "Re-run failed jobs" on the run
+(no new tag needed) and run `python tools/release.py --resume`, which only waits and checks.
+GitHub's anonymous API allows 60 requests an hour (enough for one release); set `GITHUB_TOKEN`
+for more.
+
+The two steps it runs, if you want them by hand: `tools/bump_version.py` changes every version in one go
+(the Python package, the Rust workspace and the sibling dependency versions of every crate, the
+changelog, the lock files, and with `--npm` the npm packages) and runs
+`tools/check_versions.py` on the result:
+
+```sh
+python tools/bump_version.py minor --commit --push # 0.2.0 -> 0.3.0, commits only those files, pushes main
+# ... wait for CI to go green on that commit ...
+python tools/bump_version.py --tag --push # tags v0.3.0 and pushes the tag: the release starts
+```
+
+`minor` can be `major`, `patch` or an exact `X.Y.Z`; add `--npm patch` to move the npm
+packages too (they are versioned on their own), and `--dry-run` to see what would change. The
+tag step refuses a tag that already exists and a branch that isn't pushed yet. Doing it by hand
+is the same thing: `git tag v0.3.0 && git push origin v0.3.0`.
+
| Workflow | Publishes |
|---|---|
| `wheels.yml` | the Python wheels and sdist to PyPI (trusted publishing, no secret) |
@@ -92,7 +116,8 @@ git tag v0.2.0 && git push --tags
`release.yml` first checks that the tag matches the Python and Rust versions
(`python tools/check_versions.py v0.2.0` runs the same check by hand), then runs the whole
`ci.yml` suite on every platform, then publishes. A version that is already on a registry is
-skipped, so a run that failed halfway (say, crates.io timing out on the big
+skipped (crates.io, npm and PyPI alike: `wheels.yml` builds nothing when PyPI already has the
+version), so only what is missing runs: a run that failed halfway (say, crates.io timing out on the big
`blenderui-sys` upload) can simply be re-run. The npm packages are versioned on their own; bump
them in their `package.json` when they change.
diff --git a/tools/bump_version.py b/tools/bump_version.py
new file mode 100644
index 0000000..a2c079e
--- /dev/null
+++ b/tools/bump_version.py
@@ -0,0 +1,229 @@
+"""Bump the release version everywhere in one command, then tag it once CI is green.
+
+ python tools/bump_version.py minor # 0.2.0 -> 0.3.0 (or patch, major, or 1.0.0)
+ python tools/bump_version.py patch --npm patch # also move the npm packages
+ python tools/bump_version.py minor --commit --push # bump, commit only those files, push main
+ python tools/bump_version.py --tag --push # later, when CI is green: tag and push
+
+A release is two steps, so CI runs on the commit before anything is published:
+
+1. `bump_version.py <new> --commit --push` edits every version (below), runs
+ `tools/check_versions.py`, commits just those files and pushes the branch.
+2. When CI is green, `bump_version.py --tag --push` tags the current version and pushes the
+ tag. The tag starts `release.yml` (crates.io, npm, GitHub Release) and `wheels.yml` (PyPI).
+ Both skip what is already published, so a re-run only does what is missing.
+
+Where the version lives (one source of truth per registry, all moved together):
+
+* Python: `bindings/python/bui/_version.py` (the wheel reads it).
+* Rust: `[workspace.package]` in `bindings/rust/Cargo.toml`, and the `version = "..."` of every
+ sibling path dependency (`blenderui-sys = { path = "...", version = "..." }`).
+* npm (only with `--npm`): `bindings/node` and `bindings/react` move together, and react's
+ dependency on native. npm versions are otherwise independent of the tag.
+* `CHANGELOG.md`: `[Unreleased]` becomes a dated section and a fresh `[Unreleased]` opens.
+* The lock files (`Cargo.lock`, `bindings/package-lock.json`) are refreshed (best effort).
+
+`--dry-run` shows what would change and touches nothing.
+"""
+
+import argparse
+import datetime
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+RUST = ROOT / "bindings" / "rust"
+PY_VERSION = ROOT / "bindings" / "python" / "bui" / "_version.py"
+SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
+
+
+def read(path: Path) -> str:
+ with open(path, encoding="utf-8", newline="") as f: # keep the file's line endings
+ return f.read()
+
+
+def write(path: Path, text: str) -> None:
+ with open(path, "w", encoding="utf-8", newline="") as f:
+ f.write(text)
+
+
+def run(cmd: list[str], cwd: Path = ROOT, check: bool = True) -> subprocess.CompletedProcess:
+ return subprocess.run(cmd, cwd=cwd, text=True, capture_output=True, check=check)
+
+
+def current_version() -> str:
+ m = re.search(r'__version__\s*=\s*"([^"]+)"', read(PY_VERSION))
+ if not m:
+ sys.exit(f"cannot read the version from {PY_VERSION}")
+ return m.group(1)
+
+
+def next_version(cur: str, what: str) -> str:
+ if SEMVER.match(what):
+ return what
+ major, minor, patch = (int(x) for x in cur.split("."))
+ if what == "major":
+ return f"{major + 1}.0.0"
+ if what == "minor":
+ return f"{major}.{minor + 1}.0"
+ if what == "patch":
+ return f"{major}.{minor}.{patch + 1}"
+ sys.exit(f"'{what}' is not major, minor, patch or X.Y.Z")
+
+
+def plan_edits(new: str, npm: str | None) -> dict[Path, str]:
+ """Every file's new text, keyed by path. Nothing is written here."""
+ edits: dict[Path, str] = {}
+
+ def put(path: Path, text: str) -> None:
+ if text != read(path):
+ edits[path] = text
+
+ put(PY_VERSION, re.sub(r'(__version__\s*=\s*")[^"]+(")', rf"\g<1>{new}\g<2>", read(PY_VERSION)))
+
+ ws = RUST / "Cargo.toml"
+ text = read(ws)
+ m = re.search(r"\[workspace\.package\](.*?)(?=^\[|\Z)", text, re.S | re.M)
+ if not m:
+ sys.exit("no [workspace.package] in bindings/rust/Cargo.toml")
+ section = re.sub(r'(^version\s*=\s*")[^"]+(")', rf"\g<1>{new}\g<2>", m.group(1), count=1, flags=re.M)
+ put(ws, text[: m.start(1)] + section + text[m.end(1):])
+
+ # sibling path dependencies of the published crates: `blenderui-x = { path = "..", version = ".." }`
+ for toml in sorted(RUST.glob("*/Cargo.toml")):
+ lines = read(toml).splitlines(keepends=True)
+ out = []
+ for line in lines:
+ if re.match(r"\s*blenderui[\w-]*\s*=\s*\{", line) and "path" in line and "version" in line:
+ line = re.sub(r'(version\s*=\s*")[^"]+(")', rf"\g<1>{new}\g<2>", line)
+ out.append(line)
+ put(toml, "".join(out))
+
+ if npm:
+ for pkg in ("node", "react"):
+ path = ROOT / "bindings" / pkg / "package.json"
+ text = read(path)
+ text = re.sub(r'("version"\s*:\s*")[^"]+(")', rf"\g<1>{npm}\g<2>", text, count=1)
+ text = re.sub(r'("@blender-ui/native"\s*:\s*"\^)[^"]+(")', rf"\g<1>{npm}\g<2>", text)
+ put(path, text)
+
+ log = ROOT / "CHANGELOG.md"
+ text = read(log)
+ if f"## [{new}]" not in text and "## [Unreleased]" in text:
+ nl = "\r\n" if "\r\n" in text else "\n"
+ today = datetime.date.today().isoformat()
+ text = text.replace("## [Unreleased]", f"## [Unreleased]{nl}{nl}## [{new}] - {today}", 1)
+ put(log, text)
+ return edits
+
+
+def refresh_locks(npm: bool) -> list[Path]:
+ """Best effort: a lock file that can't be refreshed is reported, not fatal."""
+ touched = []
+ r = run(["cargo", "update", "--workspace", "--offline"], cwd=RUST, check=False)
+ if r.returncode != 0:
+ r = run(["cargo", "update", "--workspace"], cwd=RUST, check=False)
+ if r.returncode == 0:
+ touched.append(RUST / "Cargo.lock")
+ else:
+ print("warning: Cargo.lock was not refreshed (run `cargo update --workspace` in bindings/rust)")
+ if npm:
+ r = run(["npm", "install", "--package-lock-only", "--ignore-scripts"], cwd=ROOT / "bindings", check=False)
+ if r.returncode == 0:
+ touched.append(ROOT / "bindings" / "package-lock.json")
+ else:
+ print("warning: package-lock.json was not refreshed (run `npm install --package-lock-only` in bindings)")
+ return touched
+
+
+def git(*args: str) -> str:
+ return run(["git", *args]).stdout.strip()
+
+
+def tag_and_push(version: str, push: bool) -> None:
+ tag = f"v{version}"
+ if run([sys.executable, str(ROOT / "tools" / "check_versions.py"), tag], check=False).returncode != 0:
+ sys.exit("the versions do not match the tag: run the bump first")
+ if git("tag", "--list", tag):
+ sys.exit(f"{tag} already exists locally")
+ if git("ls-remote", "--tags", "origin", tag):
+ sys.exit(f"{tag} already exists on origin")
+ if git("status", "--porcelain", "--untracked-files=no"):
+ print("warning: the working tree has uncommitted changes; the tag points at the last commit")
+ if push:
+ ahead = git("rev-list", "--count", "@{u}..HEAD")
+ if ahead != "0":
+ sys.exit(f"{ahead} commit(s) are not pushed yet: push them and wait for CI before tagging")
+ git("tag", tag)
+ print(f"tagged {tag} at {git('rev-parse', '--short', 'HEAD')}")
+ if push:
+ git("push", "origin", tag)
+ print(f"pushed {tag}: release.yml (crates.io, npm, GitHub Release) and wheels.yml (PyPI) are starting")
+ else:
+ print(f"push it with: git push origin {tag}")
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("version", nargs="?", help="major, minor, patch or X.Y.Z (leave out with --tag)")
+ ap.add_argument("--npm", metavar="V", help="also bump the npm packages: patch, minor, major or X.Y.Z")
+ ap.add_argument("--commit", action="store_true", help="commit only the files this changed")
+ ap.add_argument("--tag", action="store_true", help="tag the current version (after CI is green)")
+ ap.add_argument("--push", action="store_true", help="push the branch (with --commit) or the tag (with --tag)")
+ ap.add_argument("--dry-run", action="store_true", help="show what would change and stop")
+ ap.add_argument("--no-lock", action="store_true", help="do not refresh Cargo.lock and package-lock.json")
+ a = ap.parse_args()
+
+ cur = current_version()
+ if a.version is None:
+ if not a.tag:
+ ap.error("give a version (major, minor, patch, X.Y.Z), or --tag")
+ tag_and_push(cur, a.push)
+ return 0
+
+ new = next_version(cur, a.version)
+ if new == cur:
+ sys.exit(f"already at {cur}")
+ npm_new = None
+ if a.npm:
+ node = json.loads(read(ROOT / "bindings" / "node" / "package.json"))["version"]
+ npm_new = next_version(node, a.npm)
+
+ edits = plan_edits(new, npm_new)
+ print(f"{cur} -> {new}" + (f" (npm -> {npm_new})" if npm_new else ""))
+ for path in edits:
+ print(" edit", path.relative_to(ROOT).as_posix())
+ if a.dry_run:
+ return 0
+ for path, text in edits.items():
+ write(path, text)
+ touched = list(edits)
+ if not a.no_lock:
+ touched += refresh_locks(bool(npm_new))
+
+ if run([sys.executable, str(ROOT / "tools" / "check_versions.py"), f"v{new}"], check=False).returncode != 0:
+ print(run([sys.executable, str(ROOT / "tools" / "check_versions.py"), f"v{new}"], check=False).stdout)
+ print("check_versions.py is not happy: a version is missing from this script's list")
+ return 1
+ print(f"all versions agree on {new}")
+
+ if a.commit:
+ files = [p.relative_to(ROOT).as_posix() for p in touched]
+ git("add", "--", *files)
+ git("commit", "-m", f"release: v{new}", "--", *files)
+ print(f"committed release: v{new}")
+ if a.push:
+ git("push", "origin", "HEAD")
+ print("pushed the branch: wait for CI to go green, then: python tools/bump_version.py --tag --push")
+ else:
+ print("push it, wait for CI, then: python tools/bump_version.py --tag --push")
+ else:
+ print("review the diff, then add --commit (or commit by hand)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/release.py b/tools/release.py
new file mode 100644
index 0000000..c427128
--- /dev/null
+++ b/tools/release.py
@@ -0,0 +1,224 @@
+"""Release BUI in one command: bump, push, wait for CI, tag, watch the publish, verify.
+
+ python tools/release.py minor # 0.2.0 -> 0.3.0 (also patch, major, X.Y.Z)
+ python tools/release.py patch --npm patch # and bump the npm packages too
+ python tools/release.py --resume # a bump is already pushed: wait for CI, tag, publish
+ python tools/release.py minor --dry-run # show the plan, change nothing
+
+What it does, in order (it stops at the first problem and never tags a red commit):
+
+1. checks you are on a clean `main` that is not behind `origin`;
+2. `tools/bump_version.py <version> --commit --push`: every version, the changelog and the lock
+ files, committed on their own and pushed (anything you committed before goes out with it);
+3. waits for the `ci` and `wheels` workflows on that commit to finish, and stops if either fails;
+4. `tools/bump_version.py --tag --push`: tags `vX.Y.Z` and pushes the tag, which starts
+ `release.yml` (crates.io, npm, GitHub Release) and `wheels.yml` (PyPI);
+5. waits for those two runs, then checks every registry for the new version.
+
+If a publish step fails (a registry timeout, a secret), nothing needs re-tagging: fix it and use
+"Re-run failed jobs" on the run (the link is printed). Versions already published are skipped.
+
+GitHub's anonymous API allows 60 requests an hour, enough for one release. Set GITHUB_TOKEN (any
+token that can read this public repo) for more.
+"""
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+BUMP = ROOT / "tools" / "bump_version.py"
+PY_VERSION = ROOT / "bindings" / "python" / "bui" / "_version.py"
+
+POLL = 30 if (os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")) else 90 # seconds between checks (60 anonymous requests an hour)
+CI_TIMEOUT = 60 * 60
+PUBLISH_TIMEOUT = 75 * 60
+
+
+def sh(*cmd: str, check: bool = True) -> str:
+ r = subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True, check=False)
+ if check and r.returncode != 0:
+ sys.exit(f"`{' '.join(cmd)}` failed:\n{r.stdout}{r.stderr}")
+ return r.stdout.strip()
+
+
+def bump(*args: str) -> int:
+ return subprocess.run([sys.executable, str(BUMP), *args], cwd=ROOT).returncode
+
+
+def current_version() -> str:
+ m = re.search(r'__version__\s*=\s*"([^"]+)"', PY_VERSION.read_text(encoding="utf-8"))
+ if not m:
+ sys.exit("cannot read the version from _version.py")
+ return m.group(1)
+
+
+def repo_slug() -> str:
+ url = sh("git", "remote", "get-url", "origin")
+ m = re.search(r"github\.com[:/](.+?)(?:\.git)?$", url)
+ if not m:
+ sys.exit(f"origin is not a GitHub remote: {url}")
+ return m.group(1)
+
+
+def http_json(url: str) -> tuple[int, dict]:
+ headers = {"User-Agent": "bui-release-script", "Accept": "application/vnd.github+json"}
+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
+ if token and "api.github.com" in url:
+ headers["Authorization"] = f"Bearer {token}"
+ try:
+ with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=30) as r:
+ return r.status, json.loads(r.read() or b"{}")
+ except urllib.error.HTTPError as e:
+ try:
+ return e.code, json.loads(e.read() or b"{}")
+ except ValueError:
+ return e.code, {}
+ except (urllib.error.URLError, TimeoutError):
+ return 0, {}
+
+
+def runs_for(slug: str, sha: str) -> list[dict]:
+ code, body = http_json(f"https://api.github.com/repos/{slug}/actions/runs?head_sha={sha}&per_page=50")
+ if code == 403 and "rate limit" in str(body.get("message", "")).lower():
+ print(" GitHub's rate limit is hit (set GITHUB_TOKEN to raise it); waiting")
+ return []
+ return body.get("workflow_runs", []) if code == 200 else []
+
+
+def wait_for(slug: str, sha: str, names: set[str], timeout: int, what: str, branch: str) -> bool:
+ """Wait until every workflow in `names` has a finished run of `branch` (a branch or a tag) on `sha`.
+ True when all succeeded."""
+ print(f"waiting for {what} ({', '.join(sorted(names))}) on {sha[:7]} ...")
+ deadline = time.time() + timeout
+ last = ""
+ while time.time() < deadline:
+ latest: dict[str, dict] = {}
+ for r in runs_for(slug, sha):
+ if r["name"] in names and r["head_branch"] == branch:
+ if r["name"] not in latest or r["run_number"] > latest[r["name"]]["run_number"]:
+ latest[r["name"]] = r
+ state = " | ".join(f"{n}: {latest[n]['status']}/{latest[n]['conclusion'] or '-'}" if n in latest else f"{n}: not started"
+ for n in sorted(names))
+ if state != last:
+ print(f" {state}")
+ last = state
+ if len(latest) == len(names) and all(r["status"] == "completed" for r in latest.values()):
+ bad = [r for r in latest.values() if r["conclusion"] != "success"]
+ for r in bad:
+ print(f" FAILED {r['name']}: {r['html_url']}")
+ return not bad
+ time.sleep(POLL)
+ print(f" gave up after {timeout // 60} minutes")
+ return False
+
+
+def crates() -> list[str]:
+ """The crates release.yml publishes (read from it, so there is one list)."""
+ text = (ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8")
+ m = re.search(r"for crate in ([^;]+); do", text)
+ return m.group(1).split() if m else []
+
+
+def registry_status(version: str) -> dict[str, bool]:
+ out: dict[str, bool] = {}
+ for c in crates():
+ out[f"crates.io {c}"] = http_json(f"https://crates.io/api/v1/crates/{c}/{version}")[0] == 200
+ for pkg in ("node", "react"):
+ meta = json.loads((ROOT / "bindings" / pkg / "package.json").read_text(encoding="utf-8"))
+ name = meta["name"].replace("/", "%2F")
+ out[f"npm {meta['name']}@{meta['version']}"] = (
+ http_json(f"https://registry.npmjs.org/{name}/{meta['version']}")[0] == 200)
+ out[f"PyPI blenderui {version}"] = http_json(f"https://pypi.org/pypi/blenderui/{version}/json")[0] == 200
+ return out
+
+
+def verify(version: str) -> bool:
+ print("checking the registries ...")
+ deadline = time.time() + 10 * 60 # indexes lag a little behind a successful publish
+ while True:
+ status = registry_status(version)
+ if all(status.values()) or time.time() > deadline:
+ break
+ time.sleep(POLL)
+ for k, ok in status.items():
+ print(f" {'ok ' if ok else 'MISSING'} {k}")
+ return all(status.values())
+
+
+def preflight(allow_dirty: bool) -> None:
+ if sh("git", "rev-parse", "--abbrev-ref", "HEAD") != "main":
+ sys.exit("release from the main branch")
+ if not allow_dirty and sh("git", "status", "--porcelain", "--untracked-files=no"):
+ sys.exit("you have uncommitted changes to tracked files: commit or stash them (or --allow-dirty)")
+ sh("git", "fetch", "origin")
+ behind = sh("git", "rev-list", "--count", "HEAD..origin/main")
+ if behind != "0":
+ sys.exit(f"main is {behind} commit(s) behind origin: git pull first")
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("version", nargs="?", help="major, minor, patch or X.Y.Z")
+ ap.add_argument("--npm", metavar="V", help="also bump the npm packages: patch, minor, major or X.Y.Z")
+ ap.add_argument("--resume", action="store_true", help="the bump is already committed: wait for CI, tag, publish")
+ ap.add_argument("--dry-run", action="store_true", help="show the plan and stop")
+ ap.add_argument("--yes", action="store_true", help="do not ask before starting")
+ ap.add_argument("--allow-dirty", action="store_true")
+ a = ap.parse_args()
+ if not a.version and not a.resume:
+ ap.error("give a version (major, minor, patch, X.Y.Z) or --resume")
+
+ slug = repo_slug()
+ preflight(a.allow_dirty)
+
+ if a.resume:
+ version = current_version()
+ if a.dry_run:
+ print(f"would wait for CI on HEAD, then tag v{version}")
+ return 0
+ else:
+ extra = ["--npm", a.npm] if a.npm else []
+ if bump(a.version, *extra, "--dry-run") != 0:
+ return 1
+ if a.dry_run:
+ return 0
+ if not a.yes and input("release this? [y/N] ").strip().lower() != "y":
+ print("cancelled; nothing changed")
+ return 1
+ if bump(a.version, *extra, "--commit", "--push") != 0:
+ return 1
+ version = current_version()
+
+ sha = sh("git", "rev-parse", "HEAD")
+ if sh("git", "rev-list", "--count", "@{u}..HEAD") != "0":
+ sh("git", "push", "origin", "HEAD")
+ if not wait_for(slug, sha, {"ci", "wheels"}, CI_TIMEOUT, "CI", branch="main"):
+ print(f"\nCI is not green, so v{version} was NOT tagged. Fix it, push, then: python tools/release.py --resume")
+ return 1
+
+ tag = f"v{version}"
+ if sh("git", "ls-remote", "--tags", "origin", tag):
+ print(f"{tag} is already on origin; not tagging again")
+ elif bump("--tag", "--push") != 0:
+ return 1
+ print(f"\n{tag} is tagged. Watching the publish ...")
+ ok = wait_for(slug, sha, {"release", "wheels"}, PUBLISH_TIMEOUT, "the publish", branch=tag)
+ done = verify(version)
+ if ok and done:
+ print(f"\nv{version} is published everywhere. https://github.com/{slug}/releases/tag/v{version}")
+ return 0
+ print(f"\nNot everything is published. Open https://github.com/{slug}/actions , use \"Re-run failed jobs\" on the "
+ f"failed run (no new tag needed), then run: python tools/release.py --resume (it only checks and waits)")
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())