Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
ci: build native releases across platforms
ldm0f57c8d90a996
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex fab139254..923d75ca1 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -23,7 +23,7 @@ concurrency:cancel-in-progress: falsepermissions:- contents: write+ contents: readenv:CARGO_TERM_COLOR: always@@ -33,11 +33,13 @@ env:GIT_CONFIG_VALUE_0: ${{ github.workspace }}jobs:- release:- name: Build and publish+ validate:+ name: Validate release requestruns-on: ubuntu-latest- timeout-minutes: 90- container: rust:1.96.1-bookworm+ timeout-minutes: 10+ outputs:+ tag: ${{ steps.release.outputs.tag }}+ version: ${{ steps.release.outputs.version }}steps:- name: Checkout repositoryuses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2@@ -45,7 +47,7 @@ jobs:fetch-depth: 0persist-credentials: false- - name: Validate release request+ - name: Validate version and tagid: releaseshell: bashenv:@@ -75,33 +77,198 @@ jobs:echo "version=$version" >> "$GITHUB_OUTPUT"echo "tag=$tag" >> "$GITHUB_OUTPUT"- - name: Build and package release- shell: bash- run: scripts/release.sh --version "${{ steps.release.outputs.version }}"+ build-linux:+ name: Build Linux x86_64+ needs: validate+ runs-on: ubuntu-latest+ timeout-minutes: 90+ container: rust:1.96.1-bookworm+ steps:+ - name: Checkout repository+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false- - name: Install GitHub CLI+ - name: Install packaging dependenciesshell: bashrun: |apt-get update- apt-get install --yes --no-install-recommends gh+ apt-get install --yes --no-install-recommends binutils python3++ - name: Build and package+ shell: bash+ run: >-+ scripts/release.sh+ --version "${{ needs.validate.outputs.version }}"+ --expected-target x86_64-unknown-linux-gnu++ - name: Upload Linux artifact+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: release-linux-x86_64+ path: dist/+ if-no-files-found: error+ compression-level: 0+ retention-days: 7++ build-macos:+ name: Build macOS ${{ matrix.arch }}+ needs: validate+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 120+ strategy:+ fail-fast: false+ matrix:+ include:+ - arch: x86_64+ runner: macos-15-intel+ target: x86_64-apple-darwin+ artifact: release-macos-x86_64+ - arch: aarch64+ runner: macos-15+ target: aarch64-apple-darwin+ artifact: release-macos-aarch64+ env:+ MACOSX_DEPLOYMENT_TARGET: "13.0"+ steps:+ - name: Checkout repository+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false++ - name: Install pinned Rust toolchain+ shell: bash+ run: |+ set -euo pipefail+ toolchain=$(tr -d '[:space:]' < rust-toolchain)+ rustup toolchain install "$toolchain" --profile minimal --no-self-update+ rustc --version++ - name: Build and package+ shell: bash+ run: >-+ scripts/release.sh+ --version "${{ needs.validate.outputs.version }}"+ --expected-target "${{ matrix.target }}"++ - name: Upload macOS artifact+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ${{ matrix.artifact }}+ path: dist/+ if-no-files-found: error+ compression-level: 0+ retention-days: 7++ build-windows:+ name: Build Windows x86_64+ needs: validate+ runs-on: windows-2025+ timeout-minutes: 120+ steps:+ - name: Checkout repository+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false++ - name: Install pinned Rust toolchain+ shell: pwsh+ run: |+ $ErrorActionPreference = "Stop"+ $PSNativeCommandUseErrorActionPreference = $true+ $toolchain = (Get-Content rust-toolchain -Raw).Trim()+ rustup toolchain install $toolchain --profile minimal --no-self-update+ rustc --version++ - name: Build and package+ shell: pwsh+ run: >-+ python scripts/release.py+ --version "${{ needs.validate.outputs.version }}"+ --expected-target x86_64-pc-windows-msvc+ --no-default-features++ - name: Upload Windows artifact+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: release-windows-x86_64+ path: dist/+ if-no-files-found: error+ compression-level: 0+ retention-days: 7++ publish:+ name: Create GitHub Release+ needs:+ - validate+ - build-linux+ - build-macos+ - build-windows+ runs-on: ubuntu-latest+ timeout-minutes: 15+ permissions:+ contents: write+ steps:+ - name: Download packaged artifacts+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ pattern: release-*+ path: dist+ merge-multiple: true++ - name: Verify release assets+ shell: bash+ env:+ RELEASE_VERSION: ${{ needs.validate.outputs.version }}+ run: |+ set -euo pipefail++ expected_archives=(+ "moli-v${RELEASE_VERSION}-x86_64-unknown-linux-gnu.tar.gz"+ "moli-v${RELEASE_VERSION}-x86_64-apple-darwin.tar.gz"+ "moli-v${RELEASE_VERSION}-aarch64-apple-darwin.tar.gz"+ "moli-v${RELEASE_VERSION}-x86_64-pc-windows-msvc.zip"+ )+ for archive in "${expected_archives[@]}"; do+ test -f "dist/$archive"+ test -f "dist/$archive.sha256"+ done++ artifact_count=$(find dist -maxdepth 1 -type f | wc -l)+ if [[ "$artifact_count" -ne 8 ]]; then+ echo "Expected 8 release assets, found $artifact_count." >&2+ find dist -maxdepth 1 -type f -print >&2+ exit 1+ fi++ (+ cd dist+ for checksum in *.sha256; do+ sha256sum --check "$checksum"+ done+ )- name: Create GitHub Releaseshell: bashenv:GH_TOKEN: ${{ github.token }}- RELEASE_TAG: ${{ steps.release.outputs.tag }}+ RELEASE_TAG: ${{ needs.validate.outputs.tag }}+ RELEASE_VERSION: ${{ needs.validate.outputs.version }}RELEASE_DRAFT: ${{ inputs.draft }}RELEASE_PRERELEASE: ${{ inputs.prerelease }}run: |set -euo pipefail- shopt -s nullglob- assets=(dist/*.tar.gz dist/*.sha256)- if (( ${#assets[@]} != 2 )); then- echo "Expected one archive and one checksum, found ${#assets[@]} release assets." >&2- exit 1- fi-+ assets=(+ "dist/moli-v${RELEASE_VERSION}-x86_64-unknown-linux-gnu.tar.gz"+ "dist/moli-v${RELEASE_VERSION}-x86_64-unknown-linux-gnu.tar.gz.sha256"+ "dist/moli-v${RELEASE_VERSION}-x86_64-apple-darwin.tar.gz"+ "dist/moli-v${RELEASE_VERSION}-x86_64-apple-darwin.tar.gz.sha256"+ "dist/moli-v${RELEASE_VERSION}-aarch64-apple-darwin.tar.gz"+ "dist/moli-v${RELEASE_VERSION}-aarch64-apple-darwin.tar.gz.sha256"+ "dist/moli-v${RELEASE_VERSION}-x86_64-pc-windows-msvc.zip"+ "dist/moli-v${RELEASE_VERSION}-x86_64-pc-windows-msvc.zip.sha256"+ )args=(release create "$RELEASE_TAG""${assets[@]}"diff --git a/RELEASING.md b/RELEASING.mdindex 15ca5ffd0..254ec85b8 100644--- a/RELEASING.md+++ b/RELEASING.md@@ -1,24 +1,48 @@# Releasing Moli-The release workflow currently builds one precompiled artifact for-`x86_64-unknown-linux-gnu`. The archive contains the `moli` binary, project-licenses, README, version marker, and third-party license notices. A SHA-256-checksum is published beside it. The packager strips its staging copy of the-binary while leaving `target/release/moli` unchanged for local debugging.+The release workflow builds and publishes four native archives:++| System | Rust target | Archive |+| --- | --- | --- |+| Linux x86_64 | `x86_64-unknown-linux-gnu` | `.tar.gz` |+| macOS Intel | `x86_64-apple-darwin` | `.tar.gz` |+| macOS Apple Silicon | `aarch64-apple-darwin` | `.tar.gz` |+| Windows x86_64 | `x86_64-pc-windows-msvc` | `.zip` |++Every archive contains the `moli` executable, project licenses, README,+version marker, and third-party license notices. A SHA-256 checksum is+published beside each archive.++Each artifact is built on its native GitHub-hosted runner. The packager strips+only a staging copy, leaving the binary under `target/release` unchanged for+debugging. Because stripping invalidates a Mach-O signature, macOS staging+binaries are ad-hoc signed again and verified before packaging. They are not+Developer ID signed or notarized. Windows executables are not Authenticode+signed. The Windows build disables the default `jemalloc` feature and uses the+system allocator because upstream treats the Windows/MSVC combination as+untested.## Prepare the release1. Update `version` in `moli/Cargo.toml` and refresh `Cargo.lock`.2. Commit and push those changes to the ref that should be released.-3. Optionally build the exact same package locally:+3. Optionally build the package for your current operating system locally.++ Linux or macOS:```bashscripts/release.sh --version 0.1.0```- Artifacts are written to `dist/`. The script rejects a version that does- not match `moli/Cargo.toml` and verifies the packaged binary's reported- version.+ Windows PowerShell:++ ```powershell+ python scripts/release.py --version 0.1.0 --no-default-features+ ```++ Artifacts are written to `dist/`. The packager rejects a version that does+ not match `moli/Cargo.toml`, checks the native Rust target, strips the staged+ executable, and verifies the packaged binary's reported version.## Trigger GitHub Release@@ -27,7 +51,8 @@ binary while leaving `target/release/moli` unchanged for local debugging.3. Enter the version (with or without a leading `v`).4. Choose whether the release should be a prerelease or a draft, then run it.-The workflow builds the selected commit, creates the corresponding `vX.Y.Z`-tag, generates release notes, and uploads the archive and checksum. It stops-without publishing if the requested version does not match the manifest or if-the tag already exists.+The workflow validates the selected commit, builds all four native artifacts+in parallel, verifies every checksum, creates the corresponding `vX.Y.Z` tag,+generates release notes, and uploads all archives and checksums. It stops+without creating a release if any platform fails, if the requested version+does not match the manifest, or if the tag already exists.diff --git a/scripts/release.py b/scripts/release.pynew file mode 100755index 000000000..29d002b34--- /dev/null+++ b/scripts/release.py@@ -0,0 +1,373 @@+#!/usr/bin/env python3+"""Build, strip, verify, and package a native Moli release artifact."""++from __future__ import annotations++import argparse+import hashlib+import os+import re+import shlex+import shutil+import subprocess+import sys+import tarfile+import tempfile+import tomllib+import zipfile+from pathlib import Path+from typing import Sequence+++REPO_ROOT = Path(__file__).resolve().parent.parent+MANIFEST_PATH = REPO_ROOT / "moli" / "Cargo.toml"+SEMVER_PATTERN = re.compile(+ r"^(0|[1-9][0-9]*)\."+ r"(0|[1-9][0-9]*)\."+ r"(0|[1-9][0-9]*)"+ r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"+)+TARGET_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+$")+++class ReleaseError(RuntimeError):+ """A release precondition or command failed."""+++def display_command(command: Sequence[str]) -> str:+ return shlex.join(str(part) for part in command)+++def run_checked(+ command: Sequence[str], *, capture_output: bool = False+) -> subprocess.CompletedProcess[str]:+ rendered = display_command(command)+ print(f"+ {rendered}", flush=True)+ try:+ return subprocess.run(+ [str(part) for part in command],+ cwd=REPO_ROOT,+ check=True,+ text=True,+ stdout=subprocess.PIPE if capture_output else None,+ stderr=subprocess.PIPE if capture_output else None,+ )+ except FileNotFoundError as error:+ raise ReleaseError(f"command not found: {command[0]}") from error+ except subprocess.CalledProcessError as error:+ if error.stdout:+ print(error.stdout, end="", file=sys.stderr)+ if error.stderr:+ print(error.stderr, end="", file=sys.stderr)+ raise ReleaseError(+ f"command failed with exit code {error.returncode}: {rendered}"+ ) from error+++def normalize_version(raw_version: str) -> str:+ version = raw_version.removeprefix("v")+ if not SEMVER_PATTERN.fullmatch(version):+ raise ReleaseError(f"invalid semantic version: {raw_version}")+ return version+++def manifest_version() -> str:+ with MANIFEST_PATH.open("rb") as manifest_file:+ manifest = tomllib.load(manifest_file)+ try:+ value = manifest["package"]["version"]+ except (KeyError, TypeError) as error:+ raise ReleaseError(f"package.version is missing from {MANIFEST_PATH}") from error+ if not isinstance(value, str):+ raise ReleaseError(f"package.version in {MANIFEST_PATH} is not a string")+ return value+++def rust_host_target() -> str:+ output = run_checked(["rustc", "-vV"], capture_output=True).stdout+ for line in output.splitlines():+ if line.startswith("host: "):+ target = line.removeprefix("host: ").strip()+ if not TARGET_PATTERN.fullmatch(target):+ break+ return target+ raise ReleaseError("could not determine the Rust host target from `rustc -vV`")+++def resolve_repo_path(raw_path: str) -> Path:+ path = Path(raw_path).expanduser()+ if not path.is_absolute():+ path = REPO_ROOT / path+ return path.resolve()+++def default_binary_path(target: str) -> Path:+ target_dir = resolve_repo_path(os.environ.get("CARGO_TARGET_DIR", "target"))+ suffix = ".exe" if "-windows-" in target else ""+ return target_dir / "release" / f"moli{suffix}"+++def build_release(*, no_default_features: bool) -> None:+ command = ["cargo", "build", "--locked", "--release", "--package", "moli"]+ if no_default_features:+ command.append("--no-default-features")+ run_checked(command)+++def find_strip_tool(target: str) -> str:+ configured = os.environ.get("STRIP")+ candidates = [configured] if configured else []+ if "-windows-" in target:+ candidates.append("llvm-strip")+ if program_files := os.environ.get("ProgramFiles"):+ llvm_strip = Path(program_files) / "LLVM" / "bin" / "llvm-strip.exe"+ candidates.append(str(llvm_strip))+ candidates.append("strip")+ else:+ candidates.append("strip")++ for candidate in candidates:+ if not candidate:+ continue+ resolved = shutil.which(candidate)+ if resolved:+ return resolved+ candidate_path = Path(candidate)+ if candidate_path.is_file():+ return str(candidate_path.resolve())++ names = ", ".join(candidates)+ raise ReleaseError(f"no compatible strip tool found (tried: {names})")+++def strip_and_sign(binary: Path, target: str) -> tuple[int, int]:+ before = binary.stat().st_size+ run_checked([find_strip_tool(target), str(binary)])++ if target.endswith("-apple-darwin"):+ # Stripping changes a signed Mach-O file, so replace the invalidated+ # signature with an ad-hoc signature before verification and packaging.+ run_checked(["codesign", "--force", "--sign", "-", str(binary)])+ run_checked(["codesign", "--verify", "--strict", str(binary)])++ after = binary.stat().st_size+ return before, after+++def binary_reported_version(binary: Path) -> str:+ return run_checked([str(binary), "version"], capture_output=True).stdout.strip()+++def copy_release_materials(package_dir: Path) -> None:+ files = [+ REPO_ROOT / "README.md",+ REPO_ROOT / "RELEASING.md",+ REPO_ROOT / "LICENSE",+ REPO_ROOT / "LICENSE-APACHE",+ REPO_ROOT / "LICENSE-MIT",+ ]+ notice_dirs = [+ REPO_ROOT / "third_party" / "licenses",+ REPO_ROOT / "third_party" / "notices",+ ]++ for source in files:+ if not source.is_file():+ raise ReleaseError(f"required release file is missing: {source}")+ shutil.copy2(source, package_dir / source.name)++ notices_dir = package_dir / "third_party"+ notices_dir.mkdir()+ for source in notice_dirs:+ if not source.is_dir():+ raise ReleaseError(f"required license directory is missing: {source}")+ shutil.copytree(source, notices_dir / source.name)+++def write_archive(+ package_dir: Path, archive_path: Path, package_name: str, target: str+) -> None:+ if "-windows-" in target:+ with zipfile.ZipFile(+ archive_path,+ mode="w",+ compression=zipfile.ZIP_DEFLATED,+ compresslevel=9,+ ) as archive:+ for source in sorted(package_dir.rglob("*")):+ if source.is_file():+ relative = source.relative_to(package_dir).as_posix()+ archive.write(source, arcname=f"{package_name}/{relative}")+ return++ with tarfile.open(+ archive_path,+ mode="w:gz",+ format=tarfile.PAX_FORMAT,+ compresslevel=9,+ ) as archive:+ archive.add(package_dir, arcname=package_name, recursive=True)+++def verify_archive(archive_path: Path, expected_binary: str, target: str) -> None:+ if "-windows-" in target:+ with zipfile.ZipFile(archive_path, mode="r") as archive:+ bad_member = archive.testzip()+ if bad_member:+ raise ReleaseError(+ f"archive verification failed for ZIP member: {bad_member}"+ )+ members = set(archive.namelist())+ else:+ with tarfile.open(archive_path, mode="r:gz") as archive:+ members = set(archive.getnames())++ if expected_binary not in members:+ raise ReleaseError(+ f"archive verification failed: {expected_binary} is not in {archive_path.name}"+ )+++def sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as input_file:+ for chunk in iter(lambda: input_file.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def package_release(+ *, version: str, target: str, binary: Path, output_dir: Path+) -> tuple[Path, Path, int, int]:+ package_name = f"moli-v{version}-{target}"+ extension = ".zip" if "-windows-" in target else ".tar.gz"+ archive_path = output_dir / f"{package_name}{extension}"+ checksum_path = output_dir / f"{archive_path.name}.sha256"++ output_dir.mkdir(parents=True, exist_ok=True)+ for output in (archive_path, checksum_path):+ if output.exists():+ raise ReleaseError(f"release output already exists: {output}")++ with tempfile.TemporaryDirectory(prefix=".moli-release-", dir=output_dir) as raw:+ staging_dir = Path(raw)+ package_dir = staging_dir / package_name+ package_dir.mkdir()++ packaged_binary_name = "moli.exe" if "-windows-" in target else "moli"+ packaged_binary = package_dir / packaged_binary_name+ shutil.copy2(binary, packaged_binary)+ if "-windows-" not in target:+ packaged_binary.chmod(packaged_binary.stat().st_mode | 0o111)++ original_size, stripped_size = strip_and_sign(packaged_binary, target)+ reported_version = binary_reported_version(packaged_binary)+ if reported_version != version:+ raise ReleaseError(+ "packaged binary version does not match the requested version: "+ f"expected {version}, got {reported_version or '<empty>'}"+ )++ copy_release_materials(package_dir)+ (package_dir / "VERSION").write_text(f"{version}\n", encoding="utf-8")++ staged_archive = staging_dir / archive_path.name+ write_archive(package_dir, staged_archive, package_name, target)+ verify_archive(+ staged_archive,+ f"{package_name}/{packaged_binary_name}",+ target,+ )++ digest = sha256(staged_archive)+ staged_checksum = staging_dir / checksum_path.name+ staged_checksum.write_text(+ f"{digest} {archive_path.name}\n", encoding="ascii"+ )+ if sha256(staged_archive) != digest:+ raise ReleaseError("archive checksum changed during packaging")++ staged_archive.rename(archive_path)+ staged_checksum.rename(checksum_path)++ return archive_path, checksum_path, original_size, stripped_size+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--version", required=True, help="release version, with optional v")+ parser.add_argument(+ "--output-dir",+ default="dist",+ help="artifact output directory relative to the repository (default: dist)",+ )+ parser.add_argument(+ "--binary",+ help="prebuilt binary path (default: target/release/moli[.exe])",+ )+ parser.add_argument(+ "--skip-build",+ action="store_true",+ help="package an existing binary without running cargo build",+ )+ parser.add_argument(+ "--expected-target",+ help="fail unless the native rustc host target matches this value",+ )+ parser.add_argument(+ "--no-default-features",+ action="store_true",+ help="pass --no-default-features to cargo build",+ )+ return parser.parse_args()+++def main() -> int:+ args = parse_args()+ try:+ version = normalize_version(args.version)+ declared_version = manifest_version()+ if version != declared_version:+ raise ReleaseError(+ f"requested version {version} does not match "+ f"moli/Cargo.toml ({declared_version})"+ )++ target = rust_host_target()+ if args.expected_target and target != args.expected_target:+ raise ReleaseError(+ f"expected Rust host target {args.expected_target}, got {target}"+ )++ if not args.skip_build:+ build_release(no_default_features=args.no_default_features)++ binary = (+ resolve_repo_path(args.binary)+ if args.binary+ else default_binary_path(target)+ )+ if not binary.is_file():+ raise ReleaseError(f"release binary not found: {binary}")++ output_dir = resolve_repo_path(args.output_dir)+ archive, checksum, before, after = package_release(+ version=version,+ target=target,+ binary=binary,+ output_dir=output_dir,+ )++ print(f"Packaged target: {target}")+ print(f"Staged binary: {before:,} -> {after:,} bytes after strip")+ print(f"Created: {archive}")+ print(f"Created: {checksum}")+ return 0+ except ReleaseError as error:+ print(f"release error: {error}", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/release.sh b/scripts/release.shindex 161c9bf74..eadc2d97f 100755--- a/scripts/release.sh+++ b/scripts/release.sh@@ -1,190 +1,5 @@#!/usr/bin/env bash-set -euo pipefail-script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"-repo_root="$(cd -- "$script_dir/.." && pwd -P)"--usage() {- cat <<'EOF'-Build and package a Moli release.--Usage:- scripts/release.sh --version <VERSION> [options]--Options:- --version <VERSION> Release version, with or without a leading "v".- --output-dir <DIR> Artifact directory (defaults to ./dist).- --binary <PATH> Binary to package (defaults to Cargo's release output).- --skip-build Package an existing binary instead of running Cargo.- -h, --help Show this help.--Examples:- scripts/release.sh --version 0.1.0- scripts/release.sh --version v0.1.0 --skip-build --binary target/release/moli-EOF-}--fail() {- printf 'release: %s\n' "$*" >&2- exit 1-}--require_value() {- local option="$1"- local value="${2:-}"- [[ -n "$value" ]] || fail "$option requires a value"-}--release_version=""-output_dir="$repo_root/dist"-binary=""-skip_build=false--while (( $# > 0 )); do- case "$1" in- --version)- require_value "$1" "${2:-}"- release_version="$2"- shift 2- ;;- --output-dir)- require_value "$1" "${2:-}"- output_dir="$2"- shift 2- ;;- --binary)- require_value "$1" "${2:-}"- binary="$2"- shift 2- ;;- --skip-build)- skip_build=true- shift- ;;- -h|--help)- usage- exit 0- ;;- *)- fail "unknown argument: $1"- ;;- esac-done--[[ -n "$release_version" ]] || fail "--version is required"--version="${release_version#v}"-semver_pattern='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'-[[ "$version" =~ $semver_pattern ]] || fail "invalid semantic version: $release_version"--manifest_version="$(- awk '$1 == "version" && $2 == "=" { gsub(/"/, "", $3); print $3; exit }' \- "$repo_root/moli/Cargo.toml"-)"-[[ -n "$manifest_version" ]] || fail "could not read the version from moli/Cargo.toml"-[[ "$version" == "$manifest_version" ]] || \- fail "requested version $version does not match moli/Cargo.toml ($manifest_version)"--cd -- "$repo_root"--target="$(rustc -vV | awk '$1 == "host:" { print $2; exit }')"-[[ "$target" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]*$ ]] || fail "invalid Rust target: $target"--if [[ "$skip_build" == false ]]; then- cargo build --locked --release --package moli-fi--if [[ -z "$binary" ]]; then- target_dir="${CARGO_TARGET_DIR:-$repo_root/target}"- if [[ "$target_dir" != /* ]]; then- target_dir="$repo_root/$target_dir"- fi- binary="$target_dir/release/moli"-elif [[ "$binary" != /* ]]; then- binary="$repo_root/$binary"-fi--[[ -f "$binary" ]] || fail "binary does not exist: $binary"-[[ -x "$binary" ]] || fail "binary is not executable: $binary"--binary_version="$("$binary" version)"-[[ "$binary_version" == "$version" ]] || \- fail "binary reports version $binary_version, expected $version"--for required_file in README.md RELEASING.md LICENSE LICENSE-APACHE LICENSE-MIT; do- [[ -f "$repo_root/$required_file" ]] || fail "missing release file: $required_file"-done-for required_dir in third_party/licenses third_party/notices; do- [[ -d "$repo_root/$required_dir" ]] || fail "missing release directory: $required_dir"-done--mkdir -p -- "$output_dir"-output_dir="$(cd -- "$output_dir" && pwd -P)"--package_name="moli-v${version}-${target}"-archive_name="$package_name.tar.gz"-checksum_name="$archive_name.sha256"--[[ ! -e "$output_dir/$archive_name" ]] || fail "artifact already exists: $output_dir/$archive_name"-[[ ! -e "$output_dir/$checksum_name" ]] || fail "artifact already exists: $output_dir/$checksum_name"--staging_root="$(mktemp -d "$output_dir/.moli-release.XXXXXX")"-cleanup() {- if [[ -n "${staging_root:-}" && -d "$staging_root" ]]; then- rm -rf -- "$staging_root"- fi-}-trap cleanup EXIT--package_dir="$staging_root/$package_name"-mkdir -p -- "$package_dir/third_party"-install -m 0755 -- "$binary" "$package_dir/moli"--strip_tool="${STRIP:-strip}"-command -v -- "$strip_tool" >/dev/null 2>&1 || fail "strip tool does not exist: $strip_tool"-unstripped_size="$(wc -c < "$package_dir/moli")"-"$strip_tool" "$package_dir/moli"-stripped_size="$(wc -c < "$package_dir/moli")"-packaged_version="$("$package_dir/moli" version)"-[[ "$packaged_version" == "$version" ]] || \- fail "stripped binary reports version $packaged_version, expected $version"-printf 'Stripped packaged binary: %s -> %s bytes\n' "$unstripped_size" "$stripped_size"--install -m 0644 -- \- "$repo_root/README.md" \- "$repo_root/RELEASING.md" \- "$repo_root/LICENSE" \- "$repo_root/LICENSE-APACHE" \- "$repo_root/LICENSE-MIT" \- "$package_dir/"-cp -R -- "$repo_root/third_party/licenses" "$package_dir/third_party/licenses"-cp -R -- "$repo_root/third_party/notices" "$package_dir/third_party/notices"-printf '%s\n' "$version" > "$package_dir/VERSION"--tar -C "$staging_root" -czf "$staging_root/$archive_name" "$package_name"-tar -tzf "$staging_root/$archive_name" > "$staging_root/archive-contents.txt"-grep -Fxq "$package_name/moli" "$staging_root/archive-contents.txt" || \- fail "packaged archive does not contain the moli binary"--if command -v sha256sum >/dev/null 2>&1; then- (- cd -- "$staging_root"- sha256sum "$archive_name" > "$checksum_name"- sha256sum --check "$checksum_name"- )-elif command -v shasum >/dev/null 2>&1; then- (- cd -- "$staging_root"- shasum -a 256 "$archive_name" > "$checksum_name"- shasum -a 256 --check "$checksum_name"- )-else- fail "sha256sum or shasum is required"-fi--mv -- "$staging_root/$archive_name" "$output_dir/$archive_name"-mv -- "$staging_root/$checksum_name" "$output_dir/$checksum_name"--printf 'Created %s\n' "$output_dir/$archive_name"-printf 'Created %s\n' "$output_dir/$checksum_name"+script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)+exec python3 "$script_dir/release.py" "$@"