cargo-ark 0.2.0

Cargo release utilities
Documentation
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
#![doc = include_str!("../docs/cli.md")]

mod publish_github_release;

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::io::{self, Read};
use std::path::PathBuf;
use std::process::ExitCode;

use cargo_ark::release_dependencies::{Candidates, CargoInvoker, check};
use clap::{Parser, Subcommand};
use ohno::AppError;

#[derive(Parser)]
#[command(name = "cargo ark", version, about)]
struct Cli {
    #[command(subcommand)]
    command: ArkCommand,
}

#[derive(Subcommand)]
enum ArkCommand {
    /// Generate release notes from Git history and publish a GitHub release.
    PublishGithubRelease(publish_github_release::Args),
    /// Validate release candidates by testing their packaged archives.
    ReleaseDependencies {
        /// Existing parent directory for release scratch files (defaults to the system temp directory).
        #[arg(long, value_name = "DIR")]
        temp_dir: Option<PathBuf>,
    },
}

#[derive(Debug)]
enum CliError {
    Arguments(clap::Error),
    Publish(AppError),
    Validation(Box<dyn std::error::Error>),
}

fn run_cli(
    mut args: Vec<OsString>,
    input: impl Read,
    workspace_root: impl FnOnce() -> io::Result<PathBuf>,
    validate: impl FnOnce(Candidates, CargoInvoker) -> Result<(), Box<dyn std::error::Error>>,
    publish: impl FnOnce(&publish_github_release::Args) -> Result<(), AppError>,
) -> Result<(), CliError> {
    if args.get(1).is_some_and(|arg| arg == "ark") {
        // #[gamma::skip(literal.int_decrement, reason = "Clap discards argv[0] and has an explicit command name; leaving ark rather than the binary path in argv[0] is equivalent.")]
        args.remove(1);
    }
    match Cli::try_parse_from(args).map_err(CliError::Arguments)?.command {
        ArkCommand::PublishGithubRelease(args) => publish(&args).map_err(CliError::Publish),
        ArkCommand::ReleaseDependencies { temp_dir } => check_release_dependencies(input, |candidates| {
            let cargo = CargoInvoker::new(&workspace_root()?, BTreeMap::new(), temp_dir.as_deref())?;
            validate(candidates, cargo)
        })
        .map_err(CliError::Validation),
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
fn main() -> ExitCode {
    match run_cli(
        std::env::args_os().collect(),
        io::stdin(),
        std::env::current_dir,
        check,
        publish_github_release::run,
    ) {
        Ok(()) => ExitCode::SUCCESS,
        Err(CliError::Arguments(error)) => error.exit(),
        Err(CliError::Publish(error)) => {
            eprintln!("cargo ark publish-github-release: {error}");
            ExitCode::FAILURE
        }
        Err(CliError::Validation(error)) => {
            eprintln!("cargo ark release-dependencies: {error}");
            ExitCode::FAILURE
        }
    }
}

fn check_release_dependencies(
    mut input: impl Read,
    validate: impl FnOnce(Candidates) -> Result<(), Box<dyn std::error::Error>>,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut report = String::new();
    input.read_to_string(&mut report)?;
    let candidates = Candidates::from_report(&report)?;
    if candidates.is_empty() {
        println!("cargo ark release-dependencies: no release candidates");
        return Ok(());
    }

    validate(candidates)
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;
    use std::path::Path;

    use super::*;

    #[test]
    fn both_cli_spellings_dispatch_github_publishing() {
        for prefix in [&["cargo-ark"][..], &["cargo-ark", "ark"]] {
            let mut args: Vec<_> = prefix.iter().map(OsString::from).collect();
            args.extend(["publish-github-release", "sample-v1.2.3", "--repo", "owner/name", "--dry-run"].map(OsString::from));
            let mut called = false;
            run_cli(
                args,
                Cursor::new([0xff]),
                || panic!("publishing attempted validation workspace setup"),
                |_, _| panic!("publishing attempted dependency validation"),
                |args| {
                    assert_eq!(args.tag, "sample-v1.2.3");
                    assert_eq!(args.repo.as_deref(), Some("owner/name"));
                    assert!(args.dry_run);
                    called = true;
                    Ok(())
                },
            )
            .unwrap();
            assert!(called);
        }
    }

    fn unexpected_publish(_: &publish_github_release::Args) -> Result<(), AppError> {
        panic!("dependency validation attempted GitHub publishing");
    }

    #[test]
    #[cfg_attr(miri, ignore = "uses the host filesystem")]
    fn both_cli_spellings_pass_candidates_and_cargo_to_validation() {
        let scratch_parent = tempfile::tempdir().unwrap();
        let workspace = tempfile::tempdir_in(scratch_parent.path()).unwrap();
        for prefix in [&["cargo-ark"][..], &["cargo-ark", "ark"]] {
            let mut args: Vec<_> = prefix.iter().map(OsString::from).collect();
            args.extend(["release-dependencies", "--temp-dir"].map(OsString::from));
            args.push(scratch_parent.path().as_os_str().to_owned());
            let error = run_cli(
                args,
                Cursor::new(REPORT),
                || Ok(workspace.path().to_path_buf()),
                |candidates, _cargo| {
                    assert!(!candidates.is_empty());
                    Err("scripted validation failure".into())
                },
                unexpected_publish,
            )
            .unwrap_err();
            assert!(matches!(error, CliError::Validation(error) if error.to_string() == "scripted validation failure"));
        }
    }

    #[test]
    fn rejects_a_second_cargo_subcommand_token() {
        let args = ["cargo-ark", "ark", "ark", "release-dependencies"].map(OsString::from);
        assert!(matches!(
            run_cli(
                args.into(),
                Cursor::new([0xff]),
                || panic!("invalid arguments attempted workspace setup"),
                |_, _| panic!("invalid arguments attempted validation"),
                unexpected_publish,
            ),
            Err(CliError::Arguments(error)) if error.kind() == clap::error::ErrorKind::InvalidSubcommand
        ));
    }

    const REPORT: &str = r#"[{"name":"peer","new_version":"1.0.0"}]"#;

    fn release_args() -> Vec<OsString> {
        ["cargo-ark", "release-dependencies"].map(OsString::from).into()
    }

    #[test]
    fn skips_validation_for_an_empty_report() {
        run_cli(
            release_args(),
            Cursor::new("[]"),
            || panic!("an empty report attempted workspace setup"),
            |_, _| panic!("an empty report attempted validation"),
            unexpected_publish,
        )
        .unwrap();
    }

    #[test]
    fn rejects_non_utf8_report_input() {
        let error = check_release_dependencies(Cursor::new([0xff]), |_| panic!("an invalid report attempted validation")).unwrap_err();
        assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn rejects_an_invalid_report_before_validation() {
        let error = check_release_dependencies(Cursor::new(r#"[{"name":"peer"}]"#), |_| {
            panic!("an invalid report attempted validation")
        })
        .unwrap_err();
        assert_eq!(error.to_string(), "candidate is missing its version");
    }

    #[test]
    fn returns_the_workspace_lookup_error() {
        let error = run_cli(
            release_args(),
            Cursor::new(REPORT),
            || Err(io::Error::new(io::ErrorKind::NotFound, "workspace directory disappeared")),
            |_, _| panic!("a failed workspace lookup attempted validation"),
            unexpected_publish,
        )
        .unwrap_err();
        assert!(matches!(error, CliError::Validation(error) if error.to_string() == "workspace directory disappeared"));
    }

    #[test]
    #[cfg_attr(miri, ignore = "uses the host filesystem")]
    fn returns_the_cargo_setup_error() {
        let workspace = tempfile::tempdir().unwrap();
        let file = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        let mut args = release_args();
        args.extend([OsString::from("--temp-dir"), file.as_os_str().to_owned()]);
        let error = run_cli(
            args,
            Cursor::new(REPORT),
            || Ok(workspace.path().to_path_buf()),
            |_, _| panic!("a failed Cargo setup attempted validation"),
            unexpected_publish,
        )
        .unwrap_err();
        let context = format!("preparing release scratch directory in {}: ", file.display());
        assert!(matches!(error, CliError::Validation(error) if error.to_string().starts_with(&context)));
    }
}