command : implémentation de mes propres ExitCodes

This commit is contained in:
Ahurac 2024-04-09 19:22:40 +02:00
parent 2bf03f0662
commit 1de0e1674e

View file

@ -1,7 +1,15 @@
use std::process::ExitStatus; pub struct ExitCode {
exit_code: u8,
}
pub trait Command { pub trait Command {
fn spawn(&self) -> ExitStatus; fn spawn(&self) -> ExitCode;
}
impl ExitCode {
fn new(exit_code: u8) -> Self {
Self { exit_code }
}
} }
pub struct UnixProgram { pub struct UnixProgram {
@ -20,14 +28,34 @@ impl UnixProgram {
} }
impl Command for UnixProgram { impl Command for UnixProgram {
fn spawn(&self) -> ExitStatus { fn spawn(&self) -> ExitCode {
let mut argv = self.argv.clone(); let mut argv = self.argv.clone();
let program = argv.remove(0); let program = argv.remove(0);
let mut command = std::process::Command::new(program); let mut command = std::process::Command::new(program);
command.args(argv); command.args(argv);
let mut handle = command.spawn().expect("error spawning the command"); let handle = command.spawn();
handle.wait().expect("error waiting for the child")
if handle.is_ok() {
let exit_code = match handle
.unwrap()
.wait()
.expect("error waiting for the child")
.code()
{
Some(code) => code,
None => 1,
};
let exit_code = match u8::try_from(exit_code) {
Ok(code) => ExitCode::new(code),
Err(_e) => ExitCode::new(255),
};
exit_code
} else {
ExitCode::new(127)
}
} }
} }