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
use std::io;
use std::io::Write;
use std::process::ExitCode;

#[derive(Debug)]
pub enum OutputType {
    Stdout,
    Stderr,
}

#[derive(Debug)]
pub struct Output {
    pub stdout: OutputStream,
    pub stderr: OutputStream,
    pub status: ExitCode,
}

impl Output {
    pub fn new() -> Self {
        Self {
            stdout: OutputStream::new(OutputType::Stdout),
            stderr: OutputStream::new(OutputType::Stderr),
            status: ExitCode::from(0),
        }
    }

    #[cfg(test)]
    pub fn tracked() -> Self {
        let mut output = Self::new();
        output.stdout.track = true;
        output.stderr.track = true;

        output
    }
}

impl Default for Output {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug)]
pub struct OutputStream {
    pub content: String,
    pub output_type: OutputType,
    pub track: bool,
}

impl OutputStream {
    pub fn new(output_type: OutputType) -> Self {
        Self {
            content: Default::default(),
            track: false,
            output_type,
        }
    }
    pub fn write(&mut self, content: String) {
        if self.track {
            self.content.push_str(&content);
        } else {
            let _ = match self.output_type {
                OutputType::Stdout => io::stdout().write(content.as_bytes()),
                OutputType::Stderr => io::stderr().write(content.as_bytes()),
            };
        }
    }

    pub fn writeln(&mut self, content: String) {
        self.write(format!("{content}\n"));
    }
}

#[macro_export]
macro_rules! rtxprintln {
    () => {
        rtxprint!("\n")
    };
    ($out:ident, $($arg:tt)*) => {{
        $out.stdout.writeln(format!($($arg)*));
    }};
}

#[macro_export]
macro_rules! rtxprint {
    ($out:ident, $($arg:tt)*) => {{
        $out.stdout.write(format!($($arg)*));
    }};
}

#[macro_export]
macro_rules! rtxstatusln {
    ($out:ident, $($arg:tt)*) => {{
        let rtx = console::style("rtx ").dim().for_stderr();
        $out.stderr.writeln(format!("{}{}", rtx, format!($($arg)*)));
    }};
}