ci-cargo 0.1.0

Continuous integration using cargo for Clippy and tests for all possible features.
//! Consult [`README.md`](https://crates.io/crates/ci-cargo).
extern crate alloc;
/// Functionality related to parsing CLI arguments.
mod args;
/// Functionality related to running `cargo`.
mod cargo;
/// Functionality related to `Cargo.toml` parsing.
mod manifest;
/// Contains a `const bool` that is `true` iff `rustup` is supported by the platform.
mod rustup;
use args::{ArgsErr, HELP_MSG, MetaCmd};
use cargo::{CargoErr, Options, Toolchain, ToolchainErr};
#[cfg(target_os = "openbsd")]
use core::ffi::CStr;
use manifest::{Manifest, ManifestErr};
#[cfg(target_os = "openbsd")]
use priv_sep::{Errno, Permissions, Promise, Promises};
use std::{
    collections::HashSet,
    env, fs,
    io::{self, BufWriter, Error, Write as _},
    path::{Path, PathBuf},
    process::ExitCode,
};
/// Application error.
enum E {
    /// Error related to the passed arguments.
    Args(ArgsErr),
    /// Error getting the current directory.
    CurDir(Error),
    /// Error looking for `Cargo.toml`.
    CargoTomlIo(Error, PathBuf),
    /// Error when `Cargo.toml` could not be found.
    ///
    /// Note this is not returned when `--dir` is passed.
    CargoTomlDoesNotExist(PathBuf),
    /// Error canonicalizing `--dir`.
    CanonicalizePath(Error, PathBuf),
    /// Error setting the working directory.
    SetDir(Error, PathBuf),
    /// Error reading `Cargo.toml`.
    CargoTomlRead(Error, PathBuf),
    /// Error related to extracting the necessary data from `Cargo.toml`.
    Manifest(Box<ManifestErr>),
    /// Error looking for `rust-toolchain.toml`.
    RustToolchainTomlIo(Error, PathBuf),
    /// Error when `--ignore-msrv` was passed when using the `stable` toolchain.
    IgnoreMsrvStable,
    /// Error from `Msrv::compare_to_other`.
    Toolchain(Box<ToolchainErr>),
    /// Error from OpenBSD `pledge`.
    #[cfg(target_os = "openbsd")]
    Pledge(Errno),
    /// Error from OpenBSD `unveil`.
    #[cfg(target_os = "openbsd")]
    Unveil(Errno),
    /// Variant returned where there are too many features to generate the power set on.
    TooManyFeatures(PathBuf),
    /// Unable to write non-terminating messages to stderr.
    StdErr,
    /// Unable to write the help message to stdout.
    Help(Error),
    /// Unable to write the version message to stdout.
    Version(Error),
    /// `cargo` erred.
    Cargo(Box<CargoErr>),
    /// Unable to write the summary message to stdout.
    Summary(Error),
}
impl E {
    /// Writes `self` to `stderr` before returning [`ExitCode::FAILURE`].
    fn into_exit_code(self) -> ExitCode {
        let mut stderr = io::stderr().lock();
        match self {
            Self::Args(e) => e.write(stderr),
            Self::CurDir(err) => {
                writeln!(
                    stderr,
                    "There was an error getting the working directory: {err}."
                )
            }
            Self::CargoTomlIo(err, p) => {
                writeln!(stderr, "There was an error looking for Cargo.toml in {} and its ancestor directories: {err}.", p.display())
            }
            Self::CargoTomlDoesNotExist(p) => {
                writeln!(stderr, "Cargo.toml does not exist in {} nor its ancestor directories.", p.display())
            }
            Self::CanonicalizePath(err, p) => {
                writeln!(
                    stderr,
                    "There was an error canonicalizing the path {}: {err}.",
                    p.display()
                )
            }
            Self::SetDir(err, p) => {
                writeln!(
                    stderr,
                    "There was an error changing the working directory to {}: {err}.", p.display()
                )
            }
            Self::CargoTomlRead(err, p) => {
                writeln!(stderr, "There was an error reading {}: {err}.", p.display())
            }
            Self::Manifest(e) => e.write(stderr),
            Self::RustToolchainTomlIo(err, p) => {
                writeln!(
                    stderr,
                    "There was an error looking for rust-toolchain.toml in {} and its ancestor directories: {err}.", p.display()
                )
            }
            Self::IgnoreMsrvStable => writeln!(stderr, "--ignore-msrv was passed when using the stable toolchain."),
            Self::Toolchain(e) => e.write(stderr),
            #[cfg(target_os = "openbsd")]
            Self::Pledge(e) => writeln!(stderr, "pledge(2) erred: {e}."),
            #[cfg(target_os = "openbsd")]
            Self::Unveil(e) => writeln!(stderr, "unveil(2) erred: {e}."),
            Self::TooManyFeatures(p) => writeln!(stderr, "There are too many features defined in {}. The max number of features allowed is the number of bits that make up a pointer.", p.display()),
            Self::StdErr => Ok(()),
            Self::Help(err) => writeln!(
                stderr,
                "There was an error writing ci-cargo help to stdout: {err}."
            ),
            Self::Version(err) => writeln!(
                stderr,
                "There was an error writing ci-cargo version to stdout: {err}."
            ),
            Self::Cargo(e) => e.write(stderr),
            Self::Summary(err) => writeln!(
                stderr,
                "There was an error writing the summary to stdout: {err}."
            ),
        }
        .map_or(ExitCode::FAILURE, |()| ExitCode::FAILURE)
    }
}
/// No-op.
#[cfg(not(target_os = "openbsd"))]
#[expect(clippy::unnecessary_wraps, reason = "unify OpenBSD with non-OpenBSD")]
const fn priv_init<Never>() -> Result<(), Never> {
    Ok(())
}
/// Returns the inital set of `Promises` we pledged in addition to allow read permissions to the entire file system.
#[cfg(target_os = "openbsd")]
fn priv_init() -> Result<Promises, E> {
    let proms = Promises::new([
        Promise::Exec,
        Promise::Proc,
        Promise::Rpath,
        Promise::Stdio,
        Promise::Unveil,
    ]);
    proms.pledge().map_err(E::Pledge).and_then(|()| {
        Permissions::READ
            .unveil(c"/")
            .map_err(E::Unveil)
            .map(|()| proms)
    })
}
/// `c"/"`.
#[cfg(target_os = "openbsd")]
const ROOT: &CStr = c"/";
/// `"Cargo.toml"`.
fn cargo_toml() -> &'static Path {
    Path::new("Cargo.toml")
}
/// `"rust-toolchain.toml"`.
fn rust_toolchain_toml() -> &'static Path {
    Path::new("rust-toolchain.toml")
}
/// No-op.
#[cfg(not(target_os = "openbsd"))]
#[expect(clippy::unnecessary_wraps, reason = "unify OpenBSD with non-OpenBSD")]
const fn priv_sep_final<Never>(_: &mut (), _: &Path) -> Result<(), Never> {
    Ok(())
}
/// Remove read permissions to the entire file system before allowing execute permissions to `cargo_path` or `ROOT`.
/// Last remove read and unveil permissions.
#[cfg(target_os = "openbsd")]
fn priv_sep_final(proms: &mut Promises, cargo_path: &Path) -> Result<(), E> {
    Permissions::NONE
        .unveil(ROOT)
        .map_err(E::Unveil)
        .and_then(|()| {
            if cargo_path.is_absolute() {
                Permissions::EXECUTE.unveil(cargo_path).map_err(E::Unveil)
            } else {
                Permissions::EXECUTE.unveil(ROOT).map_err(E::Unveil)
            }
            .and_then(|()| {
                proms
                    .remove_promises_then_pledge([Promise::Rpath, Promise::Unveil])
                    .map_err(E::Pledge)
            })
        })
}
/// Finds `file` in `cur_dir` or its ancestor directories returning `true` iff `file` exists. Searching is
/// done from child directories up.
///
/// We make this recursive in the rare (impossible?) case that traversal becomes circular; in which case,
/// we want a stack overflow to occur.
fn get_path_of_file(cur_dir: &mut PathBuf, file: &Path) -> Result<bool, Error> {
    cur_dir.push(file);
    fs::exists(&cur_dir).and_then(|exists| {
        // Remove `file`.
        _ = cur_dir.pop();
        if exists {
            Ok(true)
        } else if cur_dir.pop() {
            get_path_of_file(cur_dir, file)
        } else {
            Ok(false)
        }
    })
}
/// Current version of this crate.
const VERSION: &str = concat!("ci-cargo ", env!("CARGO_PKG_VERSION"));
#[expect(
    clippy::arithmetic_side_effects,
    reason = "comment justifies correctness"
)]
fn main() -> ExitCode {
    priv_init().and_then(|mut proms| MetaCmd::from_args(env::args_os()).map_err(E::Args).and_then(|meta_cmd| {
        match meta_cmd {
            MetaCmd::Help => io::stdout().lock().write_all(HELP_MSG.as_bytes()).map_err(E::Help),
            MetaCmd::Version => writeln!(io::stdout().lock(), "{VERSION}").map_err(E::Version),
            MetaCmd::Cargo(cmd, mut opts) => opts.exec_dir.map_or_else(
                || env::current_dir().map_err(E::CurDir).and_then(|mut path| {
                    let search_start = path.clone();
                    get_path_of_file(&mut path, cargo_toml()).map_err(|e| E::CargoTomlIo(e, search_start.clone())).and_then(|exists| if exists { Ok(path) } else { Err(E::CargoTomlDoesNotExist(search_start)) })
                }),
                |path| fs::canonicalize(&path).map_err(|e| E::CanonicalizePath(e, path)),
            ).and_then(|mut cur_dir| env::set_current_dir(&cur_dir).map_err(|e| E::SetDir(e, cur_dir.clone())).and_then(|()| {
                cur_dir.push(cargo_toml());
                let mut skip_no_feats = false;
                // `ignore_features` is unique, so we simply need to check for the first
                // occurrence of an empty string and remove it. We do this _before_ calling
                // `Manifest::from_toml` since the empty string is treated special in that it
                // represents the empty set of features. It is not the name of a feature. Note
                // `cargo` disallows an empty string to be a feature name, so there is no fear
                // of misinterpeting it.
                if let Err(ig_idx) = opts.ignore_features.iter().try_fold(0, |idx, feat| {
                    if feat.is_empty() {
                        Err(idx)
                    } else {
                        // Clearly can't overflow since this is the index. Caps at `isize::MAX`.
                        Ok(idx + 1)
                    }
                }) {
                    skip_no_feats = true;
                    drop(opts.ignore_features.swap_remove(ig_idx));
                }
                fs::read_to_string(&cur_dir).map_err(|e| E::CargoTomlRead(e, cur_dir.clone())).and_then(|toml| Manifest::from_toml(toml, opts.allow_implied_features, &cur_dir, &opts.ignore_features).map_err(E::Manifest).and_then(|man| {
                    if opts.default_toolchain || (!rustup::SUPPORTED && opts.rustup_home.is_none()) {
                        Ok(Toolchain::Default(opts.ignore_msrv))
                    } else {
                        let mut cargo_toml_path = cur_dir.clone();
                        _ = cargo_toml_path.pop();
                        get_path_of_file(&mut cargo_toml_path, rust_toolchain_toml()).map_err(|e| E::RustToolchainTomlIo(e, cargo_toml_path)).and_then(|rust_toolchain_exists| if rust_toolchain_exists { Ok(Toolchain::Default(opts.ignore_msrv)) } else if opts.ignore_msrv { Err(E::IgnoreMsrvStable) } else { Ok(Toolchain::Stable) })
                    }.and_then(|toolchain| priv_sep_final(&mut proms, &opts.cargo_path).and_then(|()| man.package().msrv().map_or(Ok(None), |msrv| if !opts.skip_msrv && (rustup::SUPPORTED || opts.rustup_home.is_some()) {
                        msrv.compare_to_other(matches!(toolchain, Toolchain::Default(_)), opts.rustup_home.as_deref(), &opts.cargo_path, opts.cargo_home.as_deref()).map_err(E::Toolchain)
                    } else {
                        Ok(None)
                    }).and_then(|msrv_string| {
                        let default_feature_does_not_exist = !man.features().contains_default();
                        man.features().power_set(skip_no_feats).map_err(|_e| E::TooManyFeatures(cur_dir)).and_then(|power_set_opt| power_set_opt.map_or_else(|| Ok(()), |mut power_set| {
                            let mut non_term_errs = HashSet::new();
                            cmd.run(Options { toolchain, rustup_home: opts.rustup_home, cargo_path: opts.cargo_path, cargo_home: opts.cargo_home, package_name: man.package().name(), color: opts.color, ignore_compile_errors: opts.ignore_compile_errors, default_feature_does_not_exist, non_terminating_errors: &mut non_term_errs, }, msrv_string.as_deref(), &mut power_set, opts.progress).map_err(E::Cargo).and_then(|()| {
                                if non_term_errs.is_empty() {
                                    Ok(())
                                } else {
                                    // `StderrLock` is not buffered.
                                    let mut stderr = BufWriter::new(io::stderr().lock());
                                    non_term_errs.into_iter().try_fold((), |(), msg| stderr.write_all(msg.as_bytes())).and_then(|()| stderr.flush()).map_err(|_e| E::StdErr)
                                }
                            }).and_then(|()| {
                                if opts.summary {
                                    let mut stdout = io::stdout().lock();
                                    if matches!(toolchain, Toolchain::Stable) {
                                        if let Some(ref msrv_val) = msrv_string {
                                            writeln!(stdout, "Toolchains used: cargo +stable and cargo {msrv_val}")
                                        } else {
                                            writeln!(stdout, "Toolchain used: cargo +stable")
                                        }
                                    } else if let Some(ref msrv_val) = msrv_string {
                                        writeln!(stdout, "Toolchains used: cargo and cargo {msrv_val}")
                                    } else {
                                        writeln!(stdout, "Toolchain used: cargo")
                                    }.and_then(|()| {
                                        writeln!(stdout, "Features used:").and_then(|()| {
                                            power_set.reset();
                                            while let Some(features) = power_set.next_set() {
                                                writeln!(stdout, "{}", if features.is_empty() { "<none>" } else { features })?;
                                            }
                                            Ok(())
                                        })
                                    }).map_err(E::Summary)
                                } else {
                                    Ok(())
                                }
                            })
                        }))
                    })))
                }))
            }))
        }
    })).map_or_else(E::into_exit_code, |()| ExitCode::SUCCESS)
}