use crate::cleanup::{CleanMode, CleanupSelection};
use clap::{CommandFactory, Parser, Subcommand};
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, clap::ValueEnum)]
pub enum OutputFormat {
#[default]
Human,
Json,
Log,
}
#[derive(Clone, Debug, Default, clap::Args)]
pub struct CleanupFlags {
#[arg(long, conflicts_with = "dryrun_legacy", display_order = 5)]
pub dry_run: bool,
#[arg(long = "dryrun", hide = true, conflicts_with = "dry_run")]
pub dryrun_legacy: bool,
#[arg(long, conflicts_with = "root")]
pub full: bool,
#[arg(conflicts_with = "full")]
pub root: Option<PathBuf>,
#[arg(long)]
pub min_reclaimable_bytes: Option<u64>,
#[arg(long)]
pub older_than: Option<u64>,
#[arg(long = "include")]
pub include: Vec<String>,
#[arg(long = "exclude")]
pub exclude: Vec<String>,
#[arg(long, conflicts_with = "package", value_parser = clap::builder::NonEmptyStringValueParser::new())]
pub profile: Option<String>,
#[arg(long, conflicts_with = "profile", value_parser = clap::builder::NonEmptyStringValueParser::new())]
pub package: Option<String>,
#[arg(long, conflicts_with_all = ["dry_run", "dryrun_legacy"])]
pub cargo_preview: bool,
}
impl CleanupFlags {
pub fn overrides(&self) -> CleanupOverrides {
CleanupOverrides {
min_reclaimable_bytes: self.min_reclaimable_bytes,
older_than: self.older_than,
include: self.include.clone(),
exclude: self.exclude.clone(),
profile: self.profile.clone(),
package: self.package.clone(),
}
}
}
#[derive(Debug, clap::Args)]
#[command(
name = "cargo-cleanme",
version,
about = "Clean inactive Cargo build artifacts through Cargo, or reconcile the machine read-only",
long_about = "Clean inactive Cargo build artifacts through Cargo, or reconcile the machine read-only.\n\n\
Bare `cargo cleanme` runs routine maintenance: it selects the maintenance scope \
(bounded seed roots plus active learned roots plus the working directory, or a \
configured scan.root when one exists), re-proves complete ownership for every \
discovered participant, and executes eligible Cargo cleanup units. The working \
directory is part of that scope, so a bare run cleans what is under it -- and the \
scope only ever grows, never narrows. `--dry-run` performs the identical decision \
and proof path while invoking no `cargo clean` process at all.\n\n\
The root is the cleanup front door: `cargo cleanme ROOT` cleans one bounded \
root, `cargo cleanme --full` runs the Full cleanup -- a complete machine \
reconciliation, then the learned roots it can prove -- and `--cargo-preview` and \
the policy overrides work here too. A directory whose name collides with a \
subcommand name is read as that subcommand; spell it `./scan` to name it.\n\n\
`cargo cleanme scan` needs a scope: `--all` is the full read-only machine \
reconciliation and the only operation allowed to expire learned roots, \
`scan ROOT` is a bounded explicit scan, and `scan --known` is the read-only \
maintenance inventory.\n\n\
Deletion is always delegated to Cargo; cargo-cleanme never removes a directory itself."
)]
pub struct Cli {
#[arg(long, global = true)]
pub config: Option<PathBuf>,
#[arg(long, global = true)]
pub no_progress: bool,
#[arg(long, global = true)]
pub stats: bool,
#[arg(long, global = true, value_enum, default_value_t = OutputFormat::Human)]
pub format: OutputFormat,
#[arg(long, global = true)]
pub verbose: bool,
#[arg(short = 'i', long, global = true, display_order = 7)]
pub interactive: bool,
#[command(flatten)]
pub cleanup: CleanupFlags,
#[command(subcommand)]
pub command: Option<Command>,
}
impl CommandFactory for Cli {
fn command() -> clap::Command {
let command = <Self as clap::Args>::augment_args(clap::Command::new("cargo-cleanme"));
configure_cleanup_alias(command)
}
fn command_for_update() -> clap::Command {
<Self as clap::Args>::augment_args_for_update(clap::Command::new("cargo-cleanme"))
}
}
impl Parser for Cli {}
const ALIAS_DRY_RUN_HELP: &str = "Application simulation: run the full decision/proof/report path \
but invoke no Cargo clean command. The default mode is Execute";
fn configure_cleanup_alias(command: clap::Command) -> clap::Command {
command.mut_subcommands(|subcommand| {
if subcommand.get_name() != "clean" {
return subcommand;
}
subcommand.mut_args(|arg| {
let id = arg.get_id().clone();
match id.as_str() {
"dry_run" => arg.help(ALIAS_DRY_RUN_HELP).display_order(900),
"known" => arg.display_order(1),
_ => arg.hide(true),
}
})
})
}
#[derive(Debug, Subcommand)]
pub enum Command {
#[command(group = clap::ArgGroup::new("scan-scope").required(true).args(["root", "known", "all"]))]
Scan {
root: Option<PathBuf>,
#[arg(long)]
known: bool,
#[arg(short = 'a', long, alias = "full")]
all: bool,
},
Config {
#[command(subcommand)]
command: ConfigCommand,
},
#[command(hide = true)]
Clean {
#[command(flatten)]
flags: CleanupFlags,
#[arg(long, conflicts_with_all = ["root", "full"], display_order = 1)]
known: bool,
#[arg(long = "yes", hide = true, conflicts_with_all = ["dry_run", "cargo_preview", "dryrun_legacy"])]
yes_legacy: bool,
},
Update {
#[arg(long)]
dry_run: bool,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Subcommand)]
pub enum ConfigCommand {
Path,
Show,
Edit,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CleanupScope {
Maintenance,
Root(PathBuf),
Full,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ScanIntent {
Full,
Explicit(PathBuf),
Maintenance,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CleanupOverrides {
pub min_reclaimable_bytes: Option<u64>,
pub older_than: Option<u64>,
pub include: Vec<String>,
pub exclude: Vec<String>,
pub profile: Option<String>,
pub package: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CleanupRequest {
pub scope: CleanupScope,
pub mode: CleanMode,
pub overrides: CleanupOverrides,
pub selection: CleanupSelection,
pub interactive: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Invocation {
Cleanup(CleanupRequest),
Scan(ScanIntent),
Config(ConfigCommand),
Update {
dry_run: bool,
},
UsageError(String),
}
pub fn clean_mode(dry_run: bool, cargo_preview: bool, dryrun_legacy: bool) -> CleanMode {
debug_assert!(
!((dry_run || dryrun_legacy) && cargo_preview),
"clap rejects conflicting mode flags before this mapping runs"
);
if dry_run || dryrun_legacy {
CleanMode::Simulate
} else if cargo_preview {
CleanMode::CargoPreview
} else {
CleanMode::Execute
}
}
impl Cli {
pub fn parse_normalized() -> Self {
Self::parse_from(normalize_cargo_argv(std::env::args_os()))
}
pub fn try_parse_normalized_from(
args: impl IntoIterator<Item = OsString>,
) -> Result<Self, clap::Error> {
Self::try_parse_from(normalize_cargo_argv(args))
}
pub fn invocation(&self) -> Invocation {
match &self.command {
None => match self.cleanup_request(&CleanAlias::default()) {
Ok(request) => Invocation::Cleanup(request),
Err(message) => Invocation::UsageError(message),
},
Some(Command::Scan { root, known, all }) => {
if let Some(message) = self.reject_cleanup_flags_for("scan") {
return Invocation::UsageError(message);
}
match (root, *known, *all) {
(Some(root), _, _) => Invocation::Scan(ScanIntent::Explicit(root.clone())),
(None, true, _) => Invocation::Scan(ScanIntent::Maintenance),
(None, false, true) => Invocation::Scan(ScanIntent::Full),
(None, false, false) => {
Invocation::UsageError("scan requires a ROOT, --known, or --all".into())
}
}
}
Some(Command::Config { command }) => {
if let Some(message) = self.reject_cleanup_flags_for("config") {
return Invocation::UsageError(message);
}
Invocation::Config(*command)
}
Some(Command::Update { dry_run }) => {
if let Some(message) = self.reject_cleanup_flags_for("update") {
return Invocation::UsageError(message);
}
Invocation::Update {
dry_run: *dry_run || self.cleanup.dry_run || self.cleanup.dryrun_legacy,
}
}
Some(Command::Clean {
flags,
known,
yes_legacy: _,
}) => match self.cleanup_request(&CleanAlias {
flags: flags.clone(),
known: *known,
}) {
Ok(request) => Invocation::Cleanup(request),
Err(message) => Invocation::UsageError(message),
},
}
}
fn cleanup_request(&self, alias: &CleanAlias) -> Result<CleanupRequest, String> {
if self.cleanup.full && alias.flags.full {
return Err(duplicate_override("--full"));
}
if self.cleanup.root.is_some() && alias.flags.root.is_some() {
return Err(duplicate_override("ROOT"));
}
if self.cleanup.cargo_preview && alias.flags.cargo_preview {
return Err(duplicate_override("--cargo-preview"));
}
if (self.cleanup.dry_run || self.cleanup.dryrun_legacy)
&& (alias.flags.dry_run || alias.flags.dryrun_legacy)
{
return Err(duplicate_dry_run(&dry_run_spellings(
self.cleanup.dry_run,
self.cleanup.dryrun_legacy,
alias.flags.dry_run,
alias.flags.dryrun_legacy,
)));
}
if self.cleanup.full && alias.flags.root.is_some() {
return Err(conflicting_scope_selectors("`--full`", "ROOT"));
}
if self.cleanup.root.is_some() && alias.flags.full {
return Err(conflicting_scope_selectors("ROOT", "`--full`"));
}
let scope = if self.cleanup.full || alias.flags.full {
if alias.known {
return Err(conflicting_scopes(if self.cleanup.full {
"`--full`"
} else {
"`--full` on `clean`"
}));
}
CleanupScope::Full
} else if let Some(root) = self
.cleanup
.root
.clone()
.or_else(|| alias.flags.root.clone())
{
if alias.known {
return Err(conflicting_scopes(if self.cleanup.root.is_some() {
"`ROOT`"
} else {
"`ROOT` on `clean`"
}));
}
CleanupScope::Root(root)
} else {
CleanupScope::Maintenance
};
Ok(CleanupRequest {
selection: selection_for(&scope),
scope,
mode: merged_clean_mode(
(
self.cleanup.dry_run,
self.cleanup.cargo_preview,
self.cleanup.dryrun_legacy,
),
(
alias.flags.dry_run,
alias.flags.cargo_preview,
alias.flags.dryrun_legacy,
),
),
overrides: merge_overrides(&self.cleanup.overrides(), &alias.flags.overrides())?,
interactive: self.interactive,
})
}
fn reject_cleanup_flags_for(&self, subcommand: &str) -> Option<String> {
let mut given: Vec<&str> = Vec::new();
if self.cleanup.full {
given.push("--full");
}
if self.cleanup.root.is_some() {
given.push("ROOT");
}
if self.interactive {
given.push("--interactive");
}
if self.cleanup.min_reclaimable_bytes.is_some() {
given.push("--min-reclaimable-bytes");
}
if self.cleanup.older_than.is_some() {
given.push("--older-than");
}
if !self.cleanup.include.is_empty() {
given.push("--include");
}
if !self.cleanup.exclude.is_empty() {
given.push("--exclude");
}
if self.cleanup.profile.is_some() {
given.push("--profile");
}
if self.cleanup.package.is_some() {
given.push("--package");
}
if self.cleanup.cargo_preview {
given.push("--cargo-preview");
}
if given.is_empty() {
return None;
}
Some(format!(
"`{subcommand}` does not accept {}: these are cleanup flags, and \
`cargo cleanme {subcommand}` is read-only. Run the cleanup without the \
subcommand, or run `{subcommand}` on its own.",
given.join(", ")
))
}
}
fn selection_for(scope: &CleanupScope) -> CleanupSelection {
match scope {
CleanupScope::Maintenance => CleanupSelection::WorkingDirectory,
CleanupScope::Root(_) | CleanupScope::Full => CleanupSelection::All,
}
}
fn merged_clean_mode(root: (bool, bool, bool), clean: (bool, bool, bool)) -> CleanMode {
let (root_dry_run, root_cargo_preview, root_dryrun_legacy) = root;
let (clean_dry_run, clean_cargo_preview, clean_dryrun_legacy) = clean;
if root_dry_run || root_dryrun_legacy || clean_dry_run || clean_dryrun_legacy {
CleanMode::Simulate
} else if root_cargo_preview || clean_cargo_preview {
CleanMode::CargoPreview
} else {
CleanMode::Execute
}
}
fn duplicate_override(flag: &str) -> String {
format!(
"{flag} was given at the root and on `clean`. The two values are ambiguous; \
give it at one level only."
)
}
fn dry_run_spellings(
cleanup_dry_run: bool,
cleanup_dryrun_legacy: bool,
alias_dry_run: bool,
alias_dryrun_legacy: bool,
) -> Vec<&'static str> {
let mut names: Vec<&'static str> = Vec::new();
if cleanup_dry_run || alias_dry_run {
names.push("--dry-run");
}
if cleanup_dryrun_legacy || alias_dryrun_legacy {
names.push("--dryrun");
}
names
}
fn duplicate_dry_run(spellings: &[&str]) -> String {
let named = spellings.join(" and ");
let verb = if spellings.len() == 1 { "was" } else { "were" };
format!("{named} {verb} given at the root and on `clean`. Give it at one level only.")
}
fn conflicting_selectors(root_flag: &str, clean_flag: &str) -> String {
format!(
"{root_flag} was given at the root and {clean_flag} on `clean`. The two selectors are \
mutually exclusive; give one selector at one level only."
)
}
fn conflicting_scopes(root_flag: &str) -> String {
format!(
"{root_flag} at the root and `--known` on `clean` select different scopes; \
give one scope selector at one level only."
)
}
fn conflicting_scope_selectors(root_flag: &str, clean_flag: &str) -> String {
format!(
"{root_flag} at the root and {clean_flag} on `clean` select different scopes; \
give one scope selector at one level only."
)
}
fn merge_overrides(
root: &CleanupOverrides,
clean: &CleanupOverrides,
) -> Result<CleanupOverrides, String> {
if root.profile.is_some() && clean.package.is_some() {
return Err(conflicting_selectors("--profile", "--package"));
}
if root.package.is_some() && clean.profile.is_some() {
return Err(conflicting_selectors("--package", "--profile"));
}
Ok(CleanupOverrides {
min_reclaimable_bytes: merge_one(
"--min-reclaimable-bytes",
root.min_reclaimable_bytes,
clean.min_reclaimable_bytes,
)?,
older_than: merge_one("--older-than", root.older_than, clean.older_than)?,
include: merge_many("--include", &root.include, &clean.include)?,
exclude: merge_many("--exclude", &root.exclude, &clean.exclude)?,
profile: merge_one("--profile", root.profile.clone(), clean.profile.clone())?,
package: merge_one("--package", root.package.clone(), clean.package.clone())?,
})
}
fn merge_one<T: Clone>(flag: &str, root: Option<T>, clean: Option<T>) -> Result<Option<T>, String> {
match (root, clean) {
(Some(_), Some(_)) => Err(duplicate_override(flag)),
(Some(value), None) => Ok(Some(value)),
(None, Some(value)) => Ok(Some(value)),
(None, None) => Ok(None),
}
}
fn merge_many(flag: &str, root: &[String], clean: &[String]) -> Result<Vec<String>, String> {
match (root.is_empty(), clean.is_empty()) {
(false, false) => Err(duplicate_override(flag)),
(false, true) => Ok(root.to_vec()),
(true, false) => Ok(clean.to_vec()),
(true, true) => Ok(Vec::new()),
}
}
#[derive(Clone, Debug, Default)]
struct CleanAlias {
flags: CleanupFlags,
known: bool,
}
const CARGO_EXTERNAL_TOKEN: &str = "cleanme";
pub fn normalize_cargo_argv(args: impl IntoIterator<Item = OsString>) -> Vec<OsString> {
normalize_cargo_argv_with(args, launched_by_cargo())
}
#[doc(hidden)]
pub fn normalize_cargo_argv_with(
args: impl IntoIterator<Item = OsString>,
launched_by_cargo: bool,
) -> Vec<OsString> {
let mut argv: Vec<OsString> = args.into_iter().collect();
if launched_by_cargo && argv.len() >= 2 && argv[1] == CARGO_EXTERNAL_TOKEN {
argv.remove(1);
}
argv
}
fn launched_by_cargo() -> bool {
std::env::var_os("CARGO").is_some()
}
pub fn absolutize_root(root: &Path) -> Result<PathBuf, crate::error::AppError> {
if root.is_absolute() {
return Ok(root.to_path_buf());
}
let base = std::env::current_dir().map_err(|e| crate::error::AppError::InvalidRoot {
path: root.display().to_string(),
reason: format!("cannot resolve current directory: {e}"),
})?;
Ok(absolutize_relative(&base, root))
}
#[doc(hidden)]
pub fn absolutize_root_for_test(base: &Path, root: &Path) -> PathBuf {
if root.is_absolute() {
return root.to_path_buf();
}
absolutize_relative(base, root)
}
pub(crate) fn absolutize_relative(base: &Path, relative: &Path) -> PathBuf {
let mut out = if base.is_absolute() {
base.to_path_buf()
} else {
PathBuf::from("/").join(base)
};
for component in relative.components() {
match component {
Component::Prefix(part) => {
out = PathBuf::from(part.as_os_str());
}
Component::RootDir => {
out.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
let _ = out.pop();
}
Component::Normal(part) => out.push(part),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use clap::{CommandFactory, Parser};
use std::ffi::OsString;
fn maintenance(mode: CleanMode) -> CleanupRequest {
cleanup(CleanupScope::Maintenance, mode)
}
fn cleanup(scope: CleanupScope, mode: CleanMode) -> CleanupRequest {
let selection = match &scope {
CleanupScope::Maintenance => CleanupSelection::WorkingDirectory,
CleanupScope::Root(_) | CleanupScope::Full => CleanupSelection::All,
};
CleanupRequest {
scope,
mode,
overrides: CleanupOverrides::default(),
selection,
interactive: false,
}
}
#[test]
fn the_root_full_flag_resolves_to_the_full_scope() {
let canonical = Cli::try_parse_from(["cargo-cleanme", "--full"])
.unwrap()
.invocation();
assert_eq!(
canonical,
Invocation::Cleanup(cleanup(CleanupScope::Full, CleanMode::Execute)),
"the canonical spelling must resolve to the Full scope"
);
let alias = Cli::try_parse_from(["cargo-cleanme", "clean", "--full"])
.unwrap()
.invocation();
assert_eq!(canonical, alias, "the two spellings must not drift");
}
#[test]
fn the_clean_alias_still_resolves_and_is_hidden_from_the_help() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "--full"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Full, CleanMode::Execute))
);
let help = Cli::command().render_long_help().to_string();
let listed: Vec<&str> = help
.split("Commands:")
.nth(1)
.and_then(|rest| rest.split("Arguments:").next())
.unwrap_or_default()
.lines()
.filter_map(|line| line.split_whitespace().next())
.collect();
assert!(
!listed.contains(&"clean"),
"the hidden subcommand must not reappear in the help text: {listed:?}"
);
let command = Cli::command();
let clean = command.find_subcommand("clean").expect("clean subcommand");
assert!(
clean.is_hide_set(),
"the clean alias must stay hidden from the root help"
);
assert!(
help.contains("--full"),
"the canonical Full cleanup flag must be advertised: {help}"
);
}
#[test]
fn the_policy_overrides_work_at_the_root() {
let root = Cli::try_parse_from([
"cargo-cleanme",
"--older-than",
"3600",
"--min-reclaimable-bytes",
"4096",
"--include",
"/a/*",
"--exclude",
"/b/*",
])
.unwrap()
.invocation();
let alias = Cli::try_parse_from([
"cargo-cleanme",
"clean",
"--older-than",
"3600",
"--min-reclaimable-bytes",
"4096",
"--include",
"/a/*",
"--exclude",
"/b/*",
])
.unwrap()
.invocation();
let Invocation::Cleanup(root_request) = root else {
panic!("the root spelling must resolve to a cleanup");
};
let Invocation::Cleanup(alias_request) = alias else {
panic!("the alias must resolve to a cleanup");
};
assert_eq!(root_request.overrides, alias_request.overrides);
assert_eq!(root_request.overrides.older_than, Some(3600));
assert_eq!(root_request.overrides.min_reclaimable_bytes, Some(4096));
assert_eq!(root_request.overrides.include, vec!["/a/*".to_string()]);
assert_eq!(root_request.overrides.exclude, vec!["/b/*".to_string()]);
}
#[test]
fn the_root_positional_resolves_to_the_bounded_root_scope() {
let canonical = Cli::try_parse_from(["cargo-cleanme", "/tmp/projects"])
.unwrap()
.invocation();
assert_eq!(
canonical,
Invocation::Cleanup(cleanup(
CleanupScope::Root(PathBuf::from("/tmp/projects")),
CleanMode::Execute
))
);
let alias = Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/projects"])
.unwrap()
.invocation();
assert_eq!(canonical, alias, "the two spellings must not drift");
}
#[test]
fn a_subcommand_wins_over_a_positional_of_the_same_shape() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "scan", "--all"])
.unwrap()
.invocation(),
Invocation::Scan(ScanIntent::Full)
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "config", "path"])
.unwrap()
.invocation(),
Invocation::Config(ConfigCommand::Path)
);
}
#[test]
fn the_dot_positional_is_a_bounded_cleanup_and_not_a_usage_error() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "."])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(PathBuf::from(".")),
CleanMode::Execute
))
);
assert!(
Cli::try_parse_from(["cargo-cleanme", "./scan"]).is_ok(),
"an explicitly relative name must stay addressable"
);
}
#[test]
fn the_known_alias_is_not_orphaned_by_the_hiding() {
let alias = Cli::try_parse_from(["cargo-cleanme", "clean", "--known"])
.unwrap()
.invocation();
let bare = Cli::try_parse_from(["cargo-cleanme"]).unwrap().invocation();
assert_eq!(alias, bare, "`clean --known` must stay the bare invocation");
let Invocation::Cleanup(request) = alias else {
panic!("`clean --known` must resolve to a cleanup");
};
assert_eq!(request.scope, CleanupScope::Maintenance);
assert_eq!(request.selection, CleanupSelection::WorkingDirectory);
}
#[test]
fn the_root_help_names_the_canonical_full_cleanup_spelling() {
let help = Cli::command().render_long_help().to_string();
assert!(
help.contains("cargo cleanme --full"),
"the help must name the canonical Full cleanup spelling: {help}"
);
assert!(
help.contains("cargo cleanme ROOT"),
"the help must name the canonical bounded-root spelling: {help}"
);
}
#[test]
fn the_root_and_the_alias_resolve_to_the_same_intent() {
for (root_args, alias_args) in [
(vec!["cargo-cleanme"], vec!["cargo-cleanme", "clean"]),
(
vec!["cargo-cleanme", "/tmp/p"],
vec!["cargo-cleanme", "clean", "/tmp/p"],
),
(
vec!["cargo-cleanme", "--full"],
vec!["cargo-cleanme", "clean", "--full"],
),
(
vec!["cargo-cleanme", "--dry-run"],
vec!["cargo-cleanme", "clean", "--dry-run"],
),
] {
let root = Cli::try_parse_from(root_args.clone()).unwrap().invocation();
let alias = Cli::try_parse_from(alias_args.clone())
.unwrap()
.invocation();
assert_eq!(root, alias, "{root_args:?} and {alias_args:?} must agree");
}
}
#[test]
fn the_whole_published_spelling_set_agrees() {
const SCOPES: &[&[&str]] = &[&[], &["/tmp/c045-fixture"], &["--full"]];
const OVERRIDES: &[&[&str]] = &[
&[],
&["--min-reclaimable-bytes", "42"],
&["--older-than", "60"],
&["--include", "/a/*"],
&["--exclude", "/b/*"],
&["--profile", "release"],
&["--package", "demo"],
];
const MODES: &[&[&str]] = &[&[], &["--dry-run"], &["--dryrun"], &["--cargo-preview"]];
let mut pairs = 0usize;
for scope in SCOPES {
for override_ in OVERRIDES {
for mode in MODES {
let mut root = vec!["cargo-cleanme"];
root.extend_from_slice(scope);
root.extend_from_slice(override_);
root.extend_from_slice(mode);
let mut alias = vec!["cargo-cleanme", "clean"];
alias.extend_from_slice(scope);
alias.extend_from_slice(override_);
alias.extend_from_slice(mode);
let root_invocation = Cli::try_parse_from(root.clone())
.unwrap_or_else(|error| panic!("{root:?} must parse: {error}"))
.invocation();
let alias_invocation = Cli::try_parse_from(alias.clone())
.unwrap_or_else(|error| panic!("{alias:?} must parse: {error}"))
.invocation();
assert_eq!(
root_invocation, alias_invocation,
"{root:?} and {alias:?} must resolve to the same intent"
);
pairs += 1;
}
}
}
assert_eq!(
pairs,
SCOPES.len() * OVERRIDES.len() * MODES.len(),
"the cross product must be enumerated in full"
);
assert!(pairs >= 80, "the table must cover the published surface");
}
#[test]
fn the_alias_accepts_every_cleanup_flag_the_root_declares() {
let mut command = Cli::command();
command.build();
let clean = command.find_subcommand("clean").expect("clean subcommand");
let mut checked = 0usize;
for arg in command.get_arguments() {
let id = arg.get_id().clone();
if id == "help" || id == "version" {
continue;
}
assert!(
clean.get_arguments().any(|alias| *alias.get_id() == id),
"the root's cleanup flag `{id}` must be accepted by `clean`"
);
let mut argv = vec!["cargo-cleanme".to_string(), "clean".to_string()];
match (arg.get_long(), arg.is_positional()) {
(Some(long), _) => {
argv.push(format!("--{long}"));
if let Some(value) = sample_value(arg) {
argv.push(value);
}
}
(None, true) => argv.push("/tmp/c045-fixture".to_string()),
(None, false) => continue,
}
assert!(
Cli::try_parse_from(argv.clone()).is_ok(),
"the alias must accept the root's cleanup flag: {argv:?}"
);
checked += 1;
}
assert!(
checked >= 10,
"the guard must inspect the root's cleanup flags, not pass vacuously"
);
}
fn sample_value(arg: &clap::Arg) -> Option<String> {
if !arg
.get_num_args()
.map(|range| range.takes_values())
.unwrap_or(false)
{
return None;
}
if let Some(first) = arg.get_possible_values().first() {
return Some(first.get_name().to_string());
}
Some("1".to_string())
}
#[test]
fn the_alias_is_still_hidden_and_still_accepted() {
let help = Cli::command().render_long_help().to_string();
let listed: Vec<&str> = help
.split("Commands:")
.nth(1)
.and_then(|rest| rest.split("Arguments:").next())
.unwrap_or_default()
.lines()
.filter_map(|line| line.split_whitespace().next())
.collect();
assert!(
!listed.contains(&"clean"),
"the hidden subcommand must not reappear in the help text: {listed:?}"
);
assert!(
Cli::command()
.find_subcommand("clean")
.expect("clean subcommand")
.is_hide_set(),
"the clean alias must stay hidden from the root help"
);
for (args, expected) in [
(
vec!["cargo-cleanme", "clean", "--known"],
Invocation::Cleanup(maintenance(CleanMode::Execute)),
),
(
vec!["cargo-cleanme", "clean", "--full"],
Invocation::Cleanup(cleanup(CleanupScope::Full, CleanMode::Execute)),
),
(
vec!["cargo-cleanme", "clean", "/tmp/c045-fixture"],
Invocation::Cleanup(cleanup(
CleanupScope::Root(PathBuf::from("/tmp/c045-fixture")),
CleanMode::Execute,
)),
),
] {
assert_eq!(
Cli::try_parse_from(args.clone()).unwrap().invocation(),
expected,
"{args:?} must still resolve"
);
}
}
#[test]
fn the_alias_hide_states_are_unchanged() {
let command = Cli::command();
let clean = command.find_subcommand("clean").expect("clean subcommand");
for flag in [
"root",
"full",
"min_reclaimable_bytes",
"older_than",
"include",
"exclude",
"profile",
"package",
"cargo_preview",
"yes_legacy",
"dryrun_legacy",
] {
let arg = clean
.get_arguments()
.find(|arg| arg.get_id() == flag)
.unwrap_or_else(|| panic!("the clean alias must still carry {flag}"));
assert!(arg.is_hide_set(), "{flag} must be a hidden alias");
}
for flag in ["dry_run", "known"] {
let arg = clean
.get_arguments()
.find(|arg| arg.get_id() == flag)
.unwrap_or_else(|| panic!("the clean alias must still carry {flag}"));
assert!(!arg.is_hide_set(), "{flag} must stay advertised");
}
}
#[test]
fn the_duplicate_override_rule_survives_the_consolidation() {
for args in [
vec![
"cargo-cleanme",
"--older-than",
"3600",
"clean",
"--older-than",
"60",
],
vec![
"cargo-cleanme",
"--min-reclaimable-bytes",
"10",
"clean",
"--min-reclaimable-bytes",
"20",
],
vec![
"cargo-cleanme",
"--include",
"/a/*",
"clean",
"--include",
"/b/*",
],
vec![
"cargo-cleanme",
"--exclude",
"/a/*",
"clean",
"--exclude",
"/b/*",
],
vec!["cargo-cleanme", "--full", "clean", "--full"],
vec!["cargo-cleanme", "/tmp/x", "clean", "/tmp/y"],
vec![
"cargo-cleanme",
"--cargo-preview",
"clean",
"--cargo-preview",
],
vec!["cargo-cleanme", "--dry-run", "clean", "--dry-run"],
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
assert!(
matches!(parsed.invocation(), Invocation::UsageError(_)),
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
}
for args in [
vec!["cargo-cleanme", "--profile", "release", "--package", "demo"],
vec![
"cargo-cleanme",
"clean",
"--profile",
"release",
"--package",
"demo",
],
vec!["cargo-cleanme", "--dry-run", "--dryrun"],
vec!["cargo-cleanme", "clean", "--dry-run", "--dryrun"],
] {
assert!(
Cli::try_parse_from(args.clone()).is_err(),
"{args:?} must be refused by clap"
);
}
}
#[test]
fn the_scope_conflict_rules_survive_the_consolidation() {
for (args, expected) in [
(
vec!["cargo-cleanme", "--full", "clean", "/tmp/x"],
"`--full` at the root and ROOT on `clean`",
),
(
vec!["cargo-cleanme", "/tmp/x", "clean", "--full"],
"ROOT at the root and `--full` on `clean`",
),
(
vec!["cargo-cleanme", "--full", "clean", "--known"],
"`--full` at the root and `--known` on `clean`",
),
(
vec!["cargo-cleanme", "/tmp/x", "clean", "--known"],
"`ROOT` at the root and `--known` on `clean`",
),
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
let Invocation::UsageError(message) = parsed.invocation() else {
panic!(
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
};
assert!(
message.contains(expected),
"{args:?}: the message must name the colliding flags: {message}"
);
}
}
#[test]
fn the_bare_invocation_is_untouched_by_the_consolidation() {
let bare = Cli::try_parse_from(["cargo-cleanme"]).unwrap().invocation();
let alias = Cli::try_parse_from(["cargo-cleanme", "clean"])
.unwrap()
.invocation();
assert_eq!(bare, alias, "`clean` must stay the bare invocation");
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "--known"])
.unwrap()
.invocation(),
bare,
"`clean --known` must stay the bare invocation"
);
let Invocation::Cleanup(request) = bare else {
panic!("the bare invocation must resolve to a cleanup");
};
assert_eq!(request.scope, CleanupScope::Maintenance);
assert_eq!(request.selection, CleanupSelection::WorkingDirectory);
}
#[test]
fn yes_stays_clean_only_and_stays_unbound() {
assert!(
Cli::try_parse_from(["cargo-cleanme", "--yes"]).is_err(),
"the root must not accept `--yes`"
);
let alias = Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/c045-fixture", "--yes"])
.unwrap()
.invocation();
assert_eq!(
alias,
Invocation::Cleanup(cleanup(
CleanupScope::Root(PathBuf::from("/tmp/c045-fixture")),
CleanMode::Execute,
)),
"`--yes` must stay unbound and must not change the mode"
);
}
#[test]
fn a_cleanup_flag_on_a_read_only_subcommand_is_a_usage_error() {
for args in [
vec!["cargo-cleanme", "--full", "scan", "--all"],
vec!["cargo-cleanme", "--full", "config", "path"],
vec!["cargo-cleanme", "--full", "update"],
vec!["cargo-cleanme", "--profile", "release", "scan", "--all"],
vec!["cargo-cleanme", "--older-than", "60", "scan", "--all"],
vec!["cargo-cleanme", "--include", "/a/*", "update"],
vec!["cargo-cleanme", "--cargo-preview", "config", "show"],
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
match parsed.invocation() {
Invocation::UsageError(message) => {
assert!(!message.is_empty(), "{args:?} must say what it refused");
}
other => panic!("{args:?} must be a usage error, got {other:?}"),
}
}
}
#[test]
fn the_same_override_at_both_levels_is_a_usage_error() {
for args in [
vec![
"cargo-cleanme",
"--older-than",
"3600",
"clean",
"--older-than",
"60",
],
vec![
"cargo-cleanme",
"--min-reclaimable-bytes",
"10",
"clean",
"--min-reclaimable-bytes",
"20",
],
vec![
"cargo-cleanme",
"--include",
"/a/*",
"clean",
"--include",
"/b/*",
],
vec!["cargo-cleanme", "--full", "clean", "--full"],
vec![
"cargo-cleanme",
"--cargo-preview",
"clean",
"--cargo-preview",
],
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
assert!(
matches!(parsed.invocation(), Invocation::UsageError(_)),
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
}
}
#[test]
fn a_selector_at_the_root_and_the_other_on_clean_is_a_usage_error() {
for args in [
vec![
"cargo-cleanme",
"--profile",
"release",
"clean",
"--package",
"demo",
],
vec![
"cargo-cleanme",
"--package",
"demo",
"clean",
"--profile",
"release",
],
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
let Invocation::UsageError(message) = parsed.invocation() else {
panic!(
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
};
assert!(
message.contains("--profile") && message.contains("--package"),
"{args:?}: the message must name both selectors: {message}"
);
}
}
#[test]
fn a_scope_conflict_names_the_flags_that_actually_collide() {
for (args, expected) in [
(
vec!["cargo-cleanme", "--full", "clean", "--known"],
"`--full` at the root and `--known` on `clean`",
),
(
vec!["cargo-cleanme", "/tmp/x", "clean", "--known"],
"`ROOT` at the root and `--known` on `clean`",
),
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
let Invocation::UsageError(message) = parsed.invocation() else {
panic!(
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
};
assert!(
message.contains(expected),
"{args:?}: the message must name the colliding flags: {message}"
);
assert!(
!message.contains("was given at the root and on `clean`"),
"{args:?}: `--known` was not given at the root: {message}"
);
}
}
#[test]
fn a_full_scope_at_one_level_and_a_root_at_the_other_is_a_usage_error() {
for (args, expected) in [
(
vec!["cargo-cleanme", "--full", "clean", "/tmp/x"],
"`--full` at the root and ROOT on `clean`",
),
(
vec!["cargo-cleanme", "/tmp/x", "clean", "--full"],
"ROOT at the root and `--full` on `clean`",
),
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
let Invocation::UsageError(message) = parsed.invocation() else {
panic!(
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
};
assert!(
message.contains(expected),
"{args:?}: the message must name the colliding selectors: {message}"
);
}
}
#[test]
fn a_dry_run_at_both_levels_is_a_usage_error() {
for (args, expected) in [
(
vec!["cargo-cleanme", "--dry-run", "clean", "--dry-run"],
"--dry-run",
),
(
vec!["cargo-cleanme", "--dryrun", "clean", "--dryrun"],
"--dryrun",
),
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
let Invocation::UsageError(message) = parsed.invocation() else {
panic!(
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
};
assert!(
message.contains(expected),
"{args:?}: the message must name the spelling that was used: {message}"
);
if expected == "--dryrun" {
assert!(
!message.contains("--dry-run"),
"{args:?}: the message must not name a spelling that was not used: {message}"
);
}
}
}
#[test]
fn a_mixed_dry_run_spelling_names_both_spellings() {
let parsed = Cli::try_parse_from(vec!["cargo-cleanme", "--dryrun", "clean", "--dry-run"])
.unwrap_or_else(|error| panic!("must parse: {error}"));
let Invocation::UsageError(message) = parsed.invocation() else {
panic!("must be a usage error, got {:?}", parsed.invocation());
};
assert!(
message.contains("--dryrun") && message.contains("--dry-run"),
"both spellings must be named: {message}"
);
}
#[test]
fn the_interactive_flag_is_refused_on_the_read_only_subcommands() {
for args in [
vec!["cargo-cleanme", "scan", "--known", "--interactive"],
vec!["cargo-cleanme", "--interactive", "scan", "--known"],
vec!["cargo-cleanme", "config", "show", "--interactive"],
vec!["cargo-cleanme", "update", "--interactive"],
] {
let parsed = Cli::try_parse_from(args.clone())
.unwrap_or_else(|error| panic!("{args:?} must parse: {error}"));
let Invocation::UsageError(message) = parsed.invocation() else {
panic!(
"{args:?} must be a usage error, got {:?}",
parsed.invocation()
);
};
assert!(
message.contains("--interactive"),
"{args:?}: the message must name the refused flag: {message}"
);
}
}
#[test]
fn a_root_level_override_wins_over_the_alias() {
let parsed =
Cli::try_parse_from(["cargo-cleanme", "--older-than", "3600", "clean", "/tmp/p"])
.unwrap();
let Invocation::Cleanup(request) = parsed.invocation() else {
panic!("must resolve to a cleanup");
};
assert_eq!(request.overrides.older_than, Some(3600));
assert_eq!(request.scope, CleanupScope::Root(PathBuf::from("/tmp/p")));
}
#[test]
fn bare_invocation_is_routine_execute_maintenance_not_scan() {
let parsed = Cli::try_parse_from(["cargo-cleanme"]).unwrap();
assert!(parsed.command.is_none());
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(maintenance(CleanMode::Execute))
);
}
#[test]
fn bare_dry_run_is_simulate_and_the_legacy_alias_maps_to_it() {
for args in [
vec!["cargo-cleanme", "--dry-run"],
vec!["cargo-cleanme", "--dryrun"],
] {
let parsed = Cli::try_parse_from(args.clone()).unwrap();
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(maintenance(CleanMode::Simulate)),
"{args:?}"
);
}
assert!(
Cli::try_parse_from(["cargo-cleanme", "--dry-run", "--dryrun"]).is_err(),
"the alias must not be combinable with the canonical spelling"
);
}
#[test]
fn a_dry_run_before_the_subcommand_is_still_a_dry_run() {
for args in [
vec!["cargo-cleanme", "--dry-run", "clean", "/tmp/p"],
vec!["cargo-cleanme", "--dryrun", "clean", "/tmp/p"],
] {
let parsed = Cli::try_parse_from(args.clone()).unwrap();
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Simulate,
)),
"{args:?} must not fall back to Execute"
);
}
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "--dry-run"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Maintenance, CleanMode::Simulate))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/p", "--dry-run"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Simulate,
))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/p"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Execute,
))
);
}
#[test]
fn a_dry_run_before_update_is_still_a_dry_run() {
for args in [
vec!["cargo-cleanme", "--dry-run", "update"],
vec!["cargo-cleanme", "--dryrun", "update"],
] {
assert_eq!(
Cli::try_parse_from(args.clone()).unwrap().invocation(),
Invocation::Update { dry_run: true },
"{args:?} must not replace the binary"
);
}
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "update"])
.unwrap()
.invocation(),
Invocation::Update { dry_run: false }
);
}
#[test]
fn a_root_dry_run_wins_over_cargo_preview_because_it_spawns_nothing() {
assert_eq!(
Cli::try_parse_from([
"cargo-cleanme",
"--dry-run",
"clean",
"/tmp/p",
"--cargo-preview"
])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Simulate,
))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/p", "--cargo-preview"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::CargoPreview,
))
);
}
#[test]
fn scan_scope_selection_is_full_explicit_or_maintenance() {
assert!(
Cli::try_parse_from(["cargo-cleanme", "scan"]).is_err(),
"bare `scan` must require ROOT, --known, or --all"
);
for spelling in [
["cargo-cleanme", "scan", "--all"],
["cargo-cleanme", "scan", "-a"],
["cargo-cleanme", "scan", "--full"],
] {
assert_eq!(
Cli::try_parse_from(spelling).unwrap().invocation(),
Invocation::Scan(ScanIntent::Full),
"{spelling:?} must resolve to Full"
);
}
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"])
.unwrap()
.invocation(),
Invocation::Scan(ScanIntent::Explicit(PathBuf::from("/tmp")))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "scan", "--known"])
.unwrap()
.invocation(),
Invocation::Scan(ScanIntent::Maintenance)
);
}
#[test]
fn the_interactive_flag_is_declared_advertised_and_not_implied() {
use clap::CommandFactory;
let help = Cli::command().render_long_help().to_string();
assert!(
help.contains("-i, --interactive"),
"the flag must be advertised: {help}"
);
assert!(
Cli::try_parse_from(["cargo-cleanme", "-i"])
.unwrap()
.interactive
);
assert!(
Cli::try_parse_from(["cargo-cleanme", "--interactive"])
.unwrap()
.interactive,
"--interactive must be the same flag"
);
assert!(
!Cli::try_parse_from(["cargo-cleanme"]).unwrap().interactive,
"-i must not be implied by an ordinary invocation"
);
match Cli::try_parse_from(["cargo-cleanme", "clean", "--known", "-i"])
.unwrap()
.invocation()
{
Invocation::Cleanup(request) => assert!(
request.interactive,
"the flag must reach the cleanup intent, not just the parser"
),
other => panic!("expected a cleanup intent, got {other:?}"),
}
match Cli::try_parse_from(["cargo-cleanme", "-i"])
.unwrap()
.invocation()
{
Invocation::Cleanup(request) => {
assert_eq!(
request.selection,
CleanupSelection::WorkingDirectory,
"-i must not pre-empt the anchor; the session replaces it"
);
}
other => panic!("expected a cleanup intent, got {other:?}"),
}
}
#[test]
fn interactive_without_a_terminal_still_means_human_format_only() {
for (flag, expected) in [
("human", OutputFormat::Human),
("json", OutputFormat::Json),
("log", OutputFormat::Log),
] {
let cli = Cli::try_parse_from(["cargo-cleanme", "-i", "--format", flag]).unwrap();
assert_eq!(cli.format, expected);
assert!(cli.interactive);
}
}
#[test]
fn maintenance_spellings_anchor_selection_to_the_working_directory() {
for args in [
vec!["cargo-cleanme"],
vec!["cargo-cleanme", "clean"],
vec!["cargo-cleanme", "clean", "--known"],
] {
let Invocation::Cleanup(request) =
Cli::try_parse_from(args.clone()).unwrap().invocation()
else {
panic!("{args:?} must resolve to a cleanup request");
};
assert_eq!(
request.selection,
CleanupSelection::WorkingDirectory,
"{args:?} must anchor its selection to the working directory"
);
}
for args in [
vec!["cargo-cleanme", "clean", "/x"],
vec!["cargo-cleanme", "clean", "--full"],
] {
let Invocation::Cleanup(request) =
Cli::try_parse_from(args.clone()).unwrap().invocation()
else {
panic!("{args:?} must resolve to a cleanup request");
};
assert_eq!(
request.selection,
CleanupSelection::All,
"{args:?} must stay unfiltered"
);
}
}
#[test]
fn unresolved_working_directory_anchor_selects_nothing() {
assert!(
!CleanupSelection::WorkingDirectory.admits(Path::new("/any/workspace")),
"an unresolved anchor must never admit a candidate"
);
}
#[test]
fn scan_scope_conflicts_fail_at_invocation_time() {
for args in [
vec!["cargo-cleanme", "scan", "/tmp", "--known"],
vec!["cargo-cleanme", "scan", "/tmp", "--all"],
vec!["cargo-cleanme", "scan", "/tmp", "--full"],
vec!["cargo-cleanme", "scan", "--known", "--full"],
vec!["cargo-cleanme", "scan", "--known", "--all"],
vec!["cargo-cleanme", "scan", "--all", "--full"],
] {
assert!(
Cli::try_parse_from(args.clone()).is_err(),
"{args:?} must be rejected before any traversal"
);
}
}
#[test]
fn hidden_full_alias_is_not_advertised_in_scan_help() {
let mut command = Cli::command();
let scan = command
.find_subcommand_mut("scan")
.expect("scan subcommand");
let usage = scan.render_usage().to_string();
assert!(
!usage.contains("--full"),
"the scan's --full alias must not be advertised in the usage line: {usage}"
);
let help = scan.render_long_help().to_string();
assert!(
!help.contains("--full"),
"the scan's --full alias must not appear in the help: {help}"
);
let parsed = Cli::try_parse_from(["cargo-cleanme", "scan", "--full"])
.expect("the historical spelling must still parse");
let Some(Command::Scan { all, .. }) = parsed.command else {
panic!("scan --full must be a scan");
};
assert!(all, "the alias must select the full scope");
let all = scan
.get_arguments()
.find(|arg| arg.get_id() == "all")
.expect("the scan --all flag");
assert!(!all.is_hide_set(), "--all must stay advertised");
let known = scan
.get_arguments()
.find(|arg| arg.get_id() == "known")
.expect("the scan --known flag");
assert!(!known.is_hide_set(), "--known must stay advertised");
}
#[test]
fn clean_scope_selectors_stay_mutually_exclusive() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(PathBuf::from("/tmp")),
CleanMode::Execute
))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "--known"])
.unwrap()
.invocation(),
Invocation::Cleanup(maintenance(CleanMode::Execute))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "--full"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Full, CleanMode::Execute))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean"])
.unwrap()
.invocation(),
Cli::try_parse_from(["cargo-cleanme"]).unwrap().invocation()
);
assert!(Cli::try_parse_from(["cargo-cleanme", "clean", "/x", "--known"]).is_err());
assert!(Cli::try_parse_from(["cargo-cleanme", "clean", "--known", "--full"]).is_err());
assert!(Cli::try_parse_from(["cargo-cleanme", "clean", "/x", "--full"]).is_err());
}
#[test]
fn the_full_cleanup_alias_still_resolves_after_the_root_moved() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "--full"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Full, CleanMode::Execute))
);
}
#[test]
fn cleanup_modes_default_to_execute_and_expose_cargo_preview() {
for (args, expected) in [
(vec!["cargo-cleanme", "clean", "/tmp"], CleanMode::Execute),
(
vec!["cargo-cleanme", "clean", "/tmp", "--dry-run"],
CleanMode::Simulate,
),
(
vec!["cargo-cleanme", "clean", "/tmp", "--cargo-preview"],
CleanMode::CargoPreview,
),
(
vec!["cargo-cleanme", "clean", "/tmp", "--yes"],
CleanMode::Execute,
),
(
vec!["cargo-cleanme", "clean", "/tmp", "--dryrun"],
CleanMode::Simulate,
),
] {
let parsed = Cli::try_parse_from(args.clone()).unwrap();
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Root(PathBuf::from("/tmp")), expected)),
"{args:?}"
);
}
for args in [
vec![
"cargo-cleanme",
"clean",
"/tmp",
"--dry-run",
"--cargo-preview",
],
vec!["cargo-cleanme", "clean", "/tmp", "--dry-run", "--yes"],
vec!["cargo-cleanme", "clean", "/tmp", "--cargo-preview", "--yes"],
vec!["cargo-cleanme", "clean", "/tmp", "--dry-run", "--dryrun"],
vec![
"cargo-cleanme",
"clean",
"/tmp",
"--cargo-preview",
"--dryrun",
],
vec!["cargo-cleanme", "clean", "/tmp", "--yes", "--dryrun"],
] {
assert!(Cli::try_parse_from(args.clone()).is_err(), "{args:?}");
}
}
#[test]
fn compatibility_aliases_are_hidden_but_accepted() {
let clean_help = Cli::command()
.find_subcommand_mut("clean")
.expect("clean subcommand")
.render_long_help()
.to_string();
assert!(!clean_help.contains("--yes"), "{clean_help}");
assert!(!clean_help.contains("--dryrun"), "{clean_help}");
assert!(clean_help.contains("--dry-run"), "{clean_help}");
let command = Cli::command();
let clean = command.find_subcommand("clean").expect("clean subcommand");
for flag in [
"root",
"full",
"min_reclaimable_bytes",
"older_than",
"include",
"exclude",
"profile",
"package",
"cargo_preview",
"yes_legacy",
"dryrun_legacy",
] {
let arg = clean
.get_arguments()
.find(|arg| arg.get_id() == flag)
.unwrap_or_else(|| panic!("the clean alias must still carry {flag}"));
assert!(arg.is_hide_set(), "{flag} must be a hidden alias");
}
for flag in ["dry_run", "known"] {
let arg = clean
.get_arguments()
.find(|arg| arg.get_id() == flag)
.unwrap_or_else(|| panic!("the clean alias must still carry {flag}"));
assert!(!arg.is_hide_set(), "{flag} must stay advertised");
}
}
#[test]
fn partitioned_flag_is_gone_scoped_proof_is_the_only_behavior() {
assert!(Cli::try_parse_from(["cargo-cleanme", "--partitioned"]).is_err());
assert!(Cli::try_parse_from(["cargo-cleanme", "clean", "/x", "--partitioned"]).is_err());
assert!(matches!(
Cli::try_parse_from(["cargo-cleanme"]).unwrap().invocation(),
Invocation::Cleanup(_)
));
}
#[test]
fn update_keeps_its_own_dry_run_meaning() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "update", "--dry-run"])
.unwrap()
.invocation(),
Invocation::Update { dry_run: true }
);
}
#[test]
fn format_log_parses_globally() {
for args in [
vec!["cargo-cleanme", "--format", "log"],
vec!["cargo-cleanme", "scan", "--all", "--format", "log"],
vec!["cargo-cleanme", "--format", "log", "scan", "--all"],
vec!["cargo-cleanme", "clean", "/x", "--format", "log"],
vec![
"cargo-cleanme",
"cleanme",
"--format",
"log",
"scan",
"--all",
],
] {
let normalized: Vec<OsString> = args.iter().map(OsString::from).collect();
let parsed = Cli::try_parse_from(normalize_cargo_argv_with(normalized, true)).unwrap();
assert_eq!(parsed.format, OutputFormat::Log, "{args:?}");
}
assert_eq!(
Cli::try_parse_from(["cargo-cleanme"]).unwrap().format,
OutputFormat::Human,
"log is opt-in; a non-TTY stdout must never select it"
);
assert!(Cli::try_parse_from(["cargo-cleanme", "--format", "yaml"]).is_err());
}
#[test]
fn config_command_parses() {
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "path"]).is_ok());
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "edit"]).is_ok());
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "init"]).is_err());
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "config", "show"])
.unwrap()
.invocation(),
Invocation::Config(ConfigCommand::Show)
);
}
#[test]
fn root_parses() {
let c = Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"]).unwrap();
assert_eq!(
c.invocation(),
Invocation::Scan(ScanIntent::Explicit(PathBuf::from("/tmp")))
);
}
#[test]
fn cleanup_policy_options_are_repeatable_and_mode_independent() {
let parsed = Cli::try_parse_from([
"cargo-cleanme",
"clean",
"--known",
"--min-reclaimable-bytes",
"42",
"--older-than",
"60",
"--include",
"**/one",
"--include",
"**/two",
"--exclude",
"**/tmp",
"--dry-run",
])
.unwrap();
let intent = parsed.invocation();
assert!(
matches!(parsed.command, Some(Command::Clean { flags, .. }) if flags.min_reclaimable_bytes == Some(42) && flags.older_than == Some(60) && flags.include.len() == 2 && flags.exclude == ["**/tmp"])
);
assert_eq!(
intent,
Invocation::Cleanup(CleanupRequest {
scope: CleanupScope::Maintenance,
mode: CleanMode::Simulate,
overrides: CleanupOverrides {
min_reclaimable_bytes: Some(42),
older_than: Some(60),
include: vec!["**/one".into(), "**/two".into()],
exclude: vec!["**/tmp".into()],
profile: None,
package: None,
},
selection: CleanupSelection::WorkingDirectory,
interactive: false,
}),
"advanced policy overrides travel with the intent, not beside it"
);
let selected =
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp", "--profile", "custom"]).unwrap();
assert!(
matches!(selected.command, Some(Command::Clean { flags, .. }) if flags.profile.as_deref() == Some("custom"))
);
assert!(
Cli::try_parse_from([
"cargo-cleanme",
"clean",
"/tmp",
"--profile",
"release",
"--package",
"app",
])
.is_err()
);
}
#[test]
fn orchestration_roots_are_mutually_exclusive_and_external_forms_match() {
for mode in ["--known", "--full"] {
let direct =
Cli::try_parse_from(["cargo-cleanme", "clean", mode, "--dry-run"]).unwrap();
let external = Cli::try_parse_normalized_from(argv(&[
"cargo-cleanme",
"cleanme",
"clean",
mode,
"--dry-run",
]))
.unwrap();
assert_eq!(direct.invocation(), external.invocation());
}
}
fn argv(items: &[&str]) -> Vec<OsString> {
items.iter().map(OsString::from).collect()
}
#[test]
fn direct_argv_is_unchanged() {
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme"]), false),
argv(&["cargo-cleanme"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "scan", "/x"]), false),
argv(&["cargo-cleanme", "scan", "/x"])
);
}
#[test]
fn cargo_external_argv_strips_exactly_one_documented_token() {
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme"]), true),
argv(&["cargo-cleanme"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "scan", "/x"]), true),
argv(&["cargo-cleanme", "scan", "/x"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "config", "show"]), true),
argv(&["cargo-cleanme", "config", "show"])
);
assert_eq!(
normalize_cargo_argv_with(
argv(&["cargo-cleanme", "cleanme", "clean", "/x", "--yes"]),
true
),
argv(&["cargo-cleanme", "clean", "/x", "--yes"])
);
}
#[test]
fn later_literal_cleanme_values_are_preserved() {
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "scan", "cleanme"]), true),
argv(&["cargo-cleanme", "scan", "cleanme"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "scan", "cleanme"]), true),
argv(&["cargo-cleanme", "scan", "cleanme"])
);
assert_eq!(
normalize_cargo_argv_with(
argv(&["cargo-cleanme", "clean", "./cleanme", "--yes"]),
true
),
argv(&["cargo-cleanme", "clean", "./cleanme", "--yes"])
);
}
#[test]
fn help_and_version_forms_normalize() {
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "--help"]), true),
argv(&["cargo-cleanme", "--help"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "--version"]), true),
argv(&["cargo-cleanme", "--version"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "clean", "--help"]), true),
argv(&["cargo-cleanme", "clean", "--help"])
);
}
#[test]
fn a_direct_cleanme_root_is_never_stripped() {
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme"]), false),
argv(&["cargo-cleanme", "cleanme"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "--dry-run"]), false),
argv(&["cargo-cleanme", "cleanme", "--dry-run"])
);
assert_eq!(
normalize_cargo_argv_with(argv(&["cargo-cleanme", "cleanme", "scan", "/x"]), false),
argv(&["cargo-cleanme", "cleanme", "scan", "/x"])
);
}
#[test]
fn a_direct_cleanme_root_resolves_to_an_explicit_scope() {
let cli = Cli::try_parse_from(normalize_cargo_argv_with(
argv(&["cargo-cleanme", "cleanme"]),
false,
))
.unwrap();
match cli.invocation() {
Invocation::Cleanup(request) => {
assert_eq!(
request.scope,
CleanupScope::Root(std::path::PathBuf::from("cleanme")),
"a direct `cleanme` must stay the operator's bounded root"
);
}
other => panic!("expected a cleanup request, got {other:?}"),
}
let cargo = Cli::try_parse_from(normalize_cargo_argv_with(
argv(&["cargo-cleanme", "cleanme"]),
true,
))
.unwrap();
match cargo.invocation() {
Invocation::Cleanup(request) => assert_eq!(
request.scope,
CleanupScope::Maintenance,
"the Cargo-injected token is not a scope selector"
),
other => panic!("expected a cleanup request, got {other:?}"),
}
}
#[test]
fn direct_and_external_forms_parse_equivalently() {
for (direct, external) in [
(
argv(&["cargo-cleanme"]),
argv(&["cargo-cleanme", "cleanme"]),
),
(
argv(&["cargo-cleanme", "scan", "/x"]),
argv(&["cargo-cleanme", "cleanme", "scan", "/x"]),
),
(
argv(&["cargo-cleanme", "--dry-run"]),
argv(&["cargo-cleanme", "cleanme", "--dry-run"]),
),
(
argv(&["cargo-cleanme", "scan", "--known"]),
argv(&["cargo-cleanme", "cleanme", "scan", "--known"]),
),
(
argv(&["cargo-cleanme", "config", "path"]),
argv(&["cargo-cleanme", "cleanme", "config", "path"]),
),
(
argv(&["cargo-cleanme", "clean", "/x"]),
argv(&["cargo-cleanme", "cleanme", "clean", "/x"]),
),
] {
let a = Cli::try_parse_from(normalize_cargo_argv_with(direct, false)).unwrap();
let b = Cli::try_parse_from(normalize_cargo_argv_with(external, true)).unwrap();
assert_eq!(
a.invocation(),
b.invocation(),
"direct and external forms must agree"
);
}
}
#[test]
fn config_init_is_removed_and_edit_parses() {
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "init"]).is_err());
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "edit"]).is_ok());
}
#[test]
fn absolute_root_is_stable() {
let absolute = if cfg!(windows) {
PathBuf::from(r"C:\projects")
} else {
PathBuf::from("/projects")
};
assert_eq!(absolutize_root(&absolute).unwrap(), absolute);
}
#[test]
fn relative_root_becomes_absolute() {
let cwd = std::env::current_dir().unwrap();
let joined = absolutize_root(Path::new("./project")).unwrap();
assert!(joined.is_absolute());
assert_eq!(joined, cwd.join("project"));
let dotdot = absolutize_relative(Path::new("/a/b"), Path::new("c/../d"));
assert_eq!(dotdot, PathBuf::from("/a/b/d"));
let up = absolutize_relative(Path::new("/a/b"), Path::new("../outside"));
assert_eq!(up, PathBuf::from("/a/outside"));
let rooted = absolutize_relative(Path::new("/a"), Path::new("../../x"));
assert_eq!(rooted, PathBuf::from("/x"));
}
#[test]
fn no_progress_flag_parses_globally() {
let c = Cli::try_parse_from(["cargo-cleanme", "--no-progress", "scan", "/tmp"]).unwrap();
assert!(c.no_progress);
let c = Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"]).unwrap();
assert!(!c.no_progress);
let c = Cli::try_parse_from(["cargo-cleanme", "--no-progress"]).unwrap();
assert!(c.no_progress);
assert!(matches!(
c.invocation(),
Invocation::Cleanup(CleanupRequest { .. })
));
}
#[test]
fn stats_flag_parses_globally_in_direct_and_external_forms() {
let c = Cli::try_parse_from(["cargo-cleanme", "--stats", "scan", "/tmp"]).unwrap();
assert!(c.stats);
let c = Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"]).unwrap();
assert!(!c.stats);
let c = Cli::try_parse_from(["cargo-cleanme", "--no-progress", "--stats", "scan", "/tmp"])
.unwrap();
assert!(c.no_progress);
assert!(c.stats);
for args in [
vec!["cargo-cleanme", "clean", "/x", "--stats"],
vec!["cargo-cleanme", "clean", "/x", "--dry-run", "--stats"],
vec!["cargo-cleanme", "clean", "/x", "--cargo-preview", "--stats"],
vec!["cargo-cleanme", "clean", "/x", "--yes", "--stats"],
] {
let c = Cli::try_parse_from(args.clone()).unwrap();
assert!(c.stats, "{args:?}");
}
for args in [
vec!["cargo-cleanme", "cleanme", "--stats", "scan", "/x"],
vec!["cargo-cleanme", "cleanme", "clean", "/x", "--stats"],
vec![
"cargo-cleanme",
"cleanme",
"--no-progress",
"--stats",
"scan",
"/x",
],
] {
let normalized: Vec<OsString> = args.iter().map(OsString::from).collect::<Vec<_>>();
let parsed = Cli::try_parse_from(normalize_cargo_argv_with(normalized, true)).unwrap();
assert!(parsed.stats, "{args:?}");
}
}
}