use std::process::ExitCode;
use clap::{Args, Subcommand};
use crate::config;
#[derive(Args)]
pub struct ContextArgs {
#[command(subcommand)]
pub command: ContextCommands,
}
#[derive(Subcommand)]
pub enum ContextCommands {
List,
Set(SetArgs),
Use(UseArgs),
}
#[derive(Args)]
pub struct SetArgs {
pub name: String,
#[arg(long)]
pub api_url: String,
#[arg(long)]
pub api_key: Option<String>,
}
#[derive(Args)]
pub struct UseArgs {
pub name: String,
}
pub fn dispatch(args: ContextArgs) -> ExitCode {
match args.command {
ContextCommands::List => run_list(),
ContextCommands::Set(set_args) => run_set(set_args),
ContextCommands::Use(use_args) => run_use(use_args),
}
}
fn run_list() -> ExitCode {
let cfg = match config::load() {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
if cfg.contexts.is_empty() {
println!("No contexts configured. Use `aasm context set` to add one.");
return ExitCode::SUCCESS;
}
let default_name = cfg.default_context.as_deref().unwrap_or("");
for (name, ctx) in &cfg.contexts {
let marker = if name == default_name { " *" } else { "" };
let key_status = if ctx.api_key.is_some() { " (key set)" } else { "" };
println!("{name}{marker} {}{key_status}", ctx.api_url);
}
ExitCode::SUCCESS
}
fn run_set(args: SetArgs) -> ExitCode {
let mut cfg = match config::load() {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
cfg.contexts.insert(
args.name.clone(),
config::ContextConfig {
api_url: args.api_url,
api_key: args.api_key,
},
);
if cfg.contexts.len() == 1 {
cfg.default_context = Some(args.name.clone());
}
if let Err(e) = config::save(&cfg) {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
println!("Context '{}' saved.", args.name);
ExitCode::SUCCESS
}
fn run_use(args: UseArgs) -> ExitCode {
let mut cfg = match config::load() {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
if !cfg.contexts.contains_key(&args.name) {
eprintln!("error: context '{}' not found", args.name);
eprintln!("Available contexts:");
for name in cfg.contexts.keys() {
eprintln!(" {name}");
}
return ExitCode::FAILURE;
}
cfg.default_context = Some(args.name.clone());
if let Err(e) = config::save(&cfg) {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
println!("Switched to context '{}'.", args.name);
ExitCode::SUCCESS
}