From e30365e5aeeda6d619e4ac9faa425dbdd3673da6 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 17 Sep 2026 01:18:49 +0200 Subject: [PATCH] Add Rust metadata validation and selected-manifest repair --- AGENT_TASKS.md | 2 +- Cargo.lock | 311 +++++++++++++++++++++++++++++++++++++++++++++++- Cargo.toml | 2 + README.md | 4 +- src/cli.rs | 132 +++++++++++++++++++- src/main.rs | 1 + src/manifest.rs | 174 ++++++++++++++++++++++++++- src/project.rs | 137 +++++++++++++++++++++ 8 files changed, 751 insertions(+), 12 deletions(-) diff --git a/AGENT_TASKS.md b/AGENT_TASKS.md index 1078d1a..5967983 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: `--stop-after inspect` works for local standalone packages and exact workspace package selection. Later stages, remote acquisition, and release actions still use the Python worker. +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. Work in small, testable phases. Commit migration work in coherent increments. diff --git a/Cargo.lock b/Cargo.lock index f594b6e..4948b65 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -95,7 +95,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.5", ] [[package]] @@ -110,6 +110,17 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -132,6 +143,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -155,6 +175,109 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -189,6 +312,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "memchr" version = "2.8.3" @@ -207,6 +336,21 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -240,6 +384,8 @@ dependencies = [ "serde_json", "tempfile", "toml", + "toml_edit", + "url", ] [[package]] @@ -282,7 +428,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.5", ] [[package]] @@ -307,12 +453,35 @@ dependencies = [ "serde_core", ] +[[package]] +name = "smallvec" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.5" @@ -324,6 +493,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -337,6 +517,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "toml" version = "1.1.6+spec-1.1.0" @@ -361,6 +551,19 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + [[package]] name = "toml_parser" version = "1.1.3+spec-1.1.0" @@ -382,6 +585,24 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" @@ -408,6 +629,92 @@ name = "winnow" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] [[package]] name = "zmij" diff --git a/Cargo.toml b/Cargo.toml index fb2c04a..1b3cdd0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,8 @@ clap = { version = "4.5", features = ["derive"] } toml = "1.1" serde = { version = "1", features = ["derive"] } serde_json = "1" +toml_edit = "0.25" +url = "2.5" [dev-dependencies] tempfile = "3" diff --git a/README.md b/README.md index 2fc1d8e..577bf1d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Rust Binstall Publisher -> Rust migration status: the Rust binary currently supports local project inspection with `--stop-after inspect`, 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 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. -Build and inspect locally with `cargo run -- target_test_project --stop-after inspect`. 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. +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. 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/cli.rs b/src/cli.rs index 687006c..264710e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,6 +1,7 @@ use crate::{ config::{self, Overrides}, error::Error, + manifest, model::Stage, policy, project, }; @@ -93,6 +94,9 @@ 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); @@ -104,6 +108,43 @@ pub fn run(args: Cli) -> Result<(), Error> { { return Ok(()); } + let candidate = args + .repository_url + .as_deref() + .or(selected.repository.as_deref()) + .map(str::to_owned) + .or_else(|| project::origin_url(std::path::Path::new(&args.source))) + .ok_or_else(|| { + Error( + "package.repository is missing; provide --repository-url and --fix-metadata." + .into(), + ) + })?; + let repository = project::normalize_repository(&candidate)?; + let issues = manifest::changes(&selected.manifest, &repository, &config.tag_prefix)?; + if issues.is_empty() { + println!("Binstall metadata: valid"); + } + for issue in &issues { + let actual = if issue.actual.is_some() { + "present" + } else { + "missing" + }; + println!("{}: {actual} -> {:?}", issue.key, issue.expected); + } + 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."); + } + if !issues.is_empty() && !args.fix_metadata && !args.dry_run { + return Err(Error( + "Metadata requires repair. Rerun with --fix-metadata.".into(), + )); + } + if args.stop_after == Some(Stage::Metadata) { + return Ok(()); + } for target in &config.targets { println!( "{target}: {} ({})", @@ -114,14 +155,93 @@ 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, - &selected.repository, - ); + let _ = (&config.profile, config.locked, &config.token_env); Err(Error( "Rust release stages after inspect are still being ported; use release.sh for publication." .into(), )) } + +#[cfg(test)] +mod tests { + use super::*; + use std::{fs, path::Path}; + + fn write(root: &Path, relative: &str, content: &str) { + let path = root.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + + #[test] + fn dry_run_never_edits_and_repair_only_touches_selected_member() { + let temp = tempfile::tempdir().unwrap(); + write( + temp.path(), + "config.toml", + "[build]\ntargets=['x86_64-unknown-linux-musl']\n", + ); + write( + temp.path(), + "Cargo.toml", + "[workspace]\nmembers=['one','two']\nresolver='2'\n", + ); + for name in ["one", "two"] { + write(temp.path(), &format!("{name}/Cargo.toml"), &format!("# {name}\n[package]\nname='{name}'\nversion='0.1.0'\nedition='2021'\nrepository='https://example.com/owner/{name}'\n")); + write( + temp.path(), + &format!("{name}/src/main.rs"), + "fn main() {}\n", + ); + } + let root = temp.path().to_str().unwrap(); + let config = temp + .path() + .join("config.toml") + .to_string_lossy() + .into_owned(); + let one = temp.path().join("one/Cargo.toml"); + let two = temp.path().join("two/Cargo.toml"); + let original_one = fs::read_to_string(&one).unwrap(); + let original_two = fs::read_to_string(&two).unwrap(); + let args = Cli::parse_from([ + "rust_realease", + root, + "--config", + &config, + "--package", + "one", + "--fix-metadata", + "--dry-run", + "--stop-after", + "metadata", + ]); + run(args).unwrap(); + assert_eq!(fs::read_to_string(&one).unwrap(), original_one); + let args = Cli::parse_from([ + "rust_realease", + root, + "--config", + &config, + "--package", + "one", + "--fix-metadata", + "--stop-after", + "metadata", + ]); + run(args).unwrap(); + assert_ne!(fs::read_to_string(&one).unwrap(), original_one); + assert_eq!(fs::read_to_string(&two).unwrap(), original_two); + let args = Cli::parse_from([ + "rust_realease", + root, + "--config", + &config, + "--package", + "one", + "--stop-after", + "metadata", + ]); + run(args).unwrap(); + } +} diff --git a/src/main.rs b/src/main.rs index e7dd97c..d84a191 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ mod cli; mod config; mod error; +mod manifest; mod model; mod policy; mod project; diff --git a/src/manifest.rs b/src/manifest.rs index d7c6002..4e4bcf6 100644 --- a/src/manifest.rs +++ b/src/manifest.rs @@ -1 +1,173 @@ -//! Placeholder for the future manifest implementation. +use crate::{error::Error, policy}; +use std::{fs, path::Path}; +use toml_edit::{DocumentMut, Item, Table, Value}; + +#[derive(Debug, PartialEq, Eq)] +pub struct Change { + pub key: String, + pub actual: Option, + pub expected: Option, +} + +fn document(path: &Path) -> Result { + let source = fs::read_to_string(path) + .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?; + source + .parse::() + .map_err(|e| Error(format!("invalid {}: {e}", path.display()))) +} + +fn package(doc: &DocumentMut) -> Result<&Table, Error> { + doc.get("package") + .and_then(Item::as_table) + .ok_or_else(|| Error("Cargo.toml contains no [package] table.".into())) +} + +fn binstall(package: &Table) -> Result, Error> { + let Some(metadata) = package.get("metadata") else { + return Ok(None); + }; + let metadata = metadata + .as_table() + .ok_or_else(|| Error("package.metadata must be a table.".into()))?; + let Some(binstall) = metadata.get("binstall") else { + return Ok(None); + }; + binstall + .as_table() + .map(Some) + .ok_or_else(|| Error("package.metadata.binstall must be a table.".into())) +} + +pub fn changes(path: &Path, repository: &str, prefix: &str) -> Result, Error> { + let doc = document(path)?; + let package = package(&doc)?; + let mut result = Vec::new(); + let actual = package + .get("repository") + .and_then(Item::as_str) + .map(str::to_owned); + if actual.as_deref() != Some(repository) { + result.push(Change { + key: "package.repository".into(), + actual, + expected: Some(repository.into()), + }); + } + let metadata = binstall(package)?; + let expected = policy::binstall_metadata(prefix); + for (key, desired) in &expected { + let actual = metadata + .and_then(|table| table.get(key)) + .and_then(Item::as_str) + .map(str::to_owned); + if actual.as_deref() != Some(desired) { + result.push(Change { + key: format!("package.metadata.binstall.{key}"), + actual, + expected: Some(desired.clone()), + }); + } + } + if let Some(table) = metadata { + for (key, item) in table.iter() { + if !expected.iter().any(|(known, _)| key == *known) { + result.push(Change { + key: format!("package.metadata.binstall.{key}"), + actual: Some(item.to_string().trim().to_owned()), + expected: None, + }); + } + } + } + Ok(result) +} + +pub fn repair(path: &Path, changes: &[Change], write: bool) -> Result { + if path.is_symlink() { + return Err(Error("Refusing to repair a symlinked Cargo.toml.".into())); + } + let mut doc = document(path)?; + let package = doc["package"] + .as_table_mut() + .ok_or_else(|| Error("Cargo.toml contains no [package] table.".into()))?; + for change in changes { + if change.key == "package.repository" { + if let Some(desired) = &change.expected { + set_string(&mut package["repository"], desired); + } + continue; + } + let key = change + .key + .strip_prefix("package.metadata.binstall.") + .ok_or_else(|| Error("Invalid metadata change key.".into()))?; + if !package.contains_key("metadata") { + package["metadata"] = Item::Table(Table::new()); + } + let metadata = package["metadata"] + .as_table_mut() + .ok_or_else(|| Error("package.metadata must be a table.".into()))?; + if !metadata.contains_key("binstall") { + metadata["binstall"] = Item::Table(Table::new()); + } + let binstall = metadata["binstall"] + .as_table_mut() + .ok_or_else(|| Error("package.metadata.binstall must be a table.".into()))?; + if let Some(desired) = &change.expected { + set_string(&mut binstall[key], desired); + } else { + binstall.remove(key); + } + } + let rendered = doc.to_string(); + if write { + fs::write(path, &rendered) + .map_err(|e| Error(format!("cannot write {}: {e}", path.display())))?; + } + Ok(rendered) +} + +fn set_string(item: &mut Item, desired: &str) { + let mut replacement = Value::from(desired); + if let Some(previous) = item.as_value() { + *replacement.decor_mut() = previous.decor().clone(); + } + *item = Item::Value(replacement); +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn repair_preserves_comments_and_is_idempotent() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("Cargo.toml"); + fs::write(&path, "# keep this comment\n[package]\nname = 'demo'\nversion = '0.1.0'\nrepository = 'https://old.example/x/y' # keep inline\n[package.metadata.binstall]\npkg-fmt = 'zip'\ncustom = 'bad'\n").unwrap(); + let issues = changes(&path, "https://example.com/x/y", "release-").unwrap(); + assert_eq!(issues.len(), 5); + let before = fs::read_to_string(&path).unwrap(); + let preview = repair(&path, &issues, false).unwrap(); + assert_eq!(fs::read_to_string(&path).unwrap(), before); + assert!(preview.contains("# keep this comment")); + assert!(preview.contains("# keep inline")); + repair(&path, &issues, true).unwrap(); + assert!(changes(&path, "https://example.com/x/y", "release-") + .unwrap() + .is_empty()); + assert_eq!( + repair(&path, &[], true).unwrap(), + fs::read_to_string(&path).unwrap() + ); + } + #[test] + fn rejects_malformed_metadata_table() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("Cargo.toml"); + fs::write(&path, "[package]\nname='demo'\nmetadata='oops'\n").unwrap(); + assert!(changes(&path, "https://example.com/x/y", "v") + .unwrap_err() + .to_string() + .contains("package.metadata must be a table")); + } +} diff --git a/src/project.rs b/src/project.rs index 487dc51..17f343b 100644 --- a/src/project.rs +++ b/src/project.rs @@ -161,6 +161,120 @@ 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 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 { + return Err(Error(format!( + "Git tag {tag:?} does not point to this checkout. Check it out explicitly." + ))); + } + Ok(()) +} + +pub fn normalize_repository(input: &str) -> Result { + let candidate = if let Some((user_host, path)) = input.split_once(':') { + if !input.contains("://") && user_host.contains('@') { + let (user, host) = user_host.split_once('@').unwrap_or(("", "")); + if user.is_empty() || host.is_empty() || path.is_empty() { + return Err(Error( + "Repository must be an HTTP(S) or SSH Git URL; use --repository-url.".into(), + )); + } + format!("https://{host}/{path}") + } else { + input.to_owned() + } + } else { + input.to_owned() + }; + let parsed = url::Url::parse(&candidate).map_err(|_| { + Error("Repository must be an HTTP(S) or SSH Git URL; use --repository-url.".into()) + })?; + if !matches!(parsed.scheme(), "http" | "https" | "ssh") || parsed.host_str().is_none() { + return Err(Error( + "Repository must be an HTTP(S) or SSH Git URL; use --repository-url.".into(), + )); + } + if parsed.password().is_some() + || (parsed.scheme() != "ssh" && !parsed.username().is_empty()) + || parsed.query().is_some() + || parsed.fragment().is_some() + { + return Err(Error( + "Repository URLs must not contain credentials, query strings or fragments.".into(), + )); + } + let parts: Vec<_> = parsed + .path_segments() + .ok_or_else(|| Error("Repository URL must end in owner/repository.".into()))? + .filter(|part| !part.is_empty()) + .collect(); + if parts.len() < 2 + || parts.iter().any(|part| { + *part == "." + || *part == ".." + || !part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) + }) + { + return Err(Error("Repository URL must end in owner/repository.".into())); + } + let name = parts[parts.len() - 1] + .strip_suffix(".git") + .unwrap_or(parts[parts.len() - 1]); + if name.is_empty() || name == "." || name == ".." { + return Err(Error("Repository name is empty.".into())); + } + let host = parsed.host_str().unwrap_or_default(); + let authority = if let Some(port) = parsed.port() { + format!("{host}:{port}") + } else { + host.to_owned() + }; + let scheme = if parsed.scheme() == "ssh" { + "https" + } else { + parsed.scheme() + }; + Ok(format!( + "{scheme}://{authority}/{}{}{}", + parts[..parts.len() - 1].join("/"), + "/", + name + )) +} + #[cfg(test)] mod tests { use super::*; @@ -235,4 +349,27 @@ mod tests { .to_string() .contains("exactly one binary")); } + + #[test] + fn repository_url_normalization_rejects_credentials() { + assert_eq!( + normalize_repository("git@example.com:owner/demo.git").unwrap(), + "https://example.com/owner/demo" + ); + assert_eq!( + normalize_repository("ssh://git@example.com/owner/demo.git").unwrap(), + "https://example.com/owner/demo" + ); + assert_eq!( + normalize_repository("https://example.com/gitea/owner/demo.git").unwrap(), + "https://example.com/gitea/owner/demo" + ); + for value in [ + "https://token@example.com/owner/demo", + "https://example.com/owner/demo?token=secret", + "https://example.com/owner/../demo", + ] { + assert!(normalize_repository(value).is_err(), "{value}"); + } + } }