extern crate alloc;
mod args;
mod cargo;
mod manifest;
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,
};
enum E {
Args(ArgsErr),
CurDir(Error),
CargoTomlIo(Error, PathBuf),
CargoTomlDoesNotExist(PathBuf),
CanonicalizePath(Error, PathBuf),
SetDir(Error, PathBuf),
CargoTomlRead(Error, PathBuf),
Manifest(Box<ManifestErr>),
RustToolchainTomlIo(Error, PathBuf),
IgnoreMsrvStable,
Toolchain(Box<ToolchainErr>),
#[cfg(target_os = "openbsd")]
Pledge(Errno),
#[cfg(target_os = "openbsd")]
Unveil(Errno),
TooManyFeatures(PathBuf),
StdErr,
Help(Error),
Version(Error),
Cargo(Box<CargoErr>),
Summary(Error),
}
impl E {
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)
}
}
#[cfg(not(target_os = "openbsd"))]
#[expect(clippy::unnecessary_wraps, reason = "unify OpenBSD with non-OpenBSD")]
const fn priv_init<Never>() -> Result<(), Never> {
Ok(())
}
#[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)
})
}
#[cfg(target_os = "openbsd")]
const ROOT: &CStr = c"/";
fn cargo_toml() -> &'static Path {
Path::new("Cargo.toml")
}
fn rust_toolchain_toml() -> &'static Path {
Path::new("rust-toolchain.toml")
}
#[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(())
}
#[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)
})
})
}
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| {
_ = cur_dir.pop();
if exists {
Ok(true)
} else if cur_dir.pop() {
get_path_of_file(cur_dir, file)
} else {
Ok(false)
}
})
}
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;
if let Err(ig_idx) = opts.ignore_features.iter().try_fold(0, |idx, feat| {
if feat.is_empty() {
Err(idx)
} else {
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 {
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)
}