open,main: Improve error handling logic and use ExitCode

This commit is contained in:
George Kaklamanos 2023-11-27 20:51:44 +02:00
parent 30b7e5bfe3
commit 3ef5627a0f
No known key found for this signature in database
GPG key ID: C0CAB8A6BDC9399D
2 changed files with 30 additions and 16 deletions

View file

@ -17,22 +17,24 @@ struct AuthResult {
pub resource: String,
}
fn run_bin(bin: Binary) -> Result<String, ()> {
let mut ret = Err(());
fn run_bin(bin: Binary) -> Result<String, String> {
let mut ret = Err("".to_string());
let mut iter = bin.iter();
let mut cmd = std::process::Command::new(iter.next().unwrap());
cmd.args(iter);
if let Ok(_) = cmd.status() {
let stdout = cmd.output().unwrap().stdout;
let str = std::str::from_utf8(stdout.as_slice()).unwrap().trim();
ret = Ok(String::from(str));
}
let str = std::str::from_utf8(stdout.as_slice())
.unwrap()
.trim()
.to_string();
let st = cmd.status().unwrap();
ret = if st.success() { Ok(str) } else { Err(str) };
ret
}
fn run_auth(args: &OpenArgs, bin: Binary) -> Result<AuthResult, ()> {
let mut ret = Err(());
fn run_auth(args: &OpenArgs, bin: Binary) -> Result<AuthResult, String> {
let mut ret = Err("".to_string());
let mut auth_bin = bin.clone();
auth_bin.push(args.method.clone());
@ -50,17 +52,22 @@ fn run_auth(args: &OpenArgs, bin: Binary) -> Result<AuthResult, ()> {
ret
}
pub fn open(args: OpenArgs) -> Result<(), String> {
let mut ret = Err("Not authorized!".to_string());
pub fn open(args: OpenArgs) -> Result<(), ()> {
let mut msg = "Not authorized!";
let mut ret = Err(());
for (method, binary) in args.auth.iter() {
let output = run_auth(&args, binary.to_vec());
if let Ok(user) = output {
let resource_bin = args.hardware.get(&user.resource).unwrap();
if let Ok(_) = run_bin(resource_bin.to_vec()) {
ret = Err("Hardware failure!".to_string());
msg = "Open sesame!";
ret = Ok(());
} else {
msg = "Hardware failure!";
}
}
}
println!("{}", msg);
ret
}

View file

@ -13,8 +13,11 @@ macro_rules! add_cliargs {
};
}
fn main() -> Result<(), ()> {
let mut ret = Ok(());
use std::process::ExitCode;
fn main() -> ExitCode {
let mut ret = ExitCode::SUCCESS;
let mut module_result: Result<(), ()> = Ok(());
let cli = cli::parse();
let config = config::Config::builder()
.add_source(config::File::with_name(path).required(false))
@ -42,10 +45,14 @@ fn main() -> Result<(), ()> {
cli::Command::Open(cliargs) => {
let config = add_cliargs!(config, "open", cliargs);
let open = config.get::<cli::Open>("open").unwrap().to_config();
labadoor_open::open(open);
module_result = labadoor_open::open(open);
}
#[cfg(feature = "auth")]
cli::Command::Auth(cli) => ret = labadoor_auth::auth(&cli, config),
cli::Command::Auth(cli) => module_result = labadoor_auth::auth(&cli, config),
}
if let Err(_) = module_result {
ret = ExitCode::FAILURE;
}
ret
}