cargo-ark 0.1.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")]

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};

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

#[derive(Subcommand)]
enum ArkCommand {
    /// 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),
    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>>,
) -> 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);
    }
    let Cli {
        command: ArkCommand::ReleaseDependencies { temp_dir },
    } = Cli::try_parse_from(args).map_err(CliError::Arguments)?;
    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) {
        Ok(()) => ExitCode::SUCCESS,
        Err(CliError::Arguments(error)) => error.exit(),
        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]
    #[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())
                },
            )
            .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"),
            ),
            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"),
        )
        .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"),
        )
        .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"),
        )
        .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)));
    }
}