diff --git a/AGENT_TASKS.md b/AGENT_TASKS.md index 853aaec..1078d1a 100644 --- a/AGENT_TASKS.md +++ b/AGENT_TASKS.md @@ -6,6 +6,16 @@ Migrate `rust_realease` from its current Python implementation to a native Rust The Python implementation remains the behavioral oracle until the Rust replacement passes parity and end-to-end release validation. +## Updated product goals (2026-09-17) + +- Keep useful local unit and fixture tests throughout the rewrite. +- Accept a project and eventually produce either local artifacts or a remote release. +- Support local and remote project repair before building. An explicitly requested repair workflow may create an additional fix commit, tag, and push; ordinary release runs retain the existing mutation boundaries until that workflow is implemented and tested. +- 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. + Work in small, testable phases. Commit migration work in coherent increments. --- diff --git a/Cargo.lock b/Cargo.lock index 974ea9b..f594b6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,415 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "rust_realease" version = "0.1.0" +dependencies = [ + "clap", + "serde", + "serde_json", + "tempfile", + "toml", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "toml" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index cb57c81..fb2c04a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,3 +5,10 @@ edition = "2021" publish = false [dependencies] +clap = { version = "4.5", features = ["derive"] } +toml = "1.1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[dev-dependencies] +tempfile = "3" diff --git a/Jenkinsfile b/Jenkinsfile index b51a8e0..1b3264a 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -52,9 +52,9 @@ pipeline { } } - stage('Skeleton Smoke Test') { + stage('Inspect Smoke Test') { steps { - sh 'cargo run --locked --offline --release' + sh 'cargo run --locked --offline --release -- . --stop-after inspect' } } } @@ -64,8 +64,8 @@ pipeline { publishChecks( conclusion: 'SUCCESS', name: 'Rust CI', - summary: 'Rust skeleton passed all CI checks.', - text: 'Formatting, strict Clippy, Cargo tests, release build, and skeleton startup passed. Release functionality is not implemented yet.', + summary: 'Rust inspect milestone passed all CI checks.', + text: 'Formatting, strict Clippy, Cargo tests, release build, and local project inspection passed. Release functionality is still being ported.', title: 'CI Successful' ) } diff --git a/README.md b/README.md index 9eb8a51..2fc1d8e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # 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. + +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. + 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. ## Setup diff --git a/src/cli.rs b/src/cli.rs index b8139a2..687006c 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1 +1,127 @@ -//! Placeholder for the future cli implementation. +use crate::{ + config::{self, Overrides}, + error::Error, + model::Stage, + policy, project, +}; +use clap::Parser; +use std::path::PathBuf; + +#[derive(Debug, Parser)] +#[command(about = "Inspect and prepare Rust release inputs", version)] +pub struct Cli { + /// Local directory or Git URL. + pub source: String, + #[arg(long)] + pub package: Option, + #[arg(long, short)] + pub tag: Option, + #[arg(long)] + pub tag_prefix: Option, + #[arg(long)] + pub target: Vec, + #[arg(long)] + pub profile: Option, + #[arg(long, conflicts_with = "unlocked")] + pub locked: bool, + #[arg(long)] + pub unlocked: bool, + #[arg(long)] + pub dry_run: bool, + #[arg(long)] + pub fix_metadata: bool, + #[arg(long)] + pub skip_tests: bool, + #[arg(long)] + pub skip_binstall_test: bool, + #[arg(long)] + pub draft: bool, + #[arg(long)] + pub prerelease: bool, + #[arg(long)] + pub replace_assets: bool, + #[arg(long)] + pub keep_workdir: bool, + #[arg(long)] + pub verbose: bool, + #[arg(long, value_enum)] + pub stop_after: Option, + #[arg(long)] + pub prepare_repo: bool, + #[arg(long)] + pub commit_preparation: bool, + #[arg(long)] + pub create_tag: bool, + #[arg(long)] + pub push_preparation: bool, + #[arg(long)] + pub cross_image_tag: Option, + #[arg(long)] + pub repository_url: Option, + #[arg(long, default_value = "config.toml")] + pub config: PathBuf, +} + +pub fn run(args: Cli) -> Result<(), Error> { + if (args.commit_preparation + || args.create_tag + || args.push_preparation + || args.cross_image_tag.is_some()) + && !args.prepare_repo + { + return Err(Error("Preparation options require --prepare-repo.".into())); + } + if args.prepare_repo && args.stop_after.is_some() { + return Err(Error( + "--prepare-repo is a separate mode; omit --stop-after.".into(), + )); + } + let config = config::load( + &args.config, + Overrides { + targets: args.target, + profile: args.profile, + unlocked: args.unlocked, + tag_prefix: args.tag_prefix, + }, + )?; + let selected = project::inspect(&args.source, args.package.as_deref())?; + 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!( + "Tag {:?} does not match package version; expected {tag:?}.", + args.tag + ))); + } + println!("Package: {}", selected.name); + println!("Version: {}", selected.version); + println!("Binary: {}", selected.binary); + println!("Manifest: {}", selected.manifest.display()); + println!("Tag: {tag}"); + if args + .stop_after + .is_some_and(|stage| stage.order() <= Stage::Inspect.order()) + { + return Ok(()); + } + for target in &config.targets { + println!( + "{target}: {} ({})", + policy::archive_name(&selected.name, target, &selected.version), + policy::binary_filename(&selected.binary, target) + ); + } + for (key, value) in policy::binstall_metadata(&config.tag_prefix) { + println!("Binstall {key}: {value}"); + } + let _ = ( + &config.profile, + config.locked, + &config.token_env, + &selected.repository, + ); + Err(Error( + "Rust release stages after inspect are still being ported; use release.sh for publication." + .into(), + )) +} diff --git a/src/config.rs b/src/config.rs index a2cfe66..6309011 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1 +1,153 @@ -//! Placeholder for the future config implementation. +use crate::error::Error; +use serde::Deserialize; +use std::{fs, path::Path}; + +#[derive(Debug, Deserialize, Default)] +struct FileConfig { + build: Option, + release: Option, + package: Option, + gitea: Option, +} +#[derive(Debug, Deserialize, Default)] +struct Build { + targets: Option>, + profile: Option, + locked: Option, +} +#[derive(Debug, Deserialize, Default)] +struct Release { + #[serde(rename = "tag-prefix")] + tag_prefix: Option, +} +#[derive(Debug, Deserialize, Default)] +struct Package { + format: Option, +} +#[derive(Debug, Deserialize, Default)] +struct Gitea { + #[serde(rename = "token-env")] + token_env: Option, +} + +#[derive(Debug, Clone)] +pub struct Config { + pub targets: Vec, + pub profile: String, + pub locked: bool, + pub tag_prefix: String, + pub token_env: String, +} +#[derive(Default)] +pub struct Overrides { + pub targets: Vec, + pub profile: Option, + 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) +} +fn parse(source: &str, overrides: Overrides) -> Result { + let file: FileConfig = + toml::from_str(source).map_err(|e| Error(format!("invalid config: {e}")))?; + let build = file.build.unwrap_or_default(); + let release = file.release.unwrap_or_default(); + let package = file.package.unwrap_or_default(); + let gitea = file.gitea.unwrap_or_default(); + if package.format.as_deref().unwrap_or("tgz") != "tgz" { + return Err(Error("Only package.format = \"tgz\" is supported.".into())); + } + let mut config = Config { + targets: if overrides.targets.is_empty() { + build.targets.unwrap_or_else(|| { + [ + "x86_64-unknown-linux-musl", + "aarch64-unknown-linux-musl", + "x86_64-pc-windows-gnu", + ] + .map(str::to_owned) + .to_vec() + }) + } else { + overrides.targets + }, + profile: overrides + .profile + .or(build.profile) + .unwrap_or_else(|| "release".into()), + locked: if overrides.unlocked { + false + } else { + build.locked.unwrap_or(true) + }, + tag_prefix: overrides + .tag_prefix + .or(release.tag_prefix) + .unwrap_or_else(|| "v".into()), + token_env: gitea.token_env.unwrap_or_else(|| "GITEA_TOKEN".into()), + }; + if config.targets.is_empty() || config.targets.iter().any(|target| !valid_target(target)) { + return Err(Error( + "build.targets must be a nonempty list of Rust target triples.".into(), + )); + } + let mut unique = Vec::new(); + for target in config.targets { + if !unique.contains(&target) { + unique.push(target); + } + } + config.targets = unique; + if !valid_profile(&config.profile) { + return Err(Error("build.profile must be a Cargo profile name.".into())); + } + if !config + .tag_prefix + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) + { + return Err(Error( + "release.tag-prefix must contain only letters, digits, dots, underscores or hyphens." + .into(), + )); + } + if !valid_env(&config.token_env) { + return Err(Error( + "gitea.token-env must be an environment variable name.".into(), + )); + } + Ok(config) +} +fn valid_target(s: &str) -> bool { + s.split('-').count() >= 3 + && s.split('-').all(|part| { + !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + }) +} +fn valid_profile(s: &str) -> bool { + s.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) +} +fn valid_env(s: &str) -> bool { + s.as_bytes() + .first() + .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_') + && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn overrides_and_validation() { + let config = parse("[build]\ntargets=['x86_64-unknown-linux-musl']\nlocked=true\n[release]\ntag-prefix='v'", Overrides { targets: vec!["aarch64-unknown-linux-musl".into()], unlocked: true, tag_prefix: Some(String::new()), ..Overrides::default() }).unwrap(); + assert_eq!(config.targets, ["aarch64-unknown-linux-musl"]); + assert!(!config.locked); + assert_eq!(config.tag_prefix, ""); + assert!(parse("[build]\ntargets=['bad']", Overrides::default()).is_err()); + assert!(parse("[package]\nformat='zip'", Overrides::default()).is_err()); + } +} diff --git a/src/error.rs b/src/error.rs index 4ff2090..e99f64c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1 +1,10 @@ -//! Placeholder for the future error implementation. +use std::fmt; + +#[derive(Debug)] +pub struct Error(pub String); + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} diff --git a/src/main.rs b/src/main.rs index c906d98..e7dd97c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,18 @@ -//! Rust rewrite skeleton. Release functionality is not implemented yet. +//! Entry point for the incremental Rust replacement. -mod build; mod cli; mod config; mod error; -mod gitea; -mod manifest; mod model; -mod package; -mod prepare; +mod policy; mod project; -mod runner; -mod verify; -fn main() {} +use clap::Parser; + +fn main() { + let args = cli::Cli::parse(); + if let Err(error) = cli::run(args) { + eprintln!("error: {error}"); + std::process::exit(1); + } +} diff --git a/src/model.rs b/src/model.rs index 154e860..20bcac9 100644 --- a/src/model.rs +++ b/src/model.rs @@ -1 +1,19 @@ -//! Placeholder for the future model implementation. +use clap::ValueEnum; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] +pub enum Stage { + Inspect, + Metadata, + Verify, + Build, + Package, + Release, + Upload, + Binstall, +} + +impl Stage { + pub fn order(self) -> usize { + self as usize + } +} diff --git a/src/policy.rs b/src/policy.rs new file mode 100644 index 0000000..d44746e --- /dev/null +++ b/src/policy.rs @@ -0,0 +1,57 @@ +pub fn expected_tag(version: &str, prefix: &str) -> String { + format!("{prefix}{version}") +} + +pub fn archive_root(name: &str, target: &str, version: &str) -> String { + format!("{name}-{target}-v{version}") +} + +pub fn archive_name(name: &str, target: &str, version: &str) -> String { + format!("{}.tgz", archive_root(name, target, version)) +} + +pub fn binary_filename(binary: &str, target: &str) -> String { + if target.split('-').any(|part| part == "windows") { + format!("{binary}.exe") + } else { + binary.to_owned() + } +} + +pub fn binstall_metadata(prefix: &str) -> [(&'static str, String); 3] { + let root = archive_root("{ name }", "{ target }", "{ version }"); + [ + ( + "pkg-url", + format!("{{ repo }}/releases/download/{prefix}{{ version }}/{root}.tgz"), + ), + ("pkg-fmt", "tgz".to_owned()), + ("bin-dir", format!("{root}/{{ bin }}{{ binary-ext }}")), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_match_python_contract() { + assert_eq!(expected_tag("0.3.1", ""), "0.3.1"); + assert_eq!(expected_tag("0.3.1", "release-"), "release-0.3.1"); + assert_eq!( + archive_name("demo", "x86_64-pc-windows-gnu", "0.3.1"), + "demo-x86_64-pc-windows-gnu-v0.3.1.tgz" + ); + assert_eq!(binary_filename("demo", "x86_64-pc-windows-gnu"), "demo.exe"); + assert_eq!(binary_filename("demo", "x86_64-unknown-linux-musl"), "demo"); + let metadata = binstall_metadata("release-"); + assert_eq!( + metadata[0].1, + "{ repo }/releases/download/release-{ version }/{ name }-{ target }-v{ version }.tgz" + ); + assert_eq!( + metadata[2].1, + "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }" + ); + } +} diff --git a/src/project.rs b/src/project.rs index 4d9d06b..487dc51 100644 --- a/src/project.rs +++ b/src/project.rs @@ -1 +1,238 @@ -//! Placeholder for the future project implementation. +use crate::error::Error; +use serde::Deserialize; +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, +}; + +#[derive(Debug)] +pub struct SelectedPackage { + pub name: String, + pub version: String, + pub binary: String, + pub manifest: PathBuf, + pub repository: Option, +} +#[derive(Deserialize)] +struct Metadata { + packages: Vec, + workspace_members: Vec, + workspace_root: PathBuf, +} +#[derive(Deserialize)] +struct Package { + id: String, + name: String, + version: String, + manifest_path: PathBuf, + repository: Option, + targets: Vec, +} +#[derive(Deserialize)] +struct Target { + name: String, + kind: Vec, +} + +pub fn inspect(source: &str, package_name: Option<&str>) -> Result { + let root = Path::new(source); + if !root.is_dir() { + return Err(Error( + "Rust inspect currently requires a local project directory.".into(), + )); + } + let manifest = root.join("Cargo.toml"); + let source_text = fs::read_to_string(&manifest) + .map_err(|e| Error(format!("cannot read {}: {e}", manifest.display())))?; + let source_doc: toml::Value = toml::from_str(&source_text) + .map_err(|e| Error(format!("invalid {}: {e}", manifest.display())))?; + let output = Command::new("cargo") + .args(["metadata", "--format-version=1", "--no-deps"]) + .current_dir(root) + .output() + .map_err(|e| Error(format!("cannot run cargo metadata: {e}")))?; + if !output.status.success() { + return Err(Error(format!( + "cargo metadata failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + let metadata: Metadata = serde_json::from_slice(&output.stdout) + .map_err(|e| Error(format!("invalid cargo metadata output: {e}")))?; + let members: Vec<_> = metadata + .packages + .into_iter() + .filter(|p| metadata.workspace_members.contains(&p.id)) + .collect(); + let discovered = members + .iter() + .map(|p| p.name.as_str()) + .collect::>() + .join(", "); + let selected = match package_name { + Some(name) => members + .into_iter() + .find(|p| p.name == name) + .ok_or_else(|| { + Error(format!( + "Workspace package {name:?} was not found uniquely; discovered: {discovered}" + )) + })?, + None if source_doc + .get("package") + .and_then(toml::Value::as_table) + .is_some() + && members.len() == 1 => + { + members + .into_iter() + .next() + .ok_or_else(|| Error("No workspace package found.".into()))? + } + None => { + return Err(Error(format!( + "Workspace selection requires --package NAME; discovered: {discovered}" + ))) + } + }; + let binaries: Vec<_> = selected + .targets + .iter() + .filter(|t| t.kind.iter().any(|kind| kind == "bin")) + .collect(); + if binaries.len() != 1 { + return Err(Error(format!( + "Package {:?} must have exactly one binary; discovered: {}", + selected.name, + binaries + .iter() + .map(|t| t.name.as_str()) + .collect::>() + .join(", ") + ))); + } + for value in [&selected.name, &selected.version, &binaries[0].name] { + if !safe_component(value) { + return Err(Error("Unsafe package, version or binary filename.".into())); + } + } + let workspace_root = metadata + .workspace_root + .canonicalize() + .map_err(|e| Error(format!("invalid workspace root: {e}")))?; + let member_manifest = selected + .manifest_path + .canonicalize() + .map_err(|e| Error(format!("invalid member manifest: {e}")))?; + if !member_manifest.starts_with(&workspace_root) { + return Err(Error( + "Selected package manifest is outside the workspace root.".into(), + )); + } + let member_text = fs::read_to_string(&member_manifest) + .map_err(|e| Error(format!("cannot read {}: {e}", member_manifest.display())))?; + let member_doc: toml::Value = toml::from_str(&member_text) + .map_err(|e| Error(format!("invalid {}: {e}", member_manifest.display())))?; + if member_doc + .get("package") + .and_then(toml::Value::as_table) + .is_none() + { + return Err(Error( + "Selected Cargo.toml contains no [package] table.".into(), + )); + } + Ok(SelectedPackage { + name: selected.name, + version: selected.version, + binary: binaries[0].name.clone(), + manifest: member_manifest, + repository: selected.repository, + }) +} +fn safe_component(value: &str) -> bool { + value + .as_bytes() + .first() + .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_') + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_.+-".contains(&b)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(root: &Path, path: &str, content: &str) { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + + #[test] + fn standalone_project_and_workspace_selection() { + let temp = tempfile::tempdir().unwrap(); + write( + temp.path(), + "Cargo.toml", + "[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(); + assert_eq!(selected.name, "solo"); + assert_eq!(selected.binary, "solo"); + + let workspace = tempfile::tempdir().unwrap(); + write( + workspace.path(), + "Cargo.toml", + "[workspace]\nmembers=['one','two']\nresolver='2'\n", + ); + for name in ["one", "two"] { + write( + workspace.path(), + &format!("{name}/Cargo.toml"), + &format!("[package]\nname='{name}'\nversion='0.2.0'\nedition='2021'\n"), + ); + write( + workspace.path(), + &format!("{name}/src/main.rs"), + "fn main() {}\n", + ); + } + let root = workspace.path().to_str().unwrap(); + assert!(inspect(root, None) + .unwrap_err() + .to_string() + .contains("--package")); + assert!(inspect(root, Some("missing")) + .unwrap_err() + .to_string() + .contains("not found")); + assert_eq!(inspect(root, Some("two")).unwrap().binary, "two"); + } + + #[test] + fn rejects_library_and_multiple_binaries() { + let temp = tempfile::tempdir().unwrap(); + write( + temp.path(), + "Cargo.toml", + "[package]\nname='demo'\nversion='0.1.0'\nedition='2021'\n", + ); + write(temp.path(), "src/lib.rs", "pub fn hello() {}\n"); + let root = temp.path().to_str().unwrap(); + assert!(inspect(root, None) + .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) + .unwrap_err() + .to_string() + .contains("exactly one binary")); + } +}