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
use chrono::{DateTime, Local};
#[derive(Clone, Copy, PartialEq)]
pub enum OutputFormat {
Csv,
Human(NoiseLevel),
Json,
JsonCompact,
Silent,
Tsv,
}
#[derive(Clone, Copy, PartialEq)]
pub enum NoiseLevel {
Verbose,
Normal,
Quiet,
}
pub enum StrOrDt<'a> {
Str(&'a str),
Dt(DateTime<Local>),
}
impl OutputFormat {
pub fn format_time(&self, dt: DateTime<Local>) -> String {
dt.to_rfc2822()
}
pub fn log(&self, labels: Vec<&str>, values: Vec<Vec<&str>>) {
if let OutputFormat::Silent = self {
return;
}
let joining = |sep: &str| {
let sep = sep.to_string();
move |tokens: Vec<&str>| tokens.join(&sep)
};
match &self {
OutputFormat::Csv => {
let csv = joining(",");
println!("{}", csv(labels));
values
.into_iter()
.for_each(|line| println!("{}", csv(line)))
}
OutputFormat::Human(noise) => match noise {
NoiseLevel::Verbose => {
values.into_iter().for_each(|line| match line.len() {
0 => (),
1 => println!("{}", line.get(0).unwrap()),
2 => println!("{}: {}", line.get(0).unwrap(), line.get(1).unwrap()),
_ => println!(
"{}: {} ({})",
line.get(0).unwrap(),
line.get(1).unwrap(),
line.iter()
.skip(2)
.map(|s| s.to_string())
.collect::<Vec<_>>()
.join(", ")
),
});
}
NoiseLevel::Normal => {
values.into_iter().for_each(|line| {
if let (Some(label), Some(item)) = (line.get(0), line.get(1)) {
println!("{}: {}", label, item);
} else if let Some(info) = line.get(0) {
println!("{}", info);
}
});
}
NoiseLevel::Quiet => values.into_iter().for_each(|line| {
if let Some(message) = line.get(1) {
println!("{}", message);
}
}),
},
OutputFormat::Json => {
let keys = labels;
let objs = values
.into_iter()
.map(|vals| {
let mut obj = json::JsonValue::new_object();
keys.iter().zip(vals).for_each(|(k, v)| obj[*k] = v.into());
obj
})
.collect::<Vec<_>>();
println!("{}", json::stringify_pretty(objs, 2));
}
OutputFormat::JsonCompact => {
let keys = labels;
let objs = values
.into_iter()
.map(|vals| {
let mut obj = json::JsonValue::new_object();
keys.iter().zip(vals).for_each(|(k, v)| obj[*k] = v.into());
obj
})
.collect::<Vec<_>>();
println!("{}", json::stringify(objs));
}
OutputFormat::Silent => {
unreachable!("[BUG] Sigi should always exit outputting before this point.")
}
OutputFormat::Tsv => {
let tsv = joining("\t");
println!("{}", tsv(labels));
values
.into_iter()
.for_each(|line| println!("{}", tsv(line)))
}
}
}
}