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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! Xvc logging and output crate to be used in output channels.
//! Xvc uses to discriminate outputs of various types, (Info, Debug, Error...) and can use
//! `crossbeam_channel` to send these separately.
//! Downstream crates (xvc, xvc-file, etc.) use this crate not to use stdout, stderr directly.
#![warn(missing_docs)]
#![forbid(unsafe_code)]
use crossbeam_channel::Sender;
use log::LevelFilter;
use std::env;
use std::fmt::Display;
use std::path::Path;
use std::sync::Once;

/// Debugging macro to print the given expression and its value, with the module, function and line number
#[macro_export]
macro_rules! watch {
    ( $( $x:expr ),* ) => {
        {
            $(
               ::log::trace!("{}: {}", stringify!($x), format!("{:#?}", $x).replace("\\n", "\n"));
            )*
        }
    };
}

/// Either send a [XvcOutputLine::Error] value to the given channel, or log via `log` crate
#[macro_export]
macro_rules! error {
    ($fmt:literal $(, $x:expr )* ) => {
        {
            ::log::error!($fmt $(,$x)*);
        }
    };
    ( $channel:expr, $fmt:literal $(, $x:expr )* ) => {
        {
            (&$channel).send(Some(::xvc_logging::XvcOutputLine::Error(format!($fmt $(, $x)*)))).unwrap();
        }
    };
}

/// Either send [XvcOutputLine::Info] to the given channel, or log via `log` crate
#[macro_export]
macro_rules! info {
    ($fmt:literal $(, $x:expr )* ) => {
        {
            ::log::info!($fmt $(, $x)*);
        }
    };
    ( $channel:expr, $fmt:literal $(, $x:expr )* ) => {
        {
            (&$channel).send(Some(::xvc_logging::XvcOutputLine::Info(format!($fmt $(,$x)*)))).unwrap();
        }
    };
}

/// Either send [XvcOutputLine::Warn] to the given channel, or log via `log` crate
#[macro_export]
macro_rules! warn {
    ($fmt:literal $(, $x:expr )* ) => {
        {
            ::log::warn!($fmt $(, $x)*);
        }
    };
    ( $channel:expr, $fmt:literal $(, $x:expr )* ) => {
        {
            (&$channel).send(
                Some(
                    ::xvc_logging::XvcOutputLine::Warn(
                        format!($fmt $(, $x)*)))).unwrap();
        }
    };
}

/// Either send [XvcOutputLine::Debug] to the given channel, or log via `log` crate
#[macro_export]
macro_rules! debug {
    ($fmt:literal $(, $x:expr )* ) => {
        {
            ::log::debug!($fmt $(, $x)*);
        }
    };
    ( $channel:expr, $fmt:literal $(, $x:expr )* ) => {
        {
                    (&$channel).send(Some(::xvc_logging::XvcOutputLine::Debug(format!($fmt $(, $x)*)))).unwrap();
        }
    };
}

/// Either send [XvcOutputLine::Trace] to the given channel, or log via `log` crate
#[macro_export]
macro_rules! trace {
    ($fmt:literal $(, $x:expr )* ) => {
        {
            ::log::trace!($fmt $(, $x)*);
        }
    };
    ( $channel:expr, $fmt:literal $(, $x:expr ),* ) => {
        {
            (&$channel).send(Some(::xvc_logging::XvcOutputLine::Trace(format!("{} [{}::{}]", format!($fmt $(, $x)*), file!(), line!())))).unwrap();
        }
    };
}

/// Either send [XvcOutputLine::Output] to the given channel, or print to stdout
#[macro_export]
macro_rules! output {
    ($fmt:literal $(, $x:expr )* ) => {
        {
            ::std::println!($fmt $(, $x)*);
        }
    };
    ( $channel:expr, $fmt:literal $(, $x:expr )* ) => {
        {
            (&$channel).send(Some(::xvc_logging::XvcOutputLine::Output(format!($fmt $(, $x)*)))).unwrap();
        }
    };
}

/// Either send [XvcOutputLine::Panic] to the given channel, or print to stdout
#[macro_export]
macro_rules! panic {
    ($fmt:literal $(, $x:expr )* ) => {
        {
            watch!($fmt $(, $x)*);
            ::std::panic!($fmt $(, $x)*);
        }
    };
    ( $channel:expr, $fmt:literal $(, $x:expr )* ) => {
        {
            (&$channel).send(Some(::xvc_logging::XvcOutputLine::Panic(format!("{} [{}::{}]",
                                                                 format!($fmt $(, $x)*), file!(), line!())))).unwrap();
            ::std::panic!($fmt $(, $x)*);
        }
    };
}

/// Either send [XvcOutputLine::Tick] to the given channel, or print dots to stdout
#[macro_export]
macro_rules! tick {
    ( $channel:ident, $n:literal) => {{
        (&$channel)
            .send(Some(::xvc_logging::XvcOutputLine::Tick($n)))
            .unwrap();
    }};
    ($n:literal) => {{
        for _ in 0..$n {
            ::std::print!(".");
        }
    }};
}

/// Unwrap the result of an expression, and if it is an error, send it to the given channel
/// and panic.
/// This is mostly to be used in `for_each` blocks, where the error is not propagated.
#[macro_export]
macro_rules! uwr {
    ( $e:expr, $channel:expr ) => {{
        match $e {
            Ok(v) => v,
            Err(e) => {
                (&$channel)
                    .send(Some(::xvc_logging::XvcOutputLine::Panic(format!(
                        "{:?}, [{}::{}]",
                        e,
                        file!(),
                        line!()
                    ))))
                    .unwrap();
                ::std::panic!("{:?}", e);
            }
        }
    }};
}

/// Unwrap an option, and if it is an error, send it to the given channel
/// and panic.
/// This is mostly to be used in `for_each` blocks, where the error is not propagated.
#[macro_export]
macro_rules! uwo {
    ( $e:expr, $channel:expr ) => {{
        match $e {
            Some(v) => v,
            None => {
                watch!($e);
                let msg = format!(
                    "None from the expression: {} [{}::{}]",
                    stringify!($e),
                    file!(),
                    line!()
                );
                (&$channel)
                    .send(Some(::xvc_logging::XvcOutputLine::Panic(msg.clone())))
                    .unwrap();
                ::std::panic!("{}", msg);
            }
        }
    }};
}

/// Logging Initializer
static INIT: Once = Once::new();

/// Init logging if it's not initialized before.
/// Uses [Once] to run (non-public fn) `init_logging` once.
pub fn setup_logging(term_level: Option<LevelFilter>, file_level: Option<LevelFilter>) {
    INIT.call_once(|| init_logging(term_level, file_level));
}

fn init_logging(term_level: Option<LevelFilter>, file_level: Option<LevelFilter>) {
    let logfilename = &format!("{}/xvc.log", env::temp_dir().to_string_lossy(),);

    let logfile = Path::new(&logfilename);

    let mut dispatch = fern::Dispatch::new().format(|out, message, record| {
        out.finish(format_args!(
            "[{}][{}::{}] {}",
            record.level(),
            record.file().get_or_insert("None"),
            record.line().get_or_insert(0),
            message
        ))
    });

    if let Some(level) = term_level {
        dispatch = dispatch.level(level).chain(std::io::stderr());
    }

    if let Some(level) = file_level {
        dispatch = dispatch
            .level(level)
            .chain(fern::log_file(logfilename).expect("Cannot set log filename"));
    }

    match dispatch.apply() {
        Ok(_) => {
            if let Some(level) = term_level {
                debug!("Terminal logger enabled with level: {:?}", level);
            };
            if let Some(level) = file_level {
                debug!(
                    "File logger enabled with level: {:?} to {:?}",
                    level, logfile
                );
            };
        }
        Err(err) => {
            error!("Error enabling logger: {:?}", err);
        }
    };
}

/// Different channels of outputs Xvc can print
#[derive(Clone, Debug)]
pub enum XvcOutputLine {
    /// The output that we should be reporting to user
    Output(String),
    /// For informational messages
    Info(String),
    /// For debug output to show the internals of Xvc
    Debug(String),
    /// Warnings that are against some usual workflows
    Warn(String),
    /// Errors that interrupts a workflow but may be recoverable
    Error(String),
    /// Panics that interrupts the workflow and ends the program
    /// Note that this doesn't call panic! automatically
    Panic(String),
    /// Progress bar ticks.
    /// Self::Info is also used for Tick(1)
    Tick(usize),
}

/// The channel type to send and receive output/log/debug messages
pub type XvcOutputSender = Sender<Option<XvcOutputLine>>;

impl XvcOutputLine {
    /// print [INFO] `s`
    pub fn info(s: &str) -> Self {
        Self::Info(s.to_string())
    }
    /// print [DEBUG]
    pub fn debug(s: &str) -> Self {
        Self::Debug(s.to_string())
    }
    /// print [WARN] `s`
    pub fn warn(s: &str) -> Self {
        Self::Warn(s.to_string())
    }

    /// print [ERROR] `s`
    pub fn error(s: &str) -> Self {
        Self::Error(s.to_string())
    }

    /// print [PANIC] `s`
    ///
    /// Does not panic. Developer should call `panic!` macro separately.
    pub fn panic(s: &str) -> Self {
        Self::Panic(s.to_string())
    }

    /// Increment in progress bar
    pub fn tick(n: usize) -> Self {
        Self::Tick(n)
    }
}

impl From<&str> for XvcOutputLine {
    fn from(s: &str) -> Self {
        Self::Output(s.to_string())
    }
}

impl From<String> for XvcOutputLine {
    fn from(s: String) -> Self {
        Self::Output(s)
    }
}

impl Display for XvcOutputLine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            XvcOutputLine::Output(s) => writeln!(f, "{}", s),
            XvcOutputLine::Info(s) => writeln!(f, "[INFO] {}", s),
            XvcOutputLine::Debug(s) => writeln!(f, "[DEBUG] {}", s),
            XvcOutputLine::Warn(s) => writeln!(f, "[WARN] {}", s),
            XvcOutputLine::Error(s) => writeln!(f, "[ERROR] {}", s),
            XvcOutputLine::Panic(s) => writeln!(f, "[PANIC] {}", s),
            XvcOutputLine::Tick(n) => write!(f, "{}", ".".repeat(*n)),
        }
    }
}