-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmain.rs
389 lines (351 loc) · 11.7 KB
/
main.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
// std imports
use std::{
default::Default,
io::{IsTerminal, stdin, stdout},
path::PathBuf,
process,
sync::Arc,
time::Duration,
};
// third-party imports
use chrono::Utc;
use clap::{CommandFactory, Parser};
use enumset::enum_set;
use enumset_ext::EnumSetExt;
use env_logger::{self as logger};
use itertools::Itertools;
// local imports
use hl::{
Delimiter, IncludeExcludeKeyFilter, KeyMatchOptions, app,
appdirs::AppDirs,
cli, config,
datefmt::LinuxDateFormat,
error::*,
input::InputReference,
output::{OutputStream, Pager},
query::Query,
settings::{InputInfo, Settings},
signal::SignalHandler,
theme::Theme,
timeparse::parse_time,
timezone::Tz,
};
// private modules
mod help;
const HL_DEBUG_LOG: &str = "HL_DEBUG_LOG";
// ---
fn bootstrap() -> Result<Settings> {
if std::env::var(HL_DEBUG_LOG).is_ok() {
logger::Builder::from_env(HL_DEBUG_LOG).format_timestamp_micros().init();
log::debug!("logging initialized");
} else {
logger::Builder::new()
.filter_level(log::LevelFilter::Warn)
.format_timestamp_millis()
.init()
}
let opt = cli::BootstrapOpt::parse().args;
let (offset, no_default_configs) = opt
.config
.iter()
.rposition(|x| x == "" || x == "-")
.map(|x| (x + 1, true))
.unwrap_or_default();
let configs = &opt.config[offset..];
let settings = config::at(configs).no_default(no_default_configs).load()?;
config::global::initialize(settings.clone());
Ok(settings)
}
fn run() -> Result<()> {
let settings = bootstrap()?;
let opt = cli::Opt::parse_from(wild::args());
if opt.help {
return cli::Opt::command().print_help().map_err(Error::Io);
}
if let Some(shell) = opt.shell_completions {
let mut cmd = cli::Opt::command();
let name = cmd.get_name().to_string();
clap_complete::generate(shell, &mut cmd, name, &mut stdout());
return Ok(());
}
if opt.man_page {
let man = clap_mangen::Man::new(cli::Opt::command());
man.render(&mut stdout())?;
return Ok(());
}
let app_dirs = config::app_dirs().ok_or(Error::AppDirs)?;
if let Some(tags) = opt.list_themes {
return list_themes(&app_dirs, tags);
}
let color_supported = if stdout().is_terminal() {
if let Err(err) = hl::enable_ansi_support() {
eprintln!("failed to enable ansi support: {}", err);
false
} else {
true
}
} else {
false
};
// Configure color scheme.
let color = if opt.color_always {
cli::ColorOption::Always
} else {
opt.color
};
let use_colors = match color {
cli::ColorOption::Auto => stdout().is_terminal() && color_supported,
cli::ColorOption::Always => true,
cli::ColorOption::Never => false,
};
let theme = if use_colors {
let theme = &opt.theme;
Theme::load(&app_dirs, theme)?
} else {
Theme::none()
};
// Configure concurrency.
let concurrency = match opt.concurrency.or(settings.concurrency) {
None | Some(0) => num_cpus::get(),
Some(value) => value,
};
// Configure timezone.
let tz = if opt.local { Tz::Local } else { Tz::IANA(opt.time_zone) };
// Configure time format.
let time_format = LinuxDateFormat::new(&opt.time_format).compile();
// Configure filter.
let filter = hl::Filter {
fields: hl::FieldFilterSet::new(&opt.filter)?,
level: opt.level.map(|x| x.into()),
since: if let Some(v) = &opt.since {
Some(parse_time(v, &tz, &time_format)?.with_timezone(&Utc))
} else {
None
},
until: if let Some(v) = &opt.until {
Some(parse_time(v, &tz, &time_format)?.with_timezone(&Utc))
} else {
None
},
};
// Configure hide_empty_fields
let hide_empty_fields = !opt.show_empty_fields && opt.hide_empty_fields;
// Configure field filter.
let all = || IncludeExcludeKeyFilter::new(KeyMatchOptions::default());
let none = || all().excluded();
let mut fields = all();
for (i, key) in settings.fields.hide.iter().chain(&opt.hide).enumerate() {
if key == "*" {
fields = none();
} else if key == "!*" {
fields = all();
} else if key.starts_with("!") {
if i == 0 {
fields = none();
}
fields.entry(&key[1..]).include();
} else if key.starts_with("\\!") {
fields.entry(&key[1..]).exclude();
} else if key.starts_with("\\\\") {
fields.entry(&key[1..]).exclude();
} else {
fields.entry(&key).exclude();
}
}
let max_message_size = opt.max_message_size;
let buffer_size = std::cmp::min(max_message_size, opt.buffer_size);
let mut query: Option<Query> = None;
for q in &opt.query {
let right = Query::parse(&q)?;
if let Some(left) = query {
query = Some(left.and(right));
} else {
query = Some(right);
}
}
let mut delimiter = Delimiter::default();
if let Some(d) = opt.delimiter {
delimiter = match d.to_lowercase().as_str() {
"nul" => Delimiter::Byte(0),
"lf" => Delimiter::Byte(b'\n'),
"cr" => Delimiter::Byte(b'\r'),
"crlf" => Delimiter::default(),
_ => {
if d.len() == 1 {
Delimiter::Byte(d.as_bytes()[0])
} else if d.len() > 1 {
Delimiter::Str(d)
} else {
Delimiter::default()
}
}
};
}
let mut input_info = *opt.input_info;
if input_info.contains(InputInfo::Auto) {
log::debug!("configured input info layouts: {input_info}");
input_info = InputInfo::resolve(input_info);
log::debug!("* resolved input info layouts: {input_info}");
match term_size::dimensions_stdout().map(|(w, _)| w) {
None => {
log::debug!("* no terminal detected");
}
Some(200..) => {
log::debug!("* terminal is wide enough to show full input info");
}
Some(160..) => {
log::debug!("* terminal is wide enough to show compact input info");
if input_info.intersects(enum_set!(InputInfo::Minimal | InputInfo::Compact)) {
input_info.remove(InputInfo::Full);
}
}
_ => {
log::debug!("* terminal is too narrow to show any input info except minimal");
if input_info.intersects(enum_set!(InputInfo::Minimal | InputInfo::Compact)) {
input_info.remove(InputInfo::Full);
}
if input_info.contains(InputInfo::Minimal) {
input_info.remove(InputInfo::Compact);
}
}
}
}
// Create app.
let app = hl::App::new(hl::Options {
theme: Arc::new(theme),
raw: opt.raw,
raw_fields: opt.raw_fields,
allow_prefix: opt.allow_prefix,
time_format,
buffer_size,
max_message_size,
concurrency,
filter: app::AdvancedFilter::new(filter, query).into(),
fields: hl::FieldOptions {
settings: settings.fields.clone(),
filter: Arc::new(fields),
},
formatting: settings.formatting.clone(),
time_zone: tz,
hide_empty_fields,
sort: opt.sort,
follow: opt.follow,
sync_interval: Duration::from_millis(opt.sync_interval_ms),
input_info,
input_format: match opt.input_format {
cli::InputFormat::Auto => None,
cli::InputFormat::Json => Some(app::InputFormat::Json),
cli::InputFormat::Logfmt => Some(app::InputFormat::Logfmt),
},
dump_index: opt.dump_index,
app_dirs: Some(app_dirs),
tail: opt.tail,
delimiter,
unix_ts_unit: match opt.unix_timestamp_unit {
cli::UnixTimestampUnit::Auto => None,
cli::UnixTimestampUnit::S => Some(app::UnixTimestampUnit::Seconds),
cli::UnixTimestampUnit::Ms => Some(app::UnixTimestampUnit::Milliseconds),
cli::UnixTimestampUnit::Us => Some(app::UnixTimestampUnit::Microseconds),
cli::UnixTimestampUnit::Ns => Some(app::UnixTimestampUnit::Nanoseconds),
},
flatten: opt.flatten != cli::FlattenOption::Never,
});
// Configure the input.
let mut inputs = opt
.files
.iter()
.map(|x| {
if x.to_str() == Some("-") {
Ok::<_, std::io::Error>(InputReference::Stdin)
} else {
Ok(InputReference::File(x.clone().try_into()?))
}
})
.collect::<std::result::Result<Vec<_>, _>>()?;
if inputs.len() == 0 {
if stdin().is_terminal() {
let mut cmd = cli::Opt::command();
return cmd.print_help().map_err(Error::Io);
}
inputs.push(InputReference::Stdin);
}
let n = inputs.len();
log::debug!("hold {n} inputs");
let inputs = inputs
.into_iter()
.map(|input| input.hold().map_err(Error::Io))
.collect::<Result<Vec<_>>>()?;
let paging = match opt.paging {
cli::PagingOption::Auto => {
if stdout().is_terminal() {
true
} else {
false
}
}
cli::PagingOption::Always => true,
cli::PagingOption::Never => false,
};
let paging = if opt.paging_never || opt.follow { false } else { paging };
let mut output: OutputStream = match opt.output {
Some(output) => Box::new(std::fs::File::create(PathBuf::from(&output))?),
None => {
if paging {
if let Ok(pager) = Pager::new() {
Box::new(pager)
} else {
Box::new(stdout())
}
} else {
Box::new(stdout())
}
}
};
log::debug!("run the app");
// Run the app.
let run = || match app.run(inputs, output.as_mut()) {
Ok(()) => Ok(()),
Err(Error::Io(ref e)) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(()),
Err(err) => Err(err),
};
let interrupt_ignore_count = if opt.follow { 0 } else { opt.interrupt_ignore_count };
// Run the app with signal handling.
SignalHandler::run(interrupt_ignore_count, std::time::Duration::from_secs(1), run)
}
fn list_themes(app_dirs: &AppDirs, tags: Option<cli::ThemeTagSet>) -> Result<()> {
let items = Theme::list(app_dirs)?;
let mut formatter = help::Formatter::new(stdout());
formatter.format_grouped_list(
items
.into_iter()
.filter(|(name, _)| {
if let Some(tags) = tags {
hl::themecfg::Theme::load(app_dirs, &name)
.ok()
.map(|theme| theme.tags.includes(*tags))
.unwrap_or(false)
} else {
true
}
})
.sorted_by_key(|x| (x.1.origin, x.0.clone()))
.chunk_by(|x| x.1.origin)
.into_iter()
.map(|(origin, group)| (origin, group.map(|x| x.0))),
)?;
Ok(())
}
fn main() {
if let Err(err) = run() {
err.log(&AppInfo);
process::exit(1);
}
}
struct AppInfo;
impl AppInfoProvider for AppInfo {
fn usage_suggestion(&self, request: UsageRequest) -> Option<UsageResponse> {
match request {
UsageRequest::ListThemes => Some(("--list-themes".into(), "".into())),
}
}
}