use lib::{
cache, cache_exists, get_cfg, help, init, load_from_cache, resolve_cfg_path, Config,
BONNIE_VERSION, DEFAULT_BX_CFG_PATH,
};
use std::env;
use std::io::Write;
use std::path::Path;
fn main() {
let exit_code = real_main();
std::process::exit(exit_code)
}
fn real_main() -> i32 {
let res = core();
match res {
Ok(exit_code) => exit_code,
Err(err) => {
eprintln!("{}", err);
1
}
}
}
fn core() -> Result<i32, String> {
let stdout = &mut std::io::stdout();
let mut prog_args: Vec<String> = env::args().collect();
let _executable_name = prog_args.remove(0);
let cfg_path = resolve_cfg_path(
env::var("BX_CONF").ok().as_deref(),
env::var("BONNIE_CONF").ok().as_deref(),
Path::new(DEFAULT_BX_CFG_PATH).exists(),
);
let mut should_cache = false;
let mut verbose = false;
let mut document = false;
if !prog_args.is_empty() {
if prog_args[0] == "-v" || prog_args[0] == "--version" {
writeln!(stdout, "You are currently running Bonnie v{}! You can see the latest release at https://github.com/arctic-hen7/bonnie/releases.", BONNIE_VERSION).expect("Failed to write version.");
return Ok(0);
} else if prog_args[0] == "-i" || prog_args[0] == "--init" {
init(
match prog_args.get(1).as_ref() {
Some(arg) if &**arg == "-t" || &**arg == "--template" => {
prog_args.get(2).map(|s| s.to_string())
}
_ => None,
},
&cfg_path,
)?;
println!(
"A new Bonnie configuration file has been initialized at {}!",
&cfg_path
);
return Ok(0);
} else if prog_args[0] == "-h" || prog_args[0] == "--help" {
help(stdout);
return Ok(0);
} else if prog_args[0] == "-c" || prog_args[0] == "--cache" {
should_cache = true;
} else if prog_args[0] == "-d" || prog_args[0] == "--debug" {
verbose = true;
prog_args.remove(0);
}
else if prog_args[0] == "help" {
document = true;
}
}
let cfg = if cache_exists()? && !should_cache {
load_from_cache(stdout, None)?
} else {
let cfg_str = get_cfg()?;
Config::new(&cfg_str)?.to_final(BONNIE_VERSION, stdout)?
};
if should_cache {
cache(&cfg, stdout, None)?;
return Ok(0);
}
if document {
let msg = cfg.document(prog_args.get(1).cloned())?;
writeln!(stdout, "{}", msg).expect("Failed to write configuration help.");
return Ok(0);
}
let (command_to_run, command_name, relevant_args) = cfg.get_command_for_args(&prog_args)?;
let bone = command_to_run.prepare(&command_name, &relevant_args, &cfg.default_shell)?;
let exit_code = bone.run(&command_name, verbose, stdout)?;
Ok(exit_code)
}