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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use crate::toml::{ensure_section, write_document};
use crate::{
    colors::{BLUE, TABLE_BLUE, TABLE_YELLOW, YELLOW},
    toml::unwrap_toml_value,
};
use anyhow::Result;
use comfy_table::{Attribute, Cell, ContentArrangement, Row, Table};
use std::{fmt::Display, io::Write, ops::Deref, path::Path};
use toml_edit::{Document, Item};

use ansi_term::{ANSIString, ANSIStrings};

pub struct Output {
    out: Box<dyn Write>,
    err: Box<dyn Write>,
    color: bool,
    quiet: bool,
    verbose: bool,
    show: bool,
    code: Option<ErrorCode>,
}

impl std::fmt::Debug for Output {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Output")
            .field("color", &self.color)
            .field("quiet", &self.code)
            .field("verbose", &self.code)
            .field("show", &self.code)
            .field("code", &self.code)
            .finish()
    }
}

impl Output {
    pub fn new(out: Box<dyn Write>, err: Box<dyn Write>) -> Self {
        Self {
            out,
            err,
            color: false,
            quiet: false,
            verbose: false,
            show: false,
            code: None,
        }
    }

    pub fn quiet(mut self, value: bool) -> Self {
        self.set_quiet(value);
        self
    }

    pub fn set_quiet(&mut self, value: bool) {
        self.quiet = value;
    }

    pub fn verbose(mut self, value: bool) -> Self {
        self.set_verbose(value);
        self
    }

    pub fn set_verbose(&mut self, value: bool) {
        self.verbose = value;
    }

    pub fn color(mut self, value: bool) -> Self {
        self.color = value;
        self
    }

    pub fn only_show(mut self, value: bool) -> Self {
        self.show = value;
        self
    }

    fn format(&self, output: impl Display) -> String {
        let mut result = format!("{}", output);
        if !result.is_empty() {
            result.push('\n');
        }
        result
    }

    pub fn format_table(
        &self,
        headers: &[&str],
        data: Vec<Vec<&str>>,
        preset: Option<&str>,
    ) -> String {
        let mut table = Table::new();
        table.set_content_arrangement(ContentArrangement::Dynamic);
        if let Some(preset) = preset {
            table.load_preset(preset);
        } else {
            table.load_preset("││──╞═╪╡│    ┬┴┌┐└┘");
        }
        table.set_header(headers);
        table.enforce_styling();

        let (width, _) = crossterm::terminal::size().unwrap_or((100, 0));
        table.set_table_width(width);

        for data_row in data {
            let mut row = Row::new();
            for (i, data_cell) in data_row.iter().enumerate() {
                let mut cell = Cell::new(data_cell);

                if self.color {
                    if i == 0 {
                        cell = cell.add_attribute(Attribute::Bold).fg(TABLE_BLUE);
                    } else {
                        cell = cell.fg(TABLE_YELLOW);
                    }
                }
                row.add_cell(cell);
            }
            table.add_row(row);
        }

        self.format(table)
    }

    pub fn output(&mut self, output: impl Display) -> bool {
        let data = self.format(output);

        let stream = if self.show {
            &mut self.err
        } else {
            &mut self.out
        };
        let result = stream.write_all(data.as_bytes()).is_ok();

        if self.verbose {
            self.err
                .write_all(data.as_bytes())
                .expect("Couldn't write verbose output");
        }
        result
    }

    pub fn notify(&mut self, message: &[ANSIString]) -> bool {
        let message = if self.color {
            self.format(ANSIStrings(message))
        } else {
            self.format(
                message
                    .iter()
                    .map(|f| f.deref())
                    .collect::<Vec<&str>>()
                    .join(""),
            )
        };

        self.notify_str(&message)
    }

    pub fn notify_str(&mut self, message: &str) -> bool {
        if !self.quiet {
            self.err.write_all(message.as_bytes()).is_ok()
        } else {
            true
        }
    }

    pub fn notify_error(&mut self, code: ErrorCode, message: &[ANSIString]) -> bool {
        self.code = Some(code);
        self.notify(message)
    }

    pub fn error_code(&self) -> Option<i32> {
        self.code.clone().map(|c| c as i32)
    }

    pub fn flush(&mut self) -> Result<()> {
        self.out.flush()?;
        self.err.flush()?;
        Ok(())
    }

    pub fn write_toml<I, T>(
        &mut self,
        file: &Path,
        document: &mut Document,
        heading: &str,
        values: I,
    ) where
        I: IntoIterator<Item = (T, Item)>,
        T: AsRef<str>,
    {
        for (name, value) in values.into_iter() {
            self.notify(&[
                "Setting ".into(),
                BLUE.bold().paint(name.as_ref()),
                " = ".into(),
                YELLOW.paint(unwrap_toml_value(value.as_value().unwrap())),
            ]);

            if !self.show {
                let section = ensure_section(document, heading);
                section[name.as_ref()] = value;
            }
        }

        if !self.show {
            write_document(file, document, self);
        }
    }
}

#[derive(Debug, Clone)]
pub enum ErrorCode {
    WriteError = 1,
    ParseError = 2,
}