-
Notifications
You must be signed in to change notification settings - Fork 75
/
report.rs
392 lines (317 loc) · 9.55 KB
/
report.rs
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
use indicatif::{ProgressBar, ProgressStyle};
use std::io::{self, Write};
use std::ops::Add;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
//------------------------------------------
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd)]
pub enum LogLevel {
Fatal = 1,
Error,
Warning,
Info,
Debug,
}
impl TryFrom<u8> for LogLevel {
type Error = String;
fn try_from(level: u8) -> Result<LogLevel, <Self as TryFrom<u8>>::Error> {
match level {
0 => Err(String::from("invalid index")),
1 => Ok(LogLevel::Fatal),
2 => Ok(LogLevel::Error),
3 => Ok(LogLevel::Warning),
4 => Ok(LogLevel::Info),
5..=u8::MAX => Ok(LogLevel::Debug),
}
}
}
pub fn verbose_args(cmd: clap::Command) -> clap::Command {
use clap::Arg;
cmd.arg(
Arg::new("VERBOSE")
.help("Increase log verbosity")
.short('v')
.action(clap::ArgAction::Count)
.hide(true),
)
}
pub fn parse_log_level(matches: &clap::ArgMatches) -> Result<LogLevel, String> {
let cnt = matches.get_count("VERBOSE");
if cnt > 0 {
let v: u8 = LogLevel::Warning as u8;
(v + cnt).try_into()
} else {
Ok(LogLevel::Warning)
}
}
//------------------------------------------
#[derive(Clone, PartialEq, Eq)]
pub enum ReportOutcome {
Success,
NonFatal,
Fatal,
}
use ReportOutcome::*;
impl ReportOutcome {
pub fn combine(lhs: &ReportOutcome, rhs: &ReportOutcome) -> ReportOutcome {
match (lhs, rhs) {
(Success, rhs) => rhs.clone(),
(lhs, Success) => lhs.clone(),
(Fatal, _) => Fatal,
(_, Fatal) => Fatal,
(_, _) => NonFatal,
}
}
}
pub struct Report {
outcome: Mutex<ReportOutcome>,
inner: Mutex<Box<dyn ReportInner + Send>>,
}
pub trait ReportInner {
fn set_title(&mut self, txt: &str);
fn set_sub_title(&mut self, txt: &str);
fn set_level(&mut self, level: LogLevel);
fn progress(&mut self, percent: u8);
fn log(&mut self, txt: &str, level: LogLevel);
fn to_stdout(&mut self, txt: &str);
fn complete(&mut self);
fn get_prompt_input(&mut self, prompt: &str) -> io::Result<String>;
}
impl Report {
pub fn new(inner: Box<dyn ReportInner + Send>) -> Report {
Report {
outcome: Mutex::new(Success),
inner: Mutex::new(inner),
}
}
fn update_outcome(&self, rhs: ReportOutcome) {
let mut lhs = self.outcome.lock().unwrap();
*lhs = ReportOutcome::combine(&lhs, &rhs);
}
pub fn set_title(&self, txt: &str) {
let mut inner = self.inner.lock().unwrap();
inner.set_title(txt)
}
pub fn set_sub_title(&self, txt: &str) {
let mut inner = self.inner.lock().unwrap();
inner.set_sub_title(txt)
}
pub fn set_level(&self, level: LogLevel) {
let mut inner = self.inner.lock().unwrap();
inner.set_level(level)
}
pub fn progress(&self, percent: u8) {
let mut inner = self.inner.lock().unwrap();
inner.progress(percent)
}
pub fn info(&self, txt: &str) {
let mut inner = self.inner.lock().unwrap();
inner.log(txt, LogLevel::Info)
}
pub fn debug(&self, txt: &str) {
let mut inner = self.inner.lock().unwrap();
inner.log(txt, LogLevel::Debug)
}
pub fn warning(&self, txt: &str) {
let mut inner = self.inner.lock().unwrap();
inner.log(txt, LogLevel::Warning)
}
pub fn non_fatal(&self, txt: &str) {
self.update_outcome(NonFatal);
let mut inner = self.inner.lock().unwrap();
inner.log(txt, LogLevel::Error)
}
pub fn fatal(&self, txt: &str) {
self.update_outcome(Fatal);
let mut inner = self.inner.lock().unwrap();
inner.log(txt, LogLevel::Fatal)
}
pub fn complete(&self) {
let mut inner = self.inner.lock().unwrap();
inner.complete();
}
pub fn get_outcome(&self) -> ReportOutcome {
let outcome = self.outcome.lock().unwrap();
outcome.clone()
}
// Force a message to be printed to stdout. eg,
// TRANSACTION_ID = <blah>
pub fn to_stdout(&self, txt: &str) {
let mut inner = self.inner.lock().unwrap();
inner.to_stdout(txt)
}
pub fn get_prompt_input(&self, prompt: &str) -> io::Result<String> {
let mut inner = self.inner.lock().unwrap();
inner.get_prompt_input(prompt)
}
}
fn get_prompt_input_(prompt: &str) -> io::Result<String> {
let mut stderr = io::stderr().lock();
stderr.write_all(prompt.as_bytes())?;
stderr.flush()?;
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
Ok(input.trim_end_matches('\n').to_string())
}
//------------------------------------------
#[allow(dead_code)]
struct PBInner {
bar: ProgressBar,
level: LogLevel,
}
impl PBInner {
fn new() -> Self {
let fmt = "{prefix}[{bar:40}] Remaining {eta}{msg}".to_string();
let bar = ProgressBar::new(100);
bar.set_style(
ProgressStyle::default_bar()
.template(&fmt)
.expect("invalid template for the progress bar")
.progress_chars("=> "),
);
Self {
bar,
level: LogLevel::Warning,
}
}
}
impl ReportInner for PBInner {
// Setting title clears subtitle
fn set_title(&mut self, txt: &str) {
let prefix = if !txt.is_empty() {
String::from(txt).add(" ")
} else {
String::new()
};
self.bar.set_prefix(prefix);
self.bar.set_message("");
}
fn set_sub_title(&mut self, txt: &str) {
let msg = if !txt.is_empty() {
String::from(", ").add(txt)
} else {
String::new()
};
self.bar.set_message(msg);
}
fn set_level(&mut self, level: LogLevel) {
self.level = level;
}
fn progress(&mut self, percent: u8) {
self.bar.set_position(percent as u64);
self.bar.tick();
}
fn log(&mut self, txt: &str, level: LogLevel) {
if level <= self.level {
self.bar.println(txt);
}
}
fn to_stdout(&mut self, txt: &str) {
println!("{}", txt);
}
fn complete(&mut self) {
self.bar.finish_and_clear();
}
fn get_prompt_input(&mut self, prompt: &str) -> io::Result<String> {
self.bar.suspend(|| get_prompt_input_(prompt))
}
}
pub fn mk_progress_bar_report() -> Report {
Report::new(Box::new(PBInner::new()))
}
//------------------------------------------
struct SimpleInner {
last_progress: std::time::SystemTime,
level: LogLevel,
}
impl SimpleInner {
fn new() -> SimpleInner {
SimpleInner {
last_progress: std::time::SystemTime::now(),
level: LogLevel::Warning,
}
}
}
impl ReportInner for SimpleInner {
fn set_title(&mut self, txt: &str) {
eprintln!("{}", txt);
}
fn set_sub_title(&mut self, txt: &str) {
eprintln!("{}", txt);
}
fn set_level(&mut self, level: LogLevel) {
self.level = level;
}
fn progress(&mut self, percent: u8) {
let elapsed = self.last_progress.elapsed().unwrap();
if elapsed > std::time::Duration::from_secs(5) {
eprintln!("Progress: {}%", percent);
self.last_progress = std::time::SystemTime::now();
}
}
fn log(&mut self, txt: &str, level: LogLevel) {
if level <= self.level {
eprintln!("{}", txt);
}
}
fn to_stdout(&mut self, txt: &str) {
println!("{}", txt);
}
fn complete(&mut self) {}
fn get_prompt_input(&mut self, prompt: &str) -> io::Result<String> {
get_prompt_input_(prompt)
}
}
pub fn mk_simple_report() -> Report {
Report::new(Box::new(SimpleInner::new()))
}
//------------------------------------------
struct QuietInner {}
impl ReportInner for QuietInner {
fn set_title(&mut self, _txt: &str) {}
fn set_sub_title(&mut self, _txt: &str) {}
fn set_level(&mut self, _level: LogLevel) {}
fn progress(&mut self, _percent: u8) {}
fn log(&mut self, _txt: &str, _level: LogLevel) {}
fn to_stdout(&mut self, _txt: &str) {}
fn complete(&mut self) {}
fn get_prompt_input(&mut self, _prompt: &str) -> io::Result<String> {
Ok(String::new()) // the quiet report doesn't accept inputs
}
}
pub fn mk_quiet_report() -> Report {
Report::new(Box::new(QuietInner {}))
}
//------------------------------------------
pub struct ProgressMonitor {
tid: JoinHandle<()>,
stop_flag: Arc<AtomicBool>,
}
impl ProgressMonitor {
pub fn new<F>(report: Arc<Report>, total: u64, processed: F) -> Self
where
F: Fn() -> u64 + Send + 'static,
{
let stop_flag = Arc::new(AtomicBool::new(false));
let stopped = stop_flag.clone();
let tid = thread::spawn(move || {
let interval = std::time::Duration::from_millis(500);
loop {
if stopped.load(Ordering::Relaxed) {
break;
}
let n = processed() * 100 / total;
report.progress(n as u8);
thread::sleep(interval);
}
});
ProgressMonitor { tid, stop_flag }
}
// Only the owner could stop the Monitor
pub fn stop(self) {
self.stop_flag.store(true, Ordering::Relaxed);
let _ = self.tid.join();
}
}
//------------------------------------------