1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use serde::Serialize;
use std::io::{self, Write};
use std::ops::{ControlFlow, FromResidual, Try};

#[derive(Serialize)]
struct CheckJson {
    output: String,
    error: Option<String>,
    remedy: Option<String>,
}

enum CheckResultFormat {
    Json,
    Stdio,
}

impl CheckResultFormat {
    fn from_env() -> Self {
        let format = std::env::var("MEDIC_OUTPUT_FORMAT").unwrap_or("json".to_owned());
        match format.as_str() {
            "stdio" => Self::Stdio,
            _ => Self::Json,
        }
    }

    fn print(
        self,
        msg: String,
        stdout: Option<String>,
        stderr: Option<String>,
        remedy: Option<String>,
    ) {
        match self {
            CheckResultFormat::Stdio => {
                eprintln!("\x1b[31;1mError:\x1b[0m {msg}\r\n");
                if let Some(stdout) = stdout {
                    if !stdout.is_empty() {
                        eprintln!("\x1b[31;1mstdout:\x1b[0m\r\n{stdout}");
                    }
                }
                if let Some(stderr) = stderr {
                    if !stderr.is_empty() {
                        eprintln!("\x1b[31;1mstderr:\x1b[0m\r\n{stderr}");
                    }
                }
                io::stderr().flush().unwrap();
                if let Some(remedy) = remedy {
                    println!("{remedy}");
                }
            }
            CheckResultFormat::Json => {
                let mut output = format!("\x1b[31;1mError: \x1b[0m {msg}");
                let mut error = None;

                if let Some(stdout) = stdout {
                    if !stdout.is_empty() {
                        output.push_str(&format!("\r\n\r\n\x1b[31;1mstdout:\x1b[0m\r\n{stdout}"));
                    }
                }
                if let Some(stderr) = stderr {
                    if !stderr.is_empty() {
                        error = Some(format!("\x1b[31;1mstdout:\x1b[0m\r\n{stderr}"));
                    }
                }

                let json = CheckJson {
                    output,
                    error,
                    remedy,
                };

                println!("{}", serde_json::to_string(&json).unwrap());
            }
        }
    }
}

#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub enum CheckResult {
    #[default]
    CheckOk,
    CheckError(String, Option<String>, Option<String>, Option<String>),
}

impl std::process::Termination for CheckResult {
    fn report(self) -> std::process::ExitCode {
        match self {
            CheckResult::CheckOk => std::process::ExitCode::from(0),
            CheckResult::CheckError(msg, stdout, stderr, remedy) => {
                CheckResultFormat::from_env().print(msg, stdout, stderr, remedy);
                std::process::ExitCode::from(1)
            }
        }
    }
}

pub struct ResultCodeResidual(String, Option<String>, Option<String>, Option<String>);

impl Try for CheckResult {
    type Output = ();
    type Residual = ResultCodeResidual;

    fn branch(self) -> ControlFlow<Self::Residual> {
        match self {
            CheckResult::CheckError(msg, stdout, stderr, remedy) => {
                ControlFlow::Break(ResultCodeResidual(msg, stdout, stderr, remedy))
            }
            CheckResult::CheckOk => ControlFlow::Continue(()),
        }
    }
    fn from_output((): ()) -> Self {
        CheckResult::CheckOk
    }
}

impl FromResidual for CheckResult {
    fn from_residual(r: ResultCodeResidual) -> Self {
        Self::CheckError(r.0, r.1, r.2, r.3)
    }
}