use clap::{Args, Parser, Subcommand};
use autorun::Entry;
use autorun::Scope;
#[derive(Parser, Debug)]
#[command(name = "autorun", version, about, long_about = None)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
}
#[derive(Subcommand, Debug)]
pub enum Command {
List(ListArgs),
Add(AddArgs),
Remove(RemoveArgs),
Check(CheckArgs),
}
#[derive(Args, Debug, Clone)]
pub struct ScopeArg {
#[arg(short, long)]
pub system: bool,
#[arg(short, long, conflicts_with = "system")]
pub all: bool,
}
impl ScopeArg {
pub fn to_scope(&self) -> Option<Scope> {
if self.system {
Some(Scope::Machine)
} else {
Some(Scope::User)
}
}
}
#[derive(Args, Debug)]
pub struct ListArgs {}
#[derive(Args, Debug)]
pub struct AddArgs {
pub name: String,
pub command: String,
#[arg(short, long)]
pub system: bool,
}
#[derive(Args, Debug)]
pub struct RemoveArgs {
pub name: String,
#[arg(short, long)]
pub system: bool,
}
#[derive(Args, Debug)]
pub struct CheckArgs {
pub name: String,
#[arg(short, long)]
pub system: bool,
}
pub fn run(cli: Cli) -> Result<(), autorun::Error> {
match cli.command {
Command::List(args) => cmd_list(args),
Command::Add(args) => cmd_add(args),
Command::Remove(args) => cmd_remove(args),
Command::Check(args) => cmd_check(args),
}
}
fn cmd_list(_args: ListArgs) -> Result<(), autorun::Error> {
let entries = autorun::list()?;
print_entries(&entries);
Ok(())
}
fn cmd_add(args: AddArgs) -> Result<(), autorun::Error> {
let scope = if args.system {
Scope::Machine
} else {
Scope::User
};
autorun::add(&args.name, &args.command, scope)?;
println!("Added startup entry '{}' [{}]", args.name, scope);
Ok(())
}
fn cmd_remove(args: RemoveArgs) -> Result<(), autorun::Error> {
let scope = if args.system {
Scope::Machine
} else {
Scope::User
};
autorun::remove(&args.name, scope)?;
println!("Removed startup entry '{}' [{}]", args.name, scope);
Ok(())
}
fn cmd_check(args: CheckArgs) -> Result<(), autorun::Error> {
let scope = if args.system {
Scope::Machine
} else {
Scope::User
};
let found = autorun::exists(&args.name, scope)?;
if found {
println!("Startup entry '{}' exists [{}]", args.name, scope);
} else {
println!("Startup entry '{}' does not exist [{}]", args.name, scope);
}
Ok(())
}
fn print_entries(entries: &[Entry]) {
if entries.is_empty() {
println!("(none)");
return;
}
let max_name = entries.iter().map(|e| e.name.len()).max().unwrap_or(0);
for entry in entries {
println!(
" [{scope}] {name:<width$} {cmd}",
scope = entry.scope,
name = entry.name,
width = max_name,
cmd = entry.command,
);
}
}
fn main() {
let cli = Cli::parse();
if let Err(e) = run(cli) {
eprintln!("error: {}", e);
std::process::exit(1);
}
}