diff --git a/AGENT_TASKS.md b/AGENT_TASKS.md index 5967983..34dde2e 100644 --- a/AGENT_TASKS.md +++ b/AGENT_TASKS.md @@ -14,7 +14,7 @@ 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: local `inspect` and `metadata` stages work for standalone packages and exact workspace package selection. The metadata stage validates and can repair the selected manifest with `--fix-metadata`; dry-run previews changes without writing. Remote acquisition, preparation, builds, and release actions still use the Python worker. +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. Work in small, testable phases. Commit migration work in coherent increments. diff --git a/Cargo.lock b/Cargo.lock index 4948b65..5decbd3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "anstream" version = "1.0.0" @@ -375,11 +384,41 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "rust_realease" version = "0.1.0" dependencies = [ "clap", + "regex", "serde", "serde_json", "tempfile", diff --git a/Cargo.toml b/Cargo.toml index 1b3cdd0..972a76c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,5 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" toml_edit = "0.25" url = "2.5" - -[dev-dependencies] tempfile = "3" +regex = "1" diff --git a/README.md b/README.md index 577bf1d..651efcd 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Rust Binstall Publisher -> Rust migration status: the Rust binary currently supports local project inspection and metadata validation/repair through `--stop-after metadata`, including exact workspace `--package` selection. 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 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. 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. diff --git a/src/cli.rs b/src/cli.rs index 264710e..8ad5969 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -4,6 +4,7 @@ use crate::{ manifest, model::Stage, policy, project, + runner::Runner, }; use clap::Parser; use std::path::PathBuf; @@ -59,8 +60,8 @@ pub struct Cli { pub cross_image_tag: Option, #[arg(long)] pub repository_url: Option, - #[arg(long, default_value = "config.toml")] - pub config: PathBuf, + #[arg(long)] + pub config: Option, } pub fn run(args: Cli) -> Result<(), Error> { @@ -78,7 +79,7 @@ pub fn run(args: Cli) -> Result<(), Error> { )); } let config = config::load( - &args.config, + args.config.as_deref(), Overrides { targets: args.target, profile: args.profile, @@ -86,7 +87,18 @@ pub fn run(args: Cli) -> Result<(), Error> { tag_prefix: args.tag_prefix, }, )?; - let selected = project::inspect(&args.source, args.package.as_deref())?; + let runner = Runner::new(&config.token_env); + let checkout = project::acquire_project( + &args.source, + args.tag.as_deref(), + args.keep_workdir || args.prepare_repo, + &runner, + )?; + let root = checkout + .root + .to_str() + .ok_or_else(|| Error("Project path is not UTF-8.".into()))?; + let selected = project::inspect(root, args.package.as_deref(), &runner)?; let tag = policy::expected_tag(&selected.version, &config.tag_prefix); if args.tag.as_ref().is_some_and(|provided| provided != &tag) { return Err(Error(format!( @@ -94,9 +106,6 @@ pub fn run(args: Cli) -> Result<(), Error> { args.tag ))); } - if args.tag.is_some() { - project::validate_checkout_tag(std::path::Path::new(&args.source), &tag)?; - } println!("Package: {}", selected.name); println!("Version: {}", selected.version); println!("Binary: {}", selected.binary); @@ -113,7 +122,7 @@ pub fn run(args: Cli) -> Result<(), Error> { .as_deref() .or(selected.repository.as_deref()) .map(str::to_owned) - .or_else(|| project::origin_url(std::path::Path::new(&args.source))) + .or_else(|| project::origin_url(&checkout.root, &runner)) .ok_or_else(|| { Error( "package.repository is missing; provide --repository-url and --fix-metadata." diff --git a/src/config.rs b/src/config.rs index 6309011..f90c295 100644 --- a/src/config.rs +++ b/src/config.rs @@ -45,10 +45,14 @@ pub struct Overrides { pub unlocked: bool, pub tag_prefix: Option, } -pub fn load(path: &Path, overrides: Overrides) -> Result { - let source = fs::read_to_string(path) - .map_err(|e| Error(format!("cannot read config {}: {e}", path.display())))?; - parse(&source, overrides) +pub fn load(path: Option<&Path>, overrides: Overrides) -> Result { + if let Some(path) = path { + let source = fs::read_to_string(path) + .map_err(|e| Error(format!("cannot read config {}: {e}", path.display())))?; + parse(&source, overrides) + } else { + parse(include_str!("../config.toml"), overrides) + } } fn parse(source: &str, overrides: Overrides) -> Result { let file: FileConfig = @@ -149,5 +153,6 @@ mod tests { assert_eq!(config.tag_prefix, ""); assert!(parse("[build]\ntargets=['bad']", Overrides::default()).is_err()); assert!(parse("[package]\nformat='zip'", Overrides::default()).is_err()); + assert_eq!(load(None, Overrides::default()).unwrap().targets.len(), 3); } } diff --git a/src/main.rs b/src/main.rs index d84a191..a5f1772 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod manifest; mod model; mod policy; mod project; +mod runner; use clap::Parser; diff --git a/src/project.rs b/src/project.rs index 17f343b..55939af 100644 --- a/src/project.rs +++ b/src/project.rs @@ -1,9 +1,8 @@ -use crate::error::Error; +use crate::{error::Error, runner::Runner}; use serde::Deserialize; use std::{ fs, path::{Path, PathBuf}, - process::Command, }; #[derive(Debug)] @@ -14,6 +13,80 @@ pub struct SelectedPackage { pub manifest: PathBuf, pub repository: Option, } + +pub struct SourceCheckout { + pub root: PathBuf, + _temporary: Option, +} + +pub fn acquire_project( + source: &str, + tag: Option<&str>, + keep_workdir: bool, + runner: &Runner, +) -> Result { + let expanded = if let Some(suffix) = source.strip_prefix("~/") { + std::env::var_os("HOME") + .map(|home| PathBuf::from(home).join(suffix)) + .unwrap_or_else(|| PathBuf::from(source)) + } else { + PathBuf::from(source) + }; + if expanded.exists() { + if !expanded.is_dir() { + return Err(Error("Local source must be a directory.".into())); + } + let root = expanded + .canonicalize() + .map_err(|e| Error(format!("cannot resolve local source: {e}")))?; + if let Some(tag) = tag { + validate_checkout_tag(&root, tag, runner)?; + } + return Ok(SourceCheckout { + root, + _temporary: None, + }); + } + normalize_repository(source)?; + let temporary = tempfile::Builder::new() + .prefix("rust-realease-") + .tempdir() + .map_err(|e| Error(format!("cannot create temporary checkout: {e}")))?; + let root = temporary.path().join("source"); + clone_to(source, &root, tag, runner)?; + if keep_workdir { + let retained = temporary.keep(); + println!("Temporary workdir kept at {}", retained.display()); + Ok(SourceCheckout { + root, + _temporary: None, + }) + } else { + Ok(SourceCheckout { + root, + _temporary: Some(temporary), + }) + } +} + +fn clone_to(source: &str, root: &Path, tag: Option<&str>, runner: &Runner) -> Result<(), Error> { + let parent = root + .parent() + .ok_or_else(|| Error("Invalid clone destination.".into()))?; + let destination = root + .to_str() + .ok_or_else(|| Error("Clone destination is not UTF-8.".into()))?; + runner.output("git", &["clone", "--", source, destination], parent)?; + if let Some(tag) = tag { + runner.output( + "git", + &["checkout", "--detach", &format!("refs/tags/{tag}")], + root, + )?; + validate_checkout_tag(root, tag, runner)?; + } + Ok(()) +} #[derive(Deserialize)] struct Metadata { packages: Vec, @@ -35,7 +108,11 @@ struct Target { kind: Vec, } -pub fn inspect(source: &str, package_name: Option<&str>) -> Result { +pub fn inspect( + source: &str, + package_name: Option<&str>, + runner: &Runner, +) -> Result { let root = Path::new(source); if !root.is_dir() { return Err(Error( @@ -47,18 +124,12 @@ pub fn inspect(source: &str, package_name: Option<&str>) -> Result = metadata .packages @@ -161,39 +232,30 @@ fn safe_component(value: &str) -> bool { .all(|b| b.is_ascii_alphanumeric() || b"_.+-".contains(&b)) } -pub fn origin_url(root: &Path) -> Option { - let output = Command::new("git") - .args(["remote", "get-url", "origin"]) - .current_dir(root) - .output() - .ok()?; - output - .status - .success() - .then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned()) +pub fn origin_url(root: &Path, runner: &Runner) -> Option { + runner + .text("git", &["remote", "get-url", "origin"], root) + .ok() } -pub fn validate_checkout_tag(root: &Path, tag: &str) -> Result<(), Error> { - let tagged = Command::new("git") - .args([ - "rev-parse", - "--verify", - &format!("refs/tags/{tag}^{{commit}}"), - ]) - .current_dir(root) - .output() - .map_err(|e| Error(format!("cannot validate Git tag: {e}")))?; - if !tagged.status.success() { - return Err(Error(format!( - "Git tag {tag:?} does not exist. Create it explicitly first." - ))); - } - let head = Command::new("git") - .args(["rev-parse", "HEAD"]) - .current_dir(root) - .output() - .map_err(|e| Error(format!("cannot inspect Git HEAD: {e}")))?; - if !head.status.success() || head.stdout != tagged.stdout { +pub fn validate_checkout_tag(root: &Path, tag: &str, runner: &Runner) -> Result<(), Error> { + let tagged = runner + .text( + "git", + &[ + "rev-parse", + "--verify", + &format!("refs/tags/{tag}^{{commit}}"), + ], + root, + ) + .map_err(|_| { + Error(format!( + "Git tag {tag:?} does not exist. Create it explicitly first." + )) + })?; + let head = runner.text("git", &["rev-parse", "HEAD"], root)?; + if head != tagged { return Err(Error(format!( "Git tag {tag:?} does not point to this checkout. Check it out explicitly." ))); @@ -294,7 +356,12 @@ mod tests { "[package]\nname='solo'\nversion='0.1.0'\nedition='2021'\n", ); write(temp.path(), "src/main.rs", "fn main() {}\n"); - let selected = inspect(temp.path().to_str().unwrap(), None).unwrap(); + let selected = inspect( + temp.path().to_str().unwrap(), + None, + &Runner::new("GITEA_TOKEN"), + ) + .unwrap(); assert_eq!(selected.name, "solo"); assert_eq!(selected.binary, "solo"); @@ -317,15 +384,20 @@ mod tests { ); } let root = workspace.path().to_str().unwrap(); - assert!(inspect(root, None) + assert!(inspect(root, None, &Runner::new("GITEA_TOKEN")) .unwrap_err() .to_string() .contains("--package")); - assert!(inspect(root, Some("missing")) + assert!(inspect(root, Some("missing"), &Runner::new("GITEA_TOKEN")) .unwrap_err() .to_string() .contains("not found")); - assert_eq!(inspect(root, Some("two")).unwrap().binary, "two"); + assert_eq!( + inspect(root, Some("two"), &Runner::new("GITEA_TOKEN")) + .unwrap() + .binary, + "two" + ); } #[test] @@ -338,13 +410,13 @@ mod tests { ); write(temp.path(), "src/lib.rs", "pub fn hello() {}\n"); let root = temp.path().to_str().unwrap(); - assert!(inspect(root, None) + assert!(inspect(root, None, &Runner::new("GITEA_TOKEN")) .unwrap_err() .to_string() .contains("exactly one binary")); write(temp.path(), "src/main.rs", "fn main() {}\n"); write(temp.path(), "src/bin/extra.rs", "fn main() {}\n"); - assert!(inspect(root, None) + assert!(inspect(root, None, &Runner::new("GITEA_TOKEN")) .unwrap_err() .to_string() .contains("exactly one binary")); @@ -372,4 +444,51 @@ mod tests { assert!(normalize_repository(value).is_err(), "{value}"); } } + + #[test] + fn local_source_is_retained_and_clone_checks_out_exact_tag() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("origin"); + fs::create_dir(&source).unwrap(); + let runner = Runner::new("GITEA_TOKEN"); + runner.output("git", &["init", "-q"], &source).unwrap(); + fs::write(source.join("version.txt"), "one").unwrap(); + runner + .output("git", &["add", "version.txt"], &source) + .unwrap(); + let commit_args = [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "-qm", + "first", + ]; + runner.output("git", &commit_args, &source).unwrap(); + runner.output("git", &["tag", "v0.1.0"], &source).unwrap(); + fs::write(source.join("version.txt"), "two").unwrap(); + runner + .output("git", &["add", "version.txt"], &source) + .unwrap(); + runner.output("git", &commit_args, &source).unwrap(); + + let local = acquire_project(source.to_str().unwrap(), None, false, &runner).unwrap(); + assert_eq!(local.root, source.canonicalize().unwrap()); + drop(local); + assert!(source.exists()); + assert!(validate_checkout_tag(&source, "v0.1.0", &runner).is_err()); + + let clone = temp.path().join("checkout"); + clone_to(source.to_str().unwrap(), &clone, Some("v0.1.0"), &runner).unwrap(); + assert_eq!( + fs::read_to_string(clone.join("version.txt")).unwrap(), + "one" + ); + validate_checkout_tag(&clone, "v0.1.0", &runner).unwrap(); + let missing = temp.path().join("missing-tag"); + assert!(clone_to(source.to_str().unwrap(), &missing, Some("v9.9.9"), &runner).is_err()); + } } diff --git a/src/runner.rs b/src/runner.rs index 66a05c7..f239bfc 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -1 +1,87 @@ -//! Placeholder for the future runner implementation. +use crate::error::Error; +use regex::Regex; +use std::{path::Path, process::Command, sync::OnceLock}; + +pub struct Runner { + token_env: String, +} + +impl Runner { + pub fn new(token_env: &str) -> Self { + Self { + token_env: token_env.to_owned(), + } + } + + pub fn output(&self, program: &str, args: &[&str], cwd: &Path) -> Result, Error> { + let output = Command::new(program) + .args(args) + .current_dir(cwd) + .env_remove("GITEA_TOKEN") + .env_remove(&self.token_env) + .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)); + return Err(Error(format!( + "command {} failed with {}: {}", + self.redact(&command), + output.status, + detail.trim() + ))); + } + Ok(output.stdout) + } + + pub fn text(&self, program: &str, args: &[&str], cwd: &Path) -> Result { + let bytes = self.output(program, args, cwd)?; + String::from_utf8(bytes) + .map(|text| text.trim().to_owned()) + .map_err(|e| Error(format!("{program} returned non-UTF-8 output: {e}"))) + } + + 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() + }; + static URLS: OnceLock = OnceLock::new(); + let pattern = URLS.get_or_init(|| { + Regex::new(r#"(?i)(?:https?|ssh)://[^\s'"<>]+"#) + .unwrap_or_else(|_| unreachable!("static URL regex must compile")) + }); + pattern.replace_all(&without_token, "[URL]").into_owned() + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn redacts_token_and_urls_and_keeps_token_out_of_child() { + let runner = Runner::new("RUST_RELEASE_TEST_SECRET"); + let secret = "unit-test-secret-value"; + std::env::set_var("RUST_RELEASE_TEST_SECRET", secret); + let message = runner + .redact("failed https://user:password@example.com/repo and unit-test-secret-value"); + assert!(!message.contains(secret)); + assert!(!message.contains("password")); + let child = runner.text("env", &[], Path::new(".")).unwrap(); + assert!(!child.contains("RUST_RELEASE_TEST_SECRET")); + 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"); + } +}