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
//! Logging and progress reporting.

use std::sync::{Arc, Mutex, Weak};

use console::style;
use indicatif::ProgressDrawTarget;
use nom::lib::std::fmt::Display;

use crate::progress::FastProgressBar;
use chrono::Local;

pub struct Log {
    program_name: String,
    progress_bar: Mutex<Weak<FastProgressBar>>,
    pub log_stderr_to_stdout: bool,
    pub no_progress: bool,
}

impl Log {
    pub fn new() -> Log {
        Log {
            progress_bar: Mutex::new(Weak::default()),
            program_name: std::env::current_exe()
                .unwrap()
                .file_name()
                .unwrap()
                .to_string_lossy()
                .to_string(),
            log_stderr_to_stdout: false,
            no_progress: false,
        }
    }

    /// Clears any previous progress bar or spinner and installs a new spinner.
    pub fn spinner(&self, msg: &str) -> Arc<FastProgressBar> {
        if self.no_progress {
            return Arc::new(FastProgressBar::new_hidden());
        }
        self.progress_bar
            .lock()
            .unwrap()
            .upgrade()
            .iter()
            .for_each(|pb| pb.finish_and_clear());
        let result = Arc::new(FastProgressBar::new_spinner(msg));
        *self.progress_bar.lock().unwrap() = Arc::downgrade(&result);
        result
    }

    /// Clears any previous progress bar or spinner and installs a new progress bar.
    pub fn progress_bar(&self, msg: &str, len: u64) -> Arc<FastProgressBar> {
        if self.no_progress {
            return Arc::new(FastProgressBar::new_hidden());
        }
        let result = Arc::new(FastProgressBar::new_progress_bar(msg, len));
        *self.progress_bar.lock().unwrap() = Arc::downgrade(&result);
        result
    }

    /// Creates a no-op progressbar that doesn't display itself.
    pub fn hidden(&self) -> Arc<FastProgressBar> {
        Arc::new(FastProgressBar::new_hidden())
    }

    /// Clears any previous progress bar or spinner and installs a new progress bar.
    pub fn bytes_progress_bar(&self, msg: &str, len: u64) -> Arc<FastProgressBar> {
        if self.no_progress {
            return Arc::new(FastProgressBar::new_hidden());
        }
        self.progress_bar
            .lock()
            .unwrap()
            .upgrade()
            .iter()
            .for_each(|pb| pb.finish_and_clear());
        let result = Arc::new(FastProgressBar::new_bytes_progress_bar(msg, len));
        *self.progress_bar.lock().unwrap() = Arc::downgrade(&result);
        result
    }

    /// Prints a message to stdout.
    /// Does not interfere with progress bar.
    pub fn println<I: Display>(&self, msg: I) {
        match self.progress_bar.lock().unwrap().upgrade() {
            Some(pb) if pb.is_visible() => {
                pb.set_draw_target(ProgressDrawTarget::hidden());
                println!("{}", msg);
                pb.set_draw_target(ProgressDrawTarget::stderr());
            }
            _ => println!("{}", msg),
        }
    }

    /// Prints a message to stderr.
    /// Does not interfere with progress bar.
    pub fn eprintln<I: Display>(&self, msg: I) {
        match self.progress_bar.lock().unwrap().upgrade() {
            Some(pb) if pb.is_visible() => pb.println(format!("{}", msg)),
            _ if self.log_stderr_to_stdout => println!("{}", msg),
            _ => eprintln!("{}", msg),
        }
    }

    const TIMESTAMP_FMT: &'static str = "[%Y-%m-%d %H:%M:%S.%3f]";

    pub fn info<I: Display>(&self, msg: I) {
        let timestamp = Local::now();
        let msg = format!(
            "{} {}: {} {}",
            style(timestamp.format(Self::TIMESTAMP_FMT))
                .for_stderr()
                .dim()
                .white(),
            style(&self.program_name).for_stderr().yellow(),
            style(" info:").for_stderr().green(),
            msg
        );
        self.eprintln(msg);
    }

    pub fn warn<I: Display>(&self, msg: I) {
        let timestamp = Local::now();
        let msg = format!(
            "{} {}: {} {}",
            style(timestamp.format(Self::TIMESTAMP_FMT))
                .for_stderr()
                .dim()
                .white(),
            style(&self.program_name).for_stderr().yellow(),
            style(" warn:").for_stderr().yellow(),
            msg
        );
        self.eprintln(msg);
    }

    pub fn err<I: Display>(&self, msg: I) {
        let timestamp = Local::now();
        let msg = format!(
            "{} {}: {} {}",
            style(timestamp.format(Self::TIMESTAMP_FMT))
                .for_stderr()
                .dim()
                .white(),
            style(&self.program_name).for_stderr().yellow(),
            style("error:").for_stderr().red(),
            msg
        );
        self.eprintln(msg);
    }
}

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