Skip to main content

medic_lib/step_result/
mod.rs

1// @related [test](medic-lib/src/step_result/step_result_test.rs)
2
3#[cfg(test)]
4mod step_result_test;
5
6use std::io::{self, Write};
7use std::ops::{ControlFlow, FromResidual, Try};
8
9pub enum StepResult {
10  StepOk,
11  StepError(String, Option<String>, Option<String>),
12}
13
14impl std::process::Termination for StepResult {
15  fn report(self) -> std::process::ExitCode {
16    match self {
17      StepResult::StepOk => std::process::ExitCode::from(0),
18      StepResult::StepError(msg, stdout, stderr) => {
19        eprintln!("\x1b[31;1mError:\x1b[0m {msg}\r\n");
20        if let Some(stdout) = stdout
21          && !stdout.is_empty()
22        {
23          eprintln!("\x1b[31;1mstdout:\x1b[0m\r\n{stdout}");
24        }
25        if let Some(stderr) = stderr
26          && !stderr.is_empty()
27        {
28          eprintln!("\x1b[31;1mstderr:\x1b[0m\r\n{stderr}");
29        }
30        io::stderr().flush().unwrap();
31
32        std::process::ExitCode::from(1)
33      }
34    }
35  }
36}
37
38pub struct ResultCodeResidual(String, Option<String>, Option<String>);
39
40impl Try for StepResult {
41  type Output = ();
42  type Residual = ResultCodeResidual;
43
44  fn branch(self) -> ControlFlow<Self::Residual> {
45    match self {
46      StepResult::StepError(msg, stdout, stderr) => ControlFlow::Break(ResultCodeResidual(msg, stdout, stderr)),
47      StepResult::StepOk => ControlFlow::Continue(()),
48    }
49  }
50  fn from_output((): ()) -> Self {
51    StepResult::StepOk
52  }
53}
54
55impl FromResidual for StepResult {
56  fn from_residual(r: ResultCodeResidual) -> Self {
57    Self::StepError(r.0, r.1, r.2)
58  }
59}
60
61impl std::ops::Residual<()> for ResultCodeResidual {
62  type TryType = StepResult;
63}