use std::io;
use std::path::{Path, PathBuf};
use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum};
use crate::catalog::CATALOG;
use crate::config::resolve::Flags;
use crate::error::Result;
use crate::policy::{KeepPolicy, parse_duration, parse_size};
use crate::report::human::HumanOptions;
use crate::report::{RunResult, human, json};
use crate::run::RunOptions;
use crate::watch::WatchOptions;
#[derive(Debug, Parser)]
#[command(name = "voom", version, about, long_about = None, args_conflicts_with_subcommands = true)]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Command>,
#[command(flatten)]
pub prune: PruneArgs,
}
#[derive(Debug, Subcommand)]
pub enum Command {
Catalog,
Config {
#[command(subcommand)]
action: ConfigAction,
},
Watch(WatchArgs),
}
#[derive(Debug, Subcommand)]
pub enum ConfigAction {
Show {
#[arg(value_name = "PATH", default_value = ".")]
path: PathBuf,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Format {
Human,
Json,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Color {
Auto,
Always,
Never,
}
impl From<Color> for anstream::ColorChoice {
fn from(color: Color) -> Self {
match color {
Color::Auto => Self::Auto,
Color::Always => Self::Always,
Color::Never => Self::Never,
}
}
}
#[expect(
clippy::struct_excessive_bools,
reason = "these are command-line flags, which are bools by nature"
)]
#[derive(Debug, Args)]
pub struct PruneArgs {
#[arg(value_name = "PATH", default_value = ".")]
pub paths: Vec<PathBuf>,
#[arg(short = 'n', long, help_heading = "Behaviour")]
pub dry_run: bool,
#[arg(long, help_heading = "Behaviour")]
pub report: bool,
#[arg(long, help_heading = "Behaviour")]
pub exit_code: bool,
#[arg(short, long, help_heading = "Output")]
pub verbose: bool,
#[arg(long, help_heading = "Output")]
pub summary: bool,
#[arg(long, value_enum, default_value_t = Format::Human, help_heading = "Output")]
pub format: Format,
#[arg(long, value_enum, default_value_t = Color::Auto, help_heading = "Output")]
pub color: Color,
#[arg(short = 'j', long, value_name = "N", help_heading = "Behaviour")]
pub jobs: Option<usize>,
#[arg(
long,
value_name = "BOOL",
num_args = 0..=1,
require_equals = true,
default_value_t = true,
default_missing_value = "true",
action = ArgAction::Set,
help_heading = "Safety"
)]
pub one_file_system: bool,
#[arg(long, value_name = "DURATION", help_heading = "Keep policies")]
pub min_age: Option<String>,
#[arg(long, value_name = "SIZE", help_heading = "Keep policies")]
pub min_size: Option<String>,
#[arg(long, value_name = "SIZE", help_heading = "Keep policies")]
pub max_size: Option<String>,
#[arg(short = 'e', long, value_name = "ID", help_heading = "Selection")]
pub ecosystem: Vec<String>,
#[arg(long, value_name = "SPEC", help_heading = "Selection")]
pub enable: Vec<String>,
#[arg(long, value_name = "SPEC", help_heading = "Selection")]
pub disable: Vec<String>,
#[arg(long, value_name = "GLOB", help_heading = "Selection")]
pub exclude: Vec<String>,
#[arg(long, help_heading = "Selection")]
pub caches: bool,
#[arg(long, value_name = "PATH", help_heading = "Selection")]
pub config: Option<PathBuf>,
}
#[derive(Debug, Args)]
pub struct WatchArgs {
#[arg(value_name = "PATH", default_value = ".")]
pub paths: Vec<PathBuf>,
#[arg(long, value_name = "DURATION", default_value = "5s")]
pub debounce: String,
#[arg(long, value_name = "DURATION", default_value = "60s")]
pub quiet_period: String,
}
impl WatchArgs {
pub fn to_run_options(&self, prune: &PruneArgs) -> Result<RunOptions> {
let mut options = prune.to_run_options()?;
options.roots.clone_from(&self.paths);
Ok(options)
}
pub fn to_watch_options(&self) -> Result<WatchOptions> {
Ok(WatchOptions {
debounce: parse_duration(&self.debounce)?,
quiet_period: parse_duration(&self.quiet_period)?,
})
}
}
impl PruneArgs {
pub fn flags(&self) -> Result<Flags> {
Ok(Flags {
ecosystems: (!self.ecosystem.is_empty()).then(|| self.ecosystem.clone()),
enable: self.enable.clone(),
disable: self.disable.clone(),
keep: self.keep()?,
exclude: self.exclude.clone(),
})
}
pub fn keep(&self) -> Result<KeepPolicy> {
Ok(KeepPolicy {
min_age: self.min_age.as_deref().map(parse_duration).transpose()?,
min_size: self.min_size.as_deref().map(parse_size).transpose()?,
max_size: self.max_size.as_deref().map(parse_size).transpose()?,
})
}
pub fn to_run_options(&self) -> Result<RunOptions> {
Ok(RunOptions {
roots: self.paths.clone(),
dry_run: self.dry_run,
jobs: self.jobs,
one_file_system: self.one_file_system,
caches: self.caches,
verbose: self.verbose || self.format == Format::Json,
config: self.config.clone(),
flags: self.flags()?,
progress: self.format == Format::Human && !self.summary,
})
}
}
pub fn render(result: &RunResult, args: &PruneArgs, out: &mut impl io::Write) -> io::Result<()> {
match args.format {
Format::Human => {
let options = HumanOptions {
verbose: args.verbose,
summary_only: args.summary,
};
human::render(result, options, out)
}
Format::Json => json::render(result, out),
}
}
pub fn render_catalog(out: &mut impl io::Write) -> io::Result<()> {
use owo_colors::OwoColorize;
for ecosystem in CATALOG {
writeln!(
out,
"{} {}",
ecosystem.name.bold(),
format_args!("({})", ecosystem.id).dimmed()
)?;
writeln!(out, " markers: {}", ecosystem.markers.join(", "))?;
let anchor = match ecosystem.anchor {
crate::catalog::Anchor::Sibling => "sibling".to_owned(),
crate::catalog::Anchor::Ancestor(levels) => format!("ancestor({levels})"),
};
writeln!(out, " anchor: {anchor}")?;
for artifact in ecosystem.artifacts {
let state = if artifact.default_on { "on " } else { "off" };
write!(
out,
" {state} {:<24} {}.{}",
artifact.path,
ecosystem.id,
artifact.slug()
)?;
match artifact.note {
Some(note) => writeln!(out, "\n {}", note.dimmed())?,
None => writeln!(out)?,
}
}
writeln!(out)?;
}
writeln!(
out,
"{}",
"`off` artifacts need an explicit opt-in: --enable <spec>, or in voom.toml.".dimmed()
)
}
pub fn render_config(root: &Path, args: &PruneArgs, out: &mut impl io::Write) -> Result<()> {
use owo_colors::OwoColorize;
let mut options = args.to_run_options()?;
options.roots = vec![root.to_path_buf()];
let merged = crate::run::resolver_for(root, &options)?.root_config()?;
let write = |out: &mut dyn io::Write| -> io::Result<()> {
writeln!(out, "{}", "sources (ascending precedence)".bold())?;
if merged.sources.is_empty() {
writeln!(out, " (none — built-in defaults only)")?;
}
for source in &merged.sources {
writeln!(out, " {}", source.display())?;
}
writeln!(out, " {}", "command line".dimmed())?;
writeln!(out, "\n{}", "[keep]".bold())?;
write_keep(out, " ", merged.keep())?;
for (ecosystem, keep) in merged.keep_overrides() {
writeln!(out, " [keep.{ecosystem}]")?;
write_keep(out, " ", keep)?;
}
writeln!(out, "\n{}", "exclude".bold())?;
for pattern in &merged.exclude {
writeln!(out, " {pattern}")?;
}
if merged.exclude.is_empty() {
writeln!(out, " (none)")?;
}
writeln!(out, "\n{}", "include".bold())?;
if merged.include.is_empty() {
writeln!(out, " (none)")?;
}
for pattern in &merged.include {
writeln!(out, " {pattern} {}", "swept without a marker".dimmed())?;
}
writeln!(out, "\n{}", "[[paths]]".bold())?;
let mut any = false;
for (pattern, keep, ops) in merged.rules() {
any = true;
writeln!(out, " match = \"{pattern}\"")?;
write_keep(out, " ", keep)?;
for (spec, enabled) in ops {
writeln!(out, " {} {spec}", if *enabled { "enable" } else { "disable" })?;
}
}
if !any {
writeln!(out, " (none)")?;
}
writeln!(out, "\n{}", "artifacts differing from the catalog default".bold())?;
let mut changed = false;
for ecosystem in CATALOG {
for (offset, artifact) in ecosystem.artifacts.iter().enumerate() {
let spec = format!("{}.{}", ecosystem.id, artifact.slug());
let Some(id) = crate::classify::ArtifactId::from_spec(&spec) else {
continue;
};
let _ = offset;
let enabled = merged.selection().is_enabled(id);
if enabled != artifact.default_on {
changed = true;
writeln!(out, " {} {spec}", if enabled { "on " } else { "off" })?;
}
}
}
if !changed {
writeln!(out, " (none)")?;
}
Ok(())
};
write(out).map_err(|error| crate::error::Error::Config {
path: root.to_path_buf(),
reason: error.to_string(),
})
}
fn write_keep(out: &mut dyn io::Write, indent: &str, keep: KeepPolicy) -> io::Result<()> {
if keep.is_empty() {
return writeln!(out, "{indent}(unset)");
}
if let Some(min_age) = keep.min_age {
writeln!(out, "{indent}min_age = {min_age:?}")?;
}
if let Some(min_size) = keep.min_size {
writeln!(out, "{indent}min_size = {min_size}")?;
}
if let Some(max_size) = keep.max_size {
writeln!(out, "{indent}max_size = {max_size}")?;
}
Ok(())
}