use std::process::ExitCode;
use bunsen::errors::BunsenResult;
use bunsen_app::{
cache::CacheCommand,
catalog::CatalogCommand,
};
#[cfg(feature = "speech")]
use bunsen_tool::{
asr,
tts,
};
use bunsen_tool::{
chat::ChatCommandGroup,
decide::DecideCommandGroup,
devices::DevicesCommand,
summary::SummaryCommand,
support::did_you_mean,
text::TextCommandGroup,
};
use clap::{
ArgMatches,
CommandFactory,
FromArgMatches,
Parser,
};
#[derive(Parser, Debug)]
#[command(author, version)]
struct Args {
#[clap(subcommand)]
command: Command,
}
#[derive(clap::Subcommand, Debug)]
enum Command {
#[cfg(feature = "speech")]
Asr(asr::AsrCommandGroup),
#[cfg(feature = "speech")]
Tts(tts::TtsCommandGroup),
Chat(Box<ChatCommandGroup>),
Decide(DecideCommandGroup),
Text(TextCommandGroup),
Cache(CacheCommand),
Catalog(CatalogCommand),
Summary(SummaryCommand),
Devices(DevicesCommand),
}
fn main() -> ExitCode {
let matches = Args::command().get_matches();
let args = match Args::from_arg_matches(&matches) {
Ok(args) => args,
Err(error) => error.exit(),
};
match run(&args, &matches) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("Error: {error:?}");
if let Some(hint) = did_you_mean::hint(&error) {
eprintln!("{hint}");
}
ExitCode::FAILURE
}
}
}
fn leaf(matches: &ArgMatches) -> &ArgMatches {
let mut at = matches;
while let Some((_, sub)) = at.subcommand() {
at = sub;
}
at
}
fn run(
args: &Args,
matches: &ArgMatches,
) -> BunsenResult<()> {
bunsen_app::logging::add_target_prefix(env!("CARGO_CRATE_NAME"));
match &args.command {
#[cfg(feature = "speech")]
Command::Asr(cmd) => cmd.run(),
#[cfg(feature = "speech")]
Command::Tts(cmd) => cmd.run(leaf(matches)),
Command::Chat(cmd) => cmd.run(leaf(matches)),
Command::Decide(cmd) => cmd.run(leaf(matches)),
Command::Text(cmd) => cmd.run(),
Command::Cache(cmd) => cmd.run(),
Command::Catalog(cmd) => cmd.run(
matches
.subcommand_matches("catalog")
.expect("the catalog subcommand"),
bunsen::data::catalog::builtin_stack()?,
),
Command::Summary(cmd) => cmd.run(),
Command::Devices(cmd) => cmd.run(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cli_is_well_formed() {
Args::command().debug_assert();
}
#[test]
fn test_decide_parses() {
for argv in [
&[
"bunsen-tool",
"decide",
"run",
"--model",
"laya-multilingual",
"--format",
"json",
"req.yml",
][..],
&["bunsen-tool", "decide", "run"],
&["bunsen-tool", "decide", "list", "--urls"],
&["bunsen-tool", "decide", "fetch", "laya"],
] {
Args::try_parse_from(argv).unwrap_or_else(|e| panic!("{argv:?}: {e}"));
}
}
#[cfg(feature = "speech")]
#[test]
fn test_tts_parses() {
for argv in [
&[
"bunsen-tool",
"tts",
"run",
"--voice",
"Cillian",
"--seed",
"7",
"-o",
"out.wav",
"Hello",
"there.",
][..],
&["bunsen-tool", "tts", "run", "--out", "out.wav"],
&["bunsen-tool", "tts", "list", "--urls"],
&["bunsen-tool", "tts", "voices", "--yes"],
&["bunsen-tool", "tts", "run", "--play", "hi"],
&["bunsen-tool", "tts", "fetch", "zonos3-mini"],
] {
Args::try_parse_from(argv).unwrap_or_else(|e| panic!("{argv:?}: {e}"));
}
}
#[test]
fn test_cache_parses() {
for action in [
&["path"][..],
&["list", "whisper"],
&["clear", "qwen3-asr/fermion", "--yes"],
] {
let mut argv = vec!["bunsen-tool", "cache", "--cache-dir", "/tmp/c"];
argv.extend_from_slice(action);
Args::try_parse_from(argv).unwrap();
}
}
#[test]
fn test_help_summaries_are_short() {
const SUMMARY: usize = 80;
fn walk(
command: &clap::Command,
path: &str,
long: &mut Vec<String>,
) {
let path = format!("{path} {}", command.get_name()).trim().to_string();
let mut check = |what: String, text: String| {
if text.chars().count() > SUMMARY {
long.push(format!("{what} ({}): {text}", text.chars().count()));
}
};
if let Some(about) = command.get_about() {
check(path.clone(), about.to_string());
}
for arg in command.get_arguments() {
if let Some(help) = arg.get_help() {
check(format!("{path} {}", arg.get_id()), help.to_string());
}
}
for sub in command.get_subcommands() {
walk(sub, &path, long);
}
}
let mut long = Vec::new();
walk(&Args::command(), "", &mut long);
long.sort();
long.dedup();
assert!(
long.is_empty(),
"{} long summaries:\n{}",
long.len(),
long.join("\n")
);
}
#[test]
fn test_catalog_runs_through_its_matches() {
let argv = [
"bunsen-tool".to_string(),
"catalog".into(),
"select".into(),
"qwen3".into(),
"--off".into(),
"thinking".into(),
"--desc".into(),
"parameters".into(),
"--limit".into(),
"1".into(),
];
let matches = Args::command().try_get_matches_from(argv).unwrap();
let args = Args::from_arg_matches(&matches).unwrap();
let Command::Catalog(cmd) = &args.command else {
panic!("the catalog command")
};
let mut out = String::new();
cmd.run_into(
matches.subcommand_matches("catalog").unwrap(),
bunsen::data::catalog::builtin_stack().unwrap(),
&mut out,
)
.unwrap();
let results: Vec<&str> = out.lines().filter(|l| l.starts_with("- name:")).collect();
assert_eq!(results, ["- name: qwen/qwen3/qwen3-8b"], "{out}");
}
}