From afa29537428c58e3fc615ae904ed06598f696046 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 17 Sep 2026 01:47:42 +0200 Subject: [PATCH] Add local Cross build and deterministic archive stages --- AGENT_TASKS.md | 100 +++++++++--------- Cargo.lock | 121 ++++++++++++++++++++++ Cargo.toml | 2 + README.md | 4 +- src/build.rs | 263 +++++++++++++++++++++++++++++++++++++++++++++- src/cli.rs | 75 +++++++++++++- src/main.rs | 2 + src/package.rs | 276 ++++++++++++++++++++++++++++++++++++++++++++++++- src/project.rs | 3 + src/runner.rs | 85 ++++++++++++--- 10 files changed, 857 insertions(+), 74 deletions(-) diff --git a/AGENT_TASKS.md b/AGENT_TASKS.md index 4c291e7..98c19f2 100644 --- a/AGENT_TASKS.md +++ b/AGENT_TASKS.md @@ -14,9 +14,9 @@ The Python implementation remains the behavioral oracle until the Rust replaceme - Defer live API release tests until a disposable token is provided. - Use the small `target_test_project` submodule for fast build and cross-target experiments. -Current Rust milestone: `inspect` and `metadata` stages work for local packages and managed remote Git checkouts, including exact workspace package selection. The metadata stage validates and can repair the selected manifest with `--fix-metadata`; dry-run previews changes without writing. A shared subprocess runner redacts tokens and URL arguments and removes Gitea tokens from child environments. Preparation, builds, and release actions still use the Python worker. +Current Rust milestone: `inspect`, `metadata`, host `verify`, Cross `build`, and local `package` stages are implemented. The tiny fixture built and packaged for x86_64 Linux musl; aarch64 Linux musl built in the matrix attempt. Windows GNU failed in the current Cross 0.2.5 image because the linker could not find `-lsynchronization`. The full target matrix gate remains open. Repository preparation and Gitea publication still use the Python worker. -Progress tracking: check a task only when the Rust behavior is implemented and locally verified. Keep phase gates open until their full fixture/parity criteria pass. Latest verified Rust checks: `cargo test --locked --offline --all` (10 tests), `cargo fmt --check`, and strict Clippy. The Python baseline has 45 passing tests and two opt-in tests skipped. CI runs Cargo tests only; Cross and live Gitea tests are deferred. Next work: complete runner environment controls and source acquisition tests, then build the repository preparation and local build pipeline. +Progress tracking: check a task only when the Rust behavior is implemented and locally verified. Keep phase gates open until their full fixture/parity criteria pass. The Python baseline has 45 passing tests and two opt-in tests skipped. CI runs Cargo tests only; Cross and live Gitea tests are deferred. Next work: validate a real local target build, complete repository preparation, and port mocked Gitea publication and artifact verification. Work in small, testable phases. Commit migration work in coherent increments. @@ -117,9 +117,9 @@ Suggested dependencies: - [ ] `reqwest` with rustls - [x] `url` - [x] `tempfile` -- [ ] `sha2` +- [x] `sha2` - [ ] `tar` -- [ ] `flate2` +- [x] `flate2` Test-only as useful: @@ -185,15 +185,15 @@ Test-only as useful: - [x] Implement argv-based subprocess runner. - [x] Support cwd. -- [ ] Support env additions/removals. +- [x] Support env additions/removals. - [x] Support captured output. - [ ] Support streaming where useful. -- [ ] Add verbose diagnostics. +- [x] Add verbose diagnostics. - [x] Add exit-code/error context. ### Secret safety -- [ ] Redact `GITEA_TOKEN`. +- [x] Redact `GITEA_TOKEN`. - [x] Redact configured token env variable. - [x] Redact credentials in URLs. - [ ] Ensure child Cargo/Cross build processes do not inherit Gitea token. @@ -258,7 +258,7 @@ Test-only as useful: - [x] Parse package/workspace information. - [x] Resolve workspace root. - [x] Resolve selected member manifest. -- [ ] Resolve target directory. +- [x] Resolve target directory. - [x] Resolve inherited package version. - [x] Resolve inherited repository. @@ -404,16 +404,16 @@ Test-only as useful: ## Phase 9 — Port prerequisite checks -- [ ] Detect `git`. -- [ ] Detect `cargo`. -- [ ] Detect `cross`. -- [ ] Detect Docker. -- [ ] Detect Podman. -- [ ] Honor `CROSS_CONTAINER_ENGINE`. -- [ ] Determine usable container backend. -- [ ] Detect `cargo-binstall` when needed. -- [ ] Report all missing prerequisites before cross build. -- [ ] Dry-run performs only read-only checks. +- [x] Detect `git`. +- [x] Detect `cargo`. +- [x] Detect `cross`. +- [x] Detect Docker. +- [x] Detect Podman. +- [x] Honor `CROSS_CONTAINER_ENGINE`. +- [x] Determine usable container backend. +- [x] Detect `cargo-binstall` when needed. +- [x] Report all missing prerequisites before cross build. +- [x] Dry-run performs only read-only checks. ### Gate @@ -425,27 +425,27 @@ Test-only as useful: ### Host validation -- [ ] Run `cargo check` for selected package. -- [ ] Run `cargo test` for selected package. -- [ ] Respect `--skip-tests`. -- [ ] Preserve selected workspace package scoping. +- [x] Run `cargo check` for selected package. +- [x] Run `cargo test` for selected package. +- [x] Respect `--skip-tests`. +- [x] Preserve selected workspace package scoping. ### Cross build -- [ ] Build default Linux x86_64 musl. -- [ ] Build default Linux aarch64 musl. +- [x] Build default Linux x86_64 musl. +- [x] Build default Linux aarch64 musl. - [ ] Build default Windows GNU x86_64. -- [ ] Respect repeatable `--target`. -- [ ] Respect profile. -- [ ] Respect locked/unlocked behavior. -- [ ] Pass selected workspace package correctly. -- [ ] Use fresh target subdirectory for every real release build. -- [ ] Preserve cross image configuration behavior. -- [ ] Do not pass Gitea token to build subprocesses. +- [x] Respect repeatable `--target`. +- [x] Respect profile. +- [x] Respect locked/unlocked behavior. +- [x] Pass selected workspace package correctly. +- [x] Use fresh target subdirectory for every real release build. +- [x] Preserve cross image configuration behavior. +- [x] Do not pass Gitea token to build subprocesses. ### Tests -- [ ] Command-construction unit tests. +- [x] Command-construction unit tests. - [ ] Fake-runner orchestration tests. - [ ] Real host Cargo fixture test. - [ ] Real Cross tests behind opt-in environment gate. @@ -462,35 +462,35 @@ Test-only as useful: ### Packaging - [ ] Locate built binary. -- [ ] Apply target-specific executable filename. -- [ ] Create standardized archive root. -- [ ] Preserve Unix executable mode. -- [ ] Create `.tgz`. -- [ ] Exclude unrelated files. -- [ ] Validate archive members against traversal paths. +- [x] Apply target-specific executable filename. +- [x] Create standardized archive root. +- [x] Preserve Unix executable mode. +- [x] Create `.tgz`. +- [x] Exclude unrelated files. +- [x] Validate archive members against traversal paths. ### Checksums -- [ ] Compute SHA-256. -- [ ] Generate deterministic `SHA256SUMS`. -- [ ] Keep stable asset ordering. +- [x] Compute SHA-256. +- [x] Generate deterministic `SHA256SUMS`. +- [x] Keep stable asset ordering. ### Reproducibility -- [ ] Normalize archive metadata where safe. +- [x] Normalize archive metadata where safe. - [ ] Document any intentional difference from Python archive bytes. - [ ] Keep naming/layout identical regardless. ### Tests -- [ ] Archive filename. -- [ ] Archive root. -- [ ] Unix binary mode. -- [ ] Windows `.exe`. -- [ ] SHA-256 generation. -- [ ] SHA256SUMS content. -- [ ] No extra files. -- [ ] Traversal/path safety. +- [x] Archive filename. +- [x] Archive root. +- [x] Unix binary mode. +- [x] Windows `.exe`. +- [x] SHA-256 generation. +- [x] SHA256SUMS content. +- [x] No extra files. +- [x] Traversal/path safety. ### Gate diff --git a/Cargo.lock b/Cargo.lock index 5decbd3..ad8b9d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.5" @@ -67,6 +73,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -119,6 +134,44 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -152,6 +205,17 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -161,6 +225,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -333,6 +407,16 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -418,9 +502,11 @@ name = "rust_realease" version = "0.1.0" dependencies = [ "clap", + "flate2", "regex", "serde", "serde_json", + "sha2", "tempfile", "toml", "toml_edit", @@ -492,6 +578,23 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "smallvec" version = "1.16.1" @@ -618,6 +721,12 @@ version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -648,6 +757,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "windows-link" version = "0.2.1" @@ -755,6 +870,12 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 972a76c..ca7a675 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,3 +13,5 @@ toml_edit = "0.25" url = "2.5" tempfile = "3" regex = "1" +flate2 = "1.1" +sha2 = "0.10" diff --git a/README.md b/README.md index 651efcd..cbb5744 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Rust Binstall Publisher -> Rust migration status: the Rust binary currently supports local and remote Git project inspection and metadata validation/repair through `--stop-after metadata`, including exact workspace `--package` selection. Remote sources are cloned to managed temporary directories; `--keep-workdir` retains them for review. The Python worker remains the release implementation for builds and publication. The `target_test_project` submodule is a tiny binary fixture for upcoming build tests. +> Rust migration status: the Rust binary supports local and remote Git project inspection, metadata validation/repair, host check/test (`--stop-after verify`), Cross builds (`--stop-after build`), and local `.tgz`/SHA256SUMS packaging (`--stop-after package`). Remote sources are cloned to managed temporary directories; `--keep-workdir` retains them for review. The tiny fixture built for both Linux targets and packaged for x86_64 Linux musl. The Windows GNU build failed in the current Cross 0.2.5 image because the linker could not find `-lsynchronization`; the full target matrix remains unverified. The Python worker remains the release implementation for repository preparation and publication. -Build and inspect locally with `cargo run -- target_test_project --stop-after inspect`. Validate metadata with `cargo run -- target_test_project --stop-after metadata`; add `--dry-run` to preview proposed repairs or `--fix-metadata` to write them. Run the Rust checks with `cargo fmt --check`, `cargo clippy --offline --all-targets --all-features -- -D warnings`, and `cargo test --offline`. Live Gitea tests are deferred until a disposable token is available. +Inspect locally with `cargo run -- target_test_project --stop-after inspect`. Validate metadata with `cargo run -- target_test_project --stop-after metadata`; add `--dry-run` to preview proposed repairs or `--fix-metadata` to write them. Run host checks with `cargo run -- target_test_project --stop-after verify`. Build and package locally with `--stop-after package` once Cross and a container backend are available. Run the Rust checks with `cargo fmt --check`, `cargo clippy --offline --all-targets --all-features -- -D warnings`, and `cargo test --offline`. Live Gitea tests are deferred until a disposable token is available. A small Python release tool for Rust CLI projects on Gitea, releasing one package with one binary at a time. It inspects Cargo metadata, checks version tags, cross-compiles binaries, creates reproducible `.tgz` archives and SHA-256 checksums, uploads a release, and verifies the downloads with cargo-binstall. diff --git a/src/build.rs b/src/build.rs index 61288d0..0d0ce74 100644 --- a/src/build.rs +++ b/src/build.rs @@ -1 +1,262 @@ -//! Placeholder for the future build implementation. +use crate::{config::Config, error::Error, policy, project::SelectedPackage, runner::Runner}; +use std::{ + env, fs, + path::{Path, PathBuf}, +}; + +pub fn prerequisites( + root: &Path, + config: &Config, + needs_cross: bool, + needs_binstall: bool, + runner: &Runner, +) -> (Vec, Option) { + let mut problems = Vec::new(); + if let Err(error) = validate_cross_config(root) { + problems.push(error.to_string()); + } + for tool in ["git", "cargo"] + .into_iter() + .chain(needs_cross.then_some("cross")) + .chain(needs_binstall.then_some("cargo-binstall")) + { + if executable(tool).is_none() { + problems.push(format!("{tool} is missing")); + } + } + let mut engine = None; + if needs_cross { + let requested = env::var("CROSS_CONTAINER_ENGINE").ok(); + let candidate = requested.or_else(|| { + ["docker", "podman"] + .into_iter() + .find(|tool| executable(tool).is_some()) + .map(str::to_owned) + }); + match candidate.as_deref() { + Some("docker" | "podman") => { + if let Some(candidate) = candidate { + if let Err(error) = runner.output(&candidate, &["info"], root) { + problems.push(error.to_string()); + } else { + engine = Some(candidate); + } + } + } + _ => problems.push( + "Set CROSS_CONTAINER_ENGINE to docker or podman with a usable backend".into(), + ), + } + } + if config.locked && !root.join("Cargo.lock").is_file() { + problems.push("Cargo.lock is missing; generate it explicitly or use --unlocked".into()); + } + (problems, engine) +} + +fn executable(name: &str) -> Option { + let path = env::var_os("PATH")?; + env::split_paths(&path) + .map(|dir| dir.join(name)) + .find(|path| path.is_file()) +} + +fn validate_cross_config(root: &Path) -> Result<(), Error> { + let source = fs::read_to_string(root.join("Cargo.toml")) + .map_err(|e| Error(format!("cannot inspect root Cargo.toml: {e}")))?; + let manifest: toml::Value = + toml::from_str(&source).map_err(|e| Error(format!("invalid root Cargo.toml: {e}")))?; + if let Some(cross) = manifest + .get("workspace") + .and_then(|value| value.get("metadata")) + .and_then(|value| value.get("cross")) + { + reject_hooks(cross)?; + } + let path = root.join("Cross.toml"); + if path.exists() { + let source = fs::read_to_string(&path) + .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?; + let cross: toml::Value = toml::from_str(&source) + .map_err(|e| Error(format!("invalid {}: {e}", path.display())))?; + reject_hooks(&cross)?; + } + Ok(()) +} + +fn reject_hooks(value: &toml::Value) -> Result<(), Error> { + match value { + toml::Value::Table(table) => { + for (key, child) in table { + if matches!(key.as_str(), "pre-build" | "dockerfile" | "runner") { + return Err(Error(format!("Repository cross configuration contains unsupported executable option {key:?}."))); + } + reject_hooks(child)?; + } + } + toml::Value::Array(array) => { + for child in array { + reject_hooks(child)?; + } + } + _ => (), + } + Ok(()) +} + +pub fn verify_source( + root: &Path, + project: &SelectedPackage, + config: &Config, + skip_tests: bool, + runner: &Runner, +) -> Result<(), Error> { + let mut flags = vec!["--package", project.name.as_str()]; + if config.locked { + flags.push("--locked"); + } + runner.output("cargo", &[&["check"], flags.as_slice()].concat(), root)?; + if !skip_tests { + runner.output("cargo", &[&["test"], flags.as_slice()].concat(), root)?; + } + Ok(()) +} + +pub fn cross_arguments( + project: &SelectedPackage, + config: &Config, + target: &str, + target_dir: &Path, +) -> Vec { + let mut args = vec!["build".to_owned()]; + if config.profile == "release" { + args.push("--release".into()); + } else { + args.extend(["--profile".into(), config.profile.clone()]); + } + if config.locked { + args.push("--locked".into()); + } + args.extend([ + "--target".into(), + target.to_owned(), + "--target-dir".into(), + target_dir.display().to_string(), + "--package".into(), + project.name.clone(), + "--bin".into(), + project.binary.clone(), + ]); + args +} + +pub fn build( + root: &Path, + project: &SelectedPackage, + config: &Config, + engine: &str, + runner: &Runner, +) -> Result, Error> { + let target_base = project.target_directory.join("binstall-publisher"); + fs::create_dir_all(&target_base) + .map_err(|e| Error(format!("cannot create {}: {e}", target_base.display())))?; + let fresh = tempfile::Builder::new() + .prefix("build-") + .tempdir_in(&target_base) + .map_err(|e| Error(format!("cannot create fresh build directory: {e}")))?; + let target_dir = fresh.keep(); + println!("Fresh build directory: {}", target_dir.display()); + let toolchain = executable("rustup") + .and_then(|_| { + runner + .text("rustup", &["show", "active-toolchain"], root) + .ok() + }) + .and_then(|line| line.split_whitespace().next().map(str::to_owned)); + let mut environment = vec![("CROSS_CONTAINER_ENGINE", engine)]; + if let Some(toolchain) = toolchain.as_deref() { + environment.push(("RUSTUP_TOOLCHAIN", toolchain)); + } + let profile_dir = if config.profile == "dev" { + "debug" + } else { + &config.profile + }; + let mut outputs = Vec::new(); + for target in &config.targets { + println!("Building {target}"); + let args = cross_arguments(project, config, target, &target_dir); + let borrowed: Vec<&str> = args.iter().map(String::as_str).collect(); + runner.output_with("cross", &borrowed, root, &environment, &[])?; + let binary = target_dir + .join(target) + .join(profile_dir) + .join(policy::binary_filename(&project.binary, target)); + let metadata = fs::symlink_metadata(&binary).map_err(|_| { + Error(format!( + "Build did not produce a regular binary: {}", + binary.display() + )) + })?; + if !metadata.file_type().is_file() { + return Err(Error(format!( + "Build did not produce a regular binary: {}", + binary.display() + ))); + } + outputs.push((target.clone(), binary)); + } + Ok(outputs) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn cross_command_scopes_package_and_uses_fresh_target_path() { + let project = SelectedPackage { + name: "cli".into(), + version: "0.1.0".into(), + binary: "cli".into(), + manifest: PathBuf::from("Cargo.toml"), + repository: None, + target_directory: PathBuf::from("target"), + }; + let config = Config { + targets: vec!["x86_64-pc-windows-gnu".into()], + profile: "release".into(), + locked: true, + tag_prefix: "v".into(), + token_env: "GITEA_TOKEN".into(), + }; + let args = cross_arguments( + &project, + &config, + "x86_64-pc-windows-gnu", + Path::new("/tmp/fresh"), + ); + assert_eq!( + args, + [ + "build", + "--release", + "--locked", + "--target", + "x86_64-pc-windows-gnu", + "--target-dir", + "/tmp/fresh", + "--package", + "cli", + "--bin", + "cli" + ] + ); + } + #[test] + fn cross_hooks_are_rejected() { + let doc: toml::Value = + toml::from_str("[target.x86_64-unknown-linux-musl]\npre-build=['echo unsafe']") + .unwrap(); + assert!(reject_hooks(&doc).is_err()); + } +} diff --git a/src/cli.rs b/src/cli.rs index 8ad5969..25455b3 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,4 +1,5 @@ use crate::{ + build, config::{self, Overrides}, error::Error, manifest, @@ -87,7 +88,7 @@ pub fn run(args: Cli) -> Result<(), Error> { tag_prefix: args.tag_prefix, }, )?; - let runner = Runner::new(&config.token_env); + let runner = Runner::new(&config.token_env).with_verbose(args.verbose); let checkout = project::acquire_project( &args.source, args.tag.as_deref(), @@ -142,6 +143,12 @@ pub fn run(args: Cli) -> Result<(), Error> { }; println!("{}: {actual} -> {:?}", issue.key, issue.expected); } + if args.prepare_repo { + return Err(Error( + "Rust repository preparation is still being ported; use release.sh for preparation." + .into(), + )); + } if !issues.is_empty() && args.fix_metadata && !args.dry_run { manifest::repair(&selected.manifest, &issues, true)?; println!("Metadata repaired locally. Commit and push explicitly if desired."); @@ -164,10 +171,70 @@ pub fn run(args: Cli) -> Result<(), Error> { for (key, value) in policy::binstall_metadata(&config.tag_prefix) { println!("Binstall {key}: {value}"); } - let _ = (&config.profile, config.locked, &config.token_env); + println!("Release destination: {repository}/releases/tag/{tag}"); + let needs_cross = args.stop_after != Some(Stage::Verify); + let needs_binstall = !args.skip_binstall_test + && args + .stop_after + .is_none_or(|stage| stage.order() >= Stage::Binstall.order()); + let (problems, engine) = build::prerequisites( + &checkout.root, + &config, + needs_cross, + needs_binstall, + &runner, + ); + for problem in &problems { + println!("Prerequisite: {problem}"); + } + if args.dry_run { + println!("Dry run complete: no manifest edits, builds or release mutations."); + if !issues.is_empty() || !problems.is_empty() { + return Err(Error( + "Dry run found the metadata/prerequisite issues reported above.".into(), + )); + } + return Ok(()); + } + if !problems.is_empty() { + return Err(Error( + "Resolve the prerequisite issues above before building.".into(), + )); + } + build::verify_source(&checkout.root, &selected, &config, args.skip_tests, &runner)?; + if args.stop_after == Some(Stage::Verify) { + return Ok(()); + } + let engine = engine.ok_or_else(|| Error("No usable Cross container backend.".into()))?; + let outputs = build::build(&checkout.root, &selected, &config, &engine, &runner)?; + if args.stop_after == Some(Stage::Build) { + return Ok(()); + } + let (artifacts, sums) = crate::package::package( + &checkout.root, + &selected.name, + &selected.version, + &selected.binary, + &outputs, + )?; + println!( + "Artifacts: {}", + sums.parent().map_or_else( + || sums.display().to_string(), + |path| path.display().to_string() + ) + ); + for artifact in &artifacts { + println!( + "Packaged {}: {}/{}", + artifact.target, artifact.root, artifact.binary + ); + } + if args.stop_after == Some(Stage::Package) { + return Ok(()); + } Err(Error( - "Rust release stages after inspect are still being ported; use release.sh for publication." - .into(), + "Rust Gitea publication is still being ported; use release.sh for publication.".into(), )) } diff --git a/src/main.rs b/src/main.rs index a5f1772..aa45728 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,12 @@ //! Entry point for the incremental Rust replacement. +mod build; mod cli; mod config; mod error; mod manifest; mod model; +mod package; mod policy; mod project; mod runner; diff --git a/src/package.rs b/src/package.rs index 022d67d..f00239c 100644 --- a/src/package.rs +++ b/src/package.rs @@ -1 +1,275 @@ -//! Placeholder for the future package implementation. +use crate::{error::Error, policy}; +use flate2::{Compression, GzBuilder}; +use sha2::{Digest, Sha256}; +use std::{ + fs::{self, File}, + io::{self, Read, Write}, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Clone)] +pub struct Artifact { + pub target: String, + pub path: PathBuf, + pub root: String, + pub binary: String, + pub sha256: String, +} + +pub fn package( + root: &Path, + name: &str, + version: &str, + binary: &str, + outputs: &[(String, PathBuf)], +) -> Result<(Vec, PathBuf), Error> { + for (target, _) in outputs { + safe_component(&policy::archive_root(name, target, version))?; + safe_component(&policy::archive_name(name, target, version))?; + safe_component(&policy::binary_filename(binary, target))?; + } + let dist = root.join("dist"); + if dist.is_symlink() { + return Err(Error("Refusing a symlinked dist directory.".into())); + } + fs::create_dir_all(&dist) + .map_err(|e| Error(format!("cannot create {}: {e}", dist.display())))?; + let staging = tempfile::Builder::new() + .prefix("release-") + .tempdir_in(&dist) + .map_err(|e| Error(format!("cannot create release staging directory: {e}")))?; + let mut artifacts = Vec::new(); + for (target, source) in outputs { + let archive_root = policy::archive_root(name, target, version); + let filename = policy::archive_name(name, target, version); + let executable = policy::binary_filename(binary, target); + let path = staging.path().join(filename); + let metadata = fs::symlink_metadata(source) + .map_err(|e| Error(format!("cannot inspect binary {}: {e}", source.display())))?; + if !metadata.file_type().is_file() { + return Err(Error(format!( + "Build did not produce a regular binary: {}", + source.display() + ))); + } + let mode = if target.split('-').any(|part| part == "windows") { + 0o644 + } else { + unix_mode(&metadata) | 0o111 + }; + let output = File::create(&path) + .map_err(|e| Error(format!("cannot create archive {}: {e}", path.display())))?; + let mut gzip = GzBuilder::new() + .mtime(0) + .operating_system(255) + .write(output, Compression::default()); + write_header(&mut gzip, &archive_root, 0o755, 0, b'5')?; + write_header( + &mut gzip, + &format!("{archive_root}/{executable}"), + mode, + metadata.len(), + b'0', + )?; + let mut input = File::open(source) + .map_err(|e| Error(format!("cannot open binary {}: {e}", source.display())))?; + let copied = io::copy(&mut input, &mut gzip) + .map_err(|e| Error(format!("cannot archive {}: {e}", source.display())))?; + if copied != metadata.len() { + return Err(Error(format!( + "Binary changed while packaging: {}", + source.display() + ))); + } + let padding = (512 - metadata.len() % 512) % 512; + gzip.write_all(&vec![0; padding as usize]) + .map_err(|e| Error(format!("cannot pad archive: {e}")))?; + gzip.write_all(&[0; 1024]) + .map_err(|e| Error(format!("cannot finish tar archive: {e}")))?; + gzip.finish() + .map_err(|e| Error(format!("cannot finish gzip archive: {e}")))?; + let sha256 = checksum(&path)?; + artifacts.push(Artifact { + target: target.clone(), + path, + root: archive_root, + binary: executable, + sha256, + }); + } + let sums = staging.path().join("SHA256SUMS"); + artifacts.sort_by(|a, b| a.path.file_name().cmp(&b.path.file_name())); + let mut checksums = String::new(); + for artifact in &artifacts { + let filename = artifact + .path + .file_name() + .and_then(|s| s.to_str()) + .ok_or_else(|| Error("Invalid archive filename.".into()))?; + checksums.push_str(&format!("{} {filename}\n", artifact.sha256)); + } + fs::write(&sums, checksums) + .map_err(|e| Error(format!("cannot write {}: {e}", sums.display())))?; + let _ = staging.keep(); + Ok((artifacts, sums)) +} + +fn safe_component(component: &str) -> Result<(), Error> { + if component.is_empty() + || component == "." + || component == ".." + || component.contains('/') + || component.contains('\\') + || component.bytes().any(|b| b == 0 || b < 32) + { + return Err(Error(format!("Unsafe archive filename: {component:?}"))); + } + Ok(()) +} + +fn unix_mode(metadata: &fs::Metadata) -> u32 { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + metadata.permissions().mode() & 0o777 + } + #[cfg(not(unix))] + { + let _ = metadata; + 0o755 + } +} + +fn checksum(path: &Path) -> Result { + let mut input = + File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?; + let mut hasher = Sha256::new(); + let mut buffer = [0_u8; 64 * 1024]; + loop { + let count = input + .read(&mut buffer) + .map_err(|e| Error(format!("cannot hash {}: {e}", path.display())))?; + if count == 0 { + break; + } + hasher.update(&buffer[..count]); + } + Ok(format!("{:x}", hasher.finalize())) +} + +fn write_header( + output: &mut W, + path: &str, + mode: u32, + size: u64, + kind: u8, +) -> Result<(), Error> { + let mut header = [0_u8; 512]; + let (name, prefix) = if path.len() <= 100 { + (path, "") + } else { + let (prefix, name) = path + .rsplit_once('/') + .ok_or_else(|| Error("Archive path exceeds USTAR name limit.".into()))?; + if name.len() > 100 || prefix.len() > 155 { + return Err(Error("Archive path exceeds USTAR limits.".into())); + } + (name, prefix) + }; + header[..name.len()].copy_from_slice(name.as_bytes()); + header[345..345 + prefix.len()].copy_from_slice(prefix.as_bytes()); + octal(&mut header[100..108], u64::from(mode))?; + octal(&mut header[108..116], 0)?; + octal(&mut header[116..124], 0)?; + octal(&mut header[124..136], size)?; + octal(&mut header[136..148], 0)?; + header[148..156].fill(b' '); + header[156] = kind; + header[257..263].copy_from_slice(b"ustar\0"); + header[263..265].copy_from_slice(b"00"); + let sum: u64 = header.iter().map(|byte| u64::from(*byte)).sum(); + let check = format!("{sum:06o}\0 "); + if check.len() != 8 { + return Err(Error("Tar header checksum overflow.".into())); + } + header[148..156].copy_from_slice(check.as_bytes()); + output + .write_all(&header) + .map_err(|e| Error(format!("cannot write tar header: {e}"))) +} + +fn octal(field: &mut [u8], number: u64) -> Result<(), Error> { + let rendered = format!("{:0width$o}\0", number, width = field.len() - 1); + if rendered.len() != field.len() { + return Err(Error("Tar field exceeds USTAR limit.".into())); + } + field.copy_from_slice(rendered.as_bytes()); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use flate2::read::GzDecoder; + #[test] + fn archive_contract_and_reproducibility() { + let temp = tempfile::tempdir().unwrap(); + let binary = temp.path().join("demo"); + fs::write(&binary, b"small executable").unwrap(); + let outputs = [ + ("x86_64-unknown-linux-musl".to_owned(), binary.clone()), + ("x86_64-pc-windows-gnu".to_owned(), binary), + ]; + let (first, sums) = package(temp.path(), "demo", "0.1.0", "demo", &outputs).unwrap(); + assert_eq!(first.len(), 2); + assert_eq!(fs::read_to_string(sums).unwrap().lines().count(), 2); + let (second, _) = package(temp.path(), "demo", "0.1.0", "demo", &outputs).unwrap(); + for (one, two) in first.iter().zip(second.iter()) { + assert_eq!(fs::read(&one.path).unwrap(), fs::read(&two.path).unwrap()); + assert_eq!(one.sha256, checksum(&one.path).unwrap()); + let mut tar = Vec::new(); + GzDecoder::new(File::open(&one.path).unwrap()) + .read_to_end(&mut tar) + .unwrap(); + assert_eq!(&tar[..one.root.len()], one.root.as_bytes()); + assert_eq!(tar[156], b'5'); + let file_header = &tar[512..1024]; + let expected = format!("{}/{}", one.root, one.binary); + assert_eq!(&file_header[..expected.len()], expected.as_bytes()); + assert_eq!(file_header[156], b'0'); + assert_eq!(&tar[1024..1024 + 16], b"small executable"); + let mode = std::str::from_utf8(&file_header[100..107]).unwrap(); + if one.target.contains("windows") { + assert_eq!(mode, "0000644"); + } else { + assert_eq!(mode, "0000755"); + } + } + } + #[test] + fn rejects_symlink_dist_and_source() { + let temp = tempfile::tempdir().unwrap(); + let binary = temp.path().join("demo"); + fs::write(&binary, "binary").unwrap(); + assert!(package( + temp.path(), + "../escape", + "0.1.0", + "demo", + &[("x86_64-unknown-linux-musl".into(), binary.clone())] + ) + .is_err()); + #[cfg(unix)] + { + std::os::unix::fs::symlink(temp.path(), temp.path().join("dist")).unwrap(); + assert!(package( + temp.path(), + "demo", + "0.1.0", + "demo", + &[("x86_64-unknown-linux-musl".into(), binary)] + ) + .is_err()); + } + } +} diff --git a/src/project.rs b/src/project.rs index 55939af..f2fd8e2 100644 --- a/src/project.rs +++ b/src/project.rs @@ -12,6 +12,7 @@ pub struct SelectedPackage { pub binary: String, pub manifest: PathBuf, pub repository: Option, + pub target_directory: PathBuf, } pub struct SourceCheckout { @@ -92,6 +93,7 @@ struct Metadata { packages: Vec, workspace_members: Vec, workspace_root: PathBuf, + target_directory: PathBuf, } #[derive(Deserialize)] struct Package { @@ -220,6 +222,7 @@ pub fn inspect( binary: binaries[0].name.clone(), manifest: member_manifest, repository: selected.repository, + target_directory: metadata.target_directory, }) } fn safe_component(value: &str) -> bool { diff --git a/src/runner.rs b/src/runner.rs index f239bfc..1c68041 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -4,30 +4,63 @@ use std::{path::Path, process::Command, sync::OnceLock}; pub struct Runner { token_env: String, + verbose: bool, } impl Runner { pub fn new(token_env: &str) -> Self { Self { token_env: token_env.to_owned(), + verbose: false, } } + pub fn with_verbose(mut self, verbose: bool) -> Self { + self.verbose = verbose; + self + } + pub fn output(&self, program: &str, args: &[&str], cwd: &Path) -> Result, Error> { - let output = Command::new(program) + self.output_with(program, args, cwd, &[], &[]) + } + + pub fn output_with( + &self, + program: &str, + args: &[&str], + cwd: &Path, + additions: &[(&str, &str)], + removals: &[&str], + ) -> Result, Error> { + let command = std::iter::once(program) + .chain(args.iter().copied()) + .map(|arg| if arg.contains("://") { "[URL]" } else { arg }) + .collect::>() + .join(" "); + if self.verbose { + eprintln!("$ {}", self.redact(&command)); + } + let mut process = Command::new(program); + process .args(args) .current_dir(cwd) .env_remove("GITEA_TOKEN") - .env_remove(&self.token_env) + .env_remove(&self.token_env); + for name in removals { + process.env_remove(name); + } + for (name, value) in additions { + process.env(name, value); + } + let output = process .output() .map_err(|e| Error(format!("cannot run {program}: {e}")))?; if !output.status.success() { - let command = std::iter::once(program) - .chain(args.iter().copied()) - .map(|arg| if arg.contains("://") { "[URL]" } else { arg }) - .collect::>() - .join(" "); - let detail = self.redact(&String::from_utf8_lossy(&output.stderr)); + let detail = self.redact(&format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + )); return Err(Error(format!( "command {} failed with {}: {}", self.redact(&command), @@ -35,6 +68,12 @@ impl Runner { detail.trim() ))); } + if self.verbose { + let output_text = self.redact(&String::from_utf8_lossy(&output.stdout)); + if !output_text.trim().is_empty() { + eprintln!("{}", output_text.trim()); + } + } Ok(output.stdout) } @@ -46,14 +85,14 @@ impl Runner { } pub fn redact(&self, text: &str) -> String { - let token = std::env::var(&self.token_env) - .ok() - .filter(|value| !value.is_empty()); - let without_token = if let Some(secret) = token { - text.replace(&secret, "[REDACTED]") - } else { - text.to_owned() - }; + let mut without_token = text.to_owned(); + for name in ["GITEA_TOKEN", self.token_env.as_str()] { + if let Ok(secret) = std::env::var(name) { + if !secret.is_empty() { + without_token = without_token.replace(&secret, "[REDACTED]"); + } + } + } static URLS: OnceLock = OnceLock::new(); let pattern = URLS.get_or_init(|| { Regex::new(r#"(?i)(?:https?|ssh)://[^\s'"<>]+"#) @@ -77,11 +116,25 @@ mod tests { assert!(!message.contains("password")); let child = runner.text("env", &[], Path::new(".")).unwrap(); assert!(!child.contains("RUST_RELEASE_TEST_SECRET")); + std::env::set_var("RUST_RELEASE_TEST_REMOVED", "remove-me"); + let child = runner + .output_with( + "env", + &[], + Path::new("."), + &[("RUST_RELEASE_TEST_ADDED", "added-value")], + &["RUST_RELEASE_TEST_REMOVED"], + ) + .unwrap(); + let child = String::from_utf8(child).unwrap(); + assert!(child.contains("RUST_RELEASE_TEST_ADDED=added-value")); + assert!(!child.contains("RUST_RELEASE_TEST_REMOVED")); let error = runner .output("git", &["rev-parse", secret], Path::new(".")) .unwrap_err() .to_string(); assert!(!error.contains(secret)); std::env::remove_var("RUST_RELEASE_TEST_SECRET"); + std::env::remove_var("RUST_RELEASE_TEST_REMOVED"); } }