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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
use crate::toml::{ensure_section, write_document};
use crate::{
    colors::{BLUE, RED, 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 show(mut self, value: bool) -> Self {
        self.show = value;
        self
    }

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

    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();

        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]) -> String {
        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) -> String {
        let message_content = message.as_bytes();
        if self.quiet {
            String::new()
        } else {
            self.err.write_all(message_content).ok();
            message.to_string()
        }
    }

    pub fn notify_error(&mut self, code: ErrorCode, message: &[ANSIString]) -> String {
        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);
        }
    }

    pub fn create_file(&mut self, file: &Path) -> Result<(), String> {
        if let Some(parent) = file.parent() {
            let created = if self.show {
                true
            } else {
                std::fs::create_dir_all(parent).is_ok()
            };

            if !created {
                return Err(self.notify_error(
                    ErrorCode::WriteError,
                    &[
                        RED.paint("Couldn't create "),
                        YELLOW.paint(parent.to_string_lossy()),
                    ],
                ));
            }
        }

        if file.is_file() {
            return Err(self.notify_error(
                ErrorCode::WriteError,
                &[
                    RED.bold().paint("File already exists at "),
                    YELLOW.paint(file.to_string_lossy()),
                ],
            ));
        }

        let created = if self.show {
            true
        } else {
            std::fs::File::create(file).is_ok()
        };

        if !created {
            return Err(self.notify_error(
                ErrorCode::WriteError,
                &[
                    RED.bold().paint("Couldn't create "),
                    YELLOW.paint(file.to_string_lossy()),
                ],
            ));
        }

        self.notify(&[
            BLUE.bold().paint("Created "),
            YELLOW.paint(file.to_string_lossy()),
        ]);
        Ok(())
    }

    pub fn move_file(&mut self, source: &Path, dest: &Path, copy: bool) -> Result<(), String> {
        let moved = if self.show {
            true
        } else {
            let result = if copy {
                std::fs::copy(source, dest).map(|_| ())
            } else {
                std::fs::rename(source, dest)
            };
            result.is_ok()
        };

        if moved {
            let message = &[
                BLUE.paint("Moved "),
                YELLOW.paint(source.to_string_lossy()),
                BLUE.paint(" to "),
                YELLOW.paint(dest.to_string_lossy()),
            ];
            self.notify(message);
            Ok(())
        } else {
            let message = &[
                RED.paint("Failed to move "),
                YELLOW.paint(source.to_string_lossy()),
                RED.paint(" to "),
                YELLOW.paint(dest.to_string_lossy()),
            ];
            Err(self.notify_error(ErrorCode::WriteError, message))
        }
    }
}

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