1use std::path::PathBuf;
6
7pub trait CliOptions {
12 fn follow(&self) -> bool;
13 fn sticky(&self) -> bool;
14 fn bytes(&self) -> Option<i64>;
15 fn offset(&self) -> Option<i64>;
16 fn verbose(&self) -> bool;
17 fn quiet(&self) -> bool;
18 fn timestamps(&self) -> bool;
19 fn window(&self) -> u64;
20 fn chunked(&self) -> bool;
21 fn no_chunked(&self) -> bool;
22 fn max_memory(&self) -> Option<usize>;
23 fn args(&self) -> &[String];
24 #[cfg(debug_assertions)]
25 fn profile_json(&self) -> bool;
26}
27
28#[derive(Debug, Clone, Default)]
30pub struct ConfigOpts {
31 pub tailing: bool,
32 pub sticky: bool,
33 pub offset: i64,
34 pub offset_unit: OffsetUnit,
35 pub show_time: bool,
36 pub batch_window_ms: u64,
37 pub mode: InputMode,
38 pub force_chunked: bool,
39 pub disable_chunked: bool,
40 pub no_file_names: bool,
41 pub all_file_names: bool,
42 pub max_memory: Option<usize>,
43 #[cfg(debug_assertions)]
44 pub profile_json: bool,
45}
46
47#[derive(Debug, Clone, Default, Copy)]
48pub enum OffsetUnit {
49 #[default]
50 Lines,
51 Bytes,
52}
53
54#[derive(Debug, Clone, Default)]
56pub enum InputMode {
57 #[default]
59 Stdin,
60 SingleFile { path: PathBuf },
62 MultiFile { paths: Vec<PathBuf> },
64}
65
66#[cfg(not(test))]
68mod runtime {
69 use std::sync::OnceLock;
70
71 use super::ConfigOpts;
72
73 pub static CONFIG: OnceLock<ConfigOpts> = OnceLock::new();
75
76 pub fn config() -> &'static ConfigOpts {
78 CONFIG
79 .get()
80 .expect("programmer error: tried to access configuration before it was set")
81 }
82
83 pub fn set(input: ConfigOpts) -> Result<(), Box<ConfigOpts>> {
85 match CONFIG.set(input) {
86 Ok(_) => Ok(()),
87 Err(e) => Err(Box::new(e)),
88 }
89 }
90}
91
92#[cfg(test)]
94mod runtime {
95 use std::cell::RefCell;
96
97 use super::ConfigOpts;
98
99 thread_local! {
101 pub static TEST_CONFIG: RefCell<Option<ConfigOpts>> = const { RefCell::new(None) };
102 }
103
104 pub fn config() -> ConfigOpts {
106 TEST_CONFIG.with(|cfg| cfg.borrow().as_ref().cloned().unwrap_or_else(ConfigOpts::default))
107 }
108
109 pub fn set(input: ConfigOpts) -> Result<(), Box<ConfigOpts>> {
111 TEST_CONFIG.with(|cfg| {
112 *cfg.borrow_mut() = Some(input);
113 });
114 Ok(())
115 }
116
117 pub fn update<F>(f: F)
119 where
120 F: FnOnce(&mut ConfigOpts),
121 {
122 TEST_CONFIG.with(|cfg| {
123 let mut borrowed = cfg.borrow_mut();
124 if borrowed.is_none() {
125 *borrowed = Some(ConfigOpts::default());
126 }
127 if let Some(ref mut config) = borrowed.as_mut() {
128 f(config);
129 }
130 });
131 }
132
133 pub fn with_config<F, R>(new_config: ConfigOpts, f: F) -> R
135 where
136 F: FnOnce() -> R,
137 {
138 let old_config = TEST_CONFIG.with(|cfg| cfg.borrow().clone());
140
141 TEST_CONFIG.with(|cfg| {
143 *cfg.borrow_mut() = Some(new_config);
144 });
145
146 let result = f();
148
149 TEST_CONFIG.with(|cfg| {
151 *cfg.borrow_mut() = old_config;
152 });
153
154 result
155 }
156}
157
158use miette::Result;
160pub use runtime::{config, set};
161#[cfg(test)]
162pub use runtime::{update, with_config};
163
164use crate::defaults::{SystemDefaults, get_system_config};
165use crate::errors::TaleError;
166
167pub fn tailing() -> bool {
171 config().tailing
172}
173
174pub fn sticky() -> bool {
175 config().sticky
176}
177
178pub fn offset() -> i64 {
179 config().offset
180}
181
182pub fn offset_unit() -> OffsetUnit {
183 config().offset_unit
184}
185
186pub fn show_time() -> bool {
187 config().show_time
188}
189
190pub fn batch_window_ms() -> u64 {
191 config().batch_window_ms
192}
193
194pub fn force_chunked() -> bool {
195 config().force_chunked
196}
197
198pub fn disable_chunked() -> bool {
199 config().disable_chunked
200}
201
202pub fn mode() -> InputMode {
203 config().mode.clone()
204}
205
206fn unescape_glob_pattern(pattern: &str) -> String {
208 let mut result = String::new();
209 let mut chars = pattern.chars().peekable();
210
211 while let Some(ch) = chars.next() {
212 if ch == '\\' {
213 if let Some(&next_ch) = chars.peek() {
215 if matches!(next_ch, '*' | '?' | '[' | ']' | '{' | '}') {
216 chars.next();
218 result.push(next_ch);
219 } else {
220 result.push(ch);
222 }
223 } else {
224 result.push(ch);
226 }
227 } else {
228 result.push(ch);
229 }
230 }
231
232 result
233}
234
235fn is_glob(maybe: &str) -> bool {
237 if maybe.contains('?') || maybe.contains('*') || maybe.contains('[') || maybe.contains('{') {
239 return true;
240 }
241
242 maybe.contains("\\*") || maybe.contains("\\?") || maybe.contains("\\[") || maybe.contains("\\{")
244}
245
246fn expand_globs(args: &[String]) -> Result<Vec<PathBuf>, TaleError> {
250 let mut all_paths = Vec::new();
251
252 for candidate in args {
253 if is_glob(candidate.as_str()) {
254 let unescaped_pattern = unescape_glob_pattern(candidate);
256 let pattern = glob::glob(&unescaped_pattern)?;
257 for fpath in pattern.flatten() {
258 if fpath.is_file() {
259 all_paths.push(fpath);
260 }
261 }
262 } else {
263 let fpath = PathBuf::from(candidate);
264 if fpath.exists() && fpath.is_file() {
265 all_paths.push(fpath);
266 }
267 }
268 }
269 all_paths.sort();
270 Ok(all_paths)
271}
272
273fn handle_possible_paths(args: &[String]) -> Result<Vec<PathBuf>, TaleError> {
274 match expand_globs(args) {
275 Ok(paths) => {
276 if paths.is_empty() {
277 let patterns: Vec<String> = args.iter().map(|s| format!("'{}'", s)).collect();
279 Err(TaleError::from(Box::new(crate::errors::FileError::NotFound {
280 path: PathBuf::from(patterns.join(", ")),
281 similar_files: vec![
282 "Check if the glob pattern is correct".to_string(),
283 "Verify the files exist in the specified directory".to_string(),
284 "Try using an absolute path".to_string(),
285 ],
286 })))
287 } else {
288 Ok(paths)
289 }
290 }
291 Err(e) => {
292 Err(e)
294 }
295 }
296}
297
298impl ConfigOpts {
299 pub fn new(args: &impl CliOptions) -> Result<Self> {
300 let system_config = get_system_config();
302 let positional = args.args();
303 let (mode, maybe_offset) = match positional.len() {
304 0 => (InputMode::Stdin, None),
305 1 => {
306 let only = &positional[0];
307 if (only.starts_with('-') || only.starts_with('+'))
308 && only.len() > 1
309 && let Ok(offset) = only.parse::<i64>()
310 {
311 (InputMode::Stdin, Some(offset))
313 } else if is_glob(only) {
314 let paths = handle_possible_paths(std::slice::from_ref(only))?;
316 (InputMode::MultiFile { paths }, None)
317 } else {
318 (
321 InputMode::SingleFile {
322 path: PathBuf::from(only),
323 },
324 None,
325 )
326 }
327 }
328 2 => {
329 let (first, second) = (&positional[0], &positional[1]);
330
331 if let Ok(offset) = first.parse::<i64>() {
333 (
335 InputMode::SingleFile {
336 path: PathBuf::from(second),
337 },
338 Some(offset),
339 )
340 } else {
341 let paths = handle_possible_paths(positional)?;
343 (InputMode::MultiFile { paths }, None)
344 }
345 }
346 _ => {
347 let paths = handle_possible_paths(positional)?;
350 (InputMode::MultiFile { paths }, None)
351 }
352 };
353
354 let (offset, offset_unit) = if let Some(bytes) = args.bytes() {
355 (bytes, OffsetUnit::Bytes)
356 } else if let Some(lines) = args.offset() {
357 (lines, OffsetUnit::Lines)
358 } else if let Some(offset) = maybe_offset {
359 (offset, OffsetUnit::Lines)
360 } else {
361 (0, OffsetUnit::Lines)
362 };
363
364 let max_memory = args.max_memory().unwrap_or_else(|| {
366 let system_percentage = system_config.memory_percentage;
368 if let Some(memory_stats) = memory_stats::memory_stats() {
369 let system_memory = memory_stats.physical_mem;
370 let calculated = (system_memory as f64 * system_percentage / 100.0) as usize;
371 calculated.clamp(SystemDefaults::MIN_MEMORY_BUDGET, SystemDefaults::MAX_MEMORY_BUDGET)
372 } else {
373 system_config.max_memory_mb * 1024 * 1024
375 }
376 });
377
378 let force_chunked = if args.chunked() {
381 true
382 } else if args.no_chunked() {
383 false
384 } else {
385 system_config.force_chunked
387 };
388
389 Ok(Self {
390 tailing: args.follow() || args.sticky(),
391 sticky: args.sticky(),
392 offset,
393 offset_unit,
394 show_time: args.timestamps(),
395 batch_window_ms: args.window(),
396 mode,
397 force_chunked,
398 disable_chunked: args.no_chunked(),
399 no_file_names: args.quiet(),
400 all_file_names: args.verbose(),
401 max_memory: Some(max_memory),
402 #[cfg(debug_assertions)]
403 profile_json: args.profile_json(),
404 })
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411
412 #[derive(Default)]
415 struct TestArgs {
416 follow: bool,
417 sticky: bool,
418 bytes: Option<i64>,
419 offset: Option<i64>,
420 verbose: bool,
421 quiet: bool,
422 timestamps: bool,
423 window: u64,
424 chunked: bool,
425 no_chunked: bool,
426 max_memory: Option<usize>,
427 positional: Vec<String>,
428 }
429
430 impl CliOptions for TestArgs {
431 fn follow(&self) -> bool {
432 self.follow
433 }
434 fn sticky(&self) -> bool {
435 self.sticky
436 }
437 fn bytes(&self) -> Option<i64> {
438 self.bytes
439 }
440 fn offset(&self) -> Option<i64> {
441 self.offset
442 }
443 fn verbose(&self) -> bool {
444 self.verbose
445 }
446 fn quiet(&self) -> bool {
447 self.quiet
448 }
449 fn timestamps(&self) -> bool {
450 self.timestamps
451 }
452 fn window(&self) -> u64 {
453 self.window
454 }
455 fn chunked(&self) -> bool {
456 self.chunked
457 }
458 fn no_chunked(&self) -> bool {
459 self.no_chunked
460 }
461 fn max_memory(&self) -> Option<usize> {
462 self.max_memory
463 }
464 fn args(&self) -> &[String] {
465 &self.positional
466 }
467 #[cfg(debug_assertions)]
468 fn profile_json(&self) -> bool {
469 false
470 }
471 }
472
473 #[test]
474 fn complicated_args() {
475 let args = TestArgs {
478 timestamps: true,
479 follow: true,
480 bytes: Some(-5),
481 window: 250,
482 positional: vec!["-4".to_string()],
483 max_memory: Some(10_000_000_000),
484 ..Default::default()
485 };
486 let config = ConfigOpts::new(&args).expect("Config should be valid for test");
487 assert_eq!(config.offset, -5);
488 assert!(matches!(config.mode, InputMode::Stdin));
489 }
490
491 #[test]
492 fn glob_expansions() {
493 let fixture_glob = "./fixtures/*.log".to_string();
494 let results = expand_globs(&[fixture_glob]).expect("this list of paths should expand successfully");
495 assert_eq!(results.len(), 8); assert_eq!(
497 results.as_slice(),
498 vec![
499 PathBuf::from("fixtures/ascii_colors.log"),
500 PathBuf::from("fixtures/garbage_prefix.log"),
501 PathBuf::from("fixtures/java_stacktrace.log"),
502 PathBuf::from("fixtures/just_loglines.log"),
503 PathBuf::from("fixtures/log4j.log"),
504 PathBuf::from("fixtures/mixed_json_types.log"),
505 PathBuf::from("fixtures/mixed_text_json.log"),
506 PathBuf::from("fixtures/windows_line_endings.log")
507 ]
508 );
509 }
510
511 #[test]
512 fn can_unescape_glob_pattern() {
513 assert_eq!(unescape_glob_pattern("\\*.log"), "*.log");
515 assert_eq!(unescape_glob_pattern("test\\?.txt"), "test?.txt");
516 assert_eq!(unescape_glob_pattern("\\[abc\\]"), "[abc]");
517
518 assert_eq!(unescape_glob_pattern("\\*.log\\?"), "*.log?");
520 assert_eq!(unescape_glob_pattern("test\\*file\\?.log"), "test*file?.log");
521
522 assert_eq!(unescape_glob_pattern("file\\name.txt"), "file\\name.txt");
524 assert_eq!(unescape_glob_pattern("path\\to\\file"), "path\\to\\file");
525
526 assert_eq!(unescape_glob_pattern("*.log"), "*.log");
528 assert_eq!(unescape_glob_pattern("test?.txt"), "test?.txt");
529
530 assert_eq!(unescape_glob_pattern(""), "");
532 assert_eq!(unescape_glob_pattern("\\"), "\\");
533 assert_eq!(unescape_glob_pattern("file\\"), "file\\");
534 }
535
536 #[test]
537 fn is_glob_with_escaped_patterns_works() {
538 assert!(is_glob("\\*.log"));
540 assert!(is_glob("test\\?.txt"));
541 assert!(is_glob("\\[abc]"));
542
543 assert!(is_glob("*.log"));
545 assert!(is_glob("test?.txt"));
546 assert!(is_glob("[abc]"));
547
548 assert!(!is_glob("file.log"));
550 assert!(!is_glob("test.txt"));
551 assert!(!is_glob("path/to/file"));
552
553 assert!(!is_glob("file\\name.txt"));
555 assert!(!is_glob("path\\to\\file"));
556 }
557
558 #[test]
559 fn can_expand_escaped_globs() {
560 let escaped_fixture_glob = ".\\*/fixtures/\\*.log".to_string();
563 let normal_fixture_glob = "./fixtures/*.log".to_string();
564
565 if let (Ok(escaped_results), Ok(normal_results)) = (
567 expand_globs(&[escaped_fixture_glob]),
568 expand_globs(&[normal_fixture_glob]),
569 ) {
570 assert_eq!(escaped_results, normal_results);
571 }
572 }
573
574 #[test]
575 fn can_modify_config() {
576 let initial_config = ConfigOpts {
577 tailing: false,
578 sticky: false,
579 offset: 10,
580 offset_unit: OffsetUnit::Lines,
581 show_time: false,
582 batch_window_ms: 250,
583 mode: InputMode::Stdin,
584 force_chunked: false,
585 disable_chunked: false,
586 ..Default::default()
587 };
588
589 with_config(initial_config.clone(), || {
591 update(|cfg| {
593 cfg.tailing = true;
594 cfg.offset = 20;
595 cfg.show_time = true;
596 });
597
598 assert!(tailing());
600 assert_eq!(offset(), 20);
601 assert!(show_time());
602 });
603 }
604
605 #[test]
606 fn can_test_with_config() {
607 let original_config = ConfigOpts::default();
608 set(original_config.clone()).expect("should set config");
609
610 let original_offset = offset();
611 let original_tailing = tailing();
612
613 let result = with_config(
615 ConfigOpts {
616 tailing: true,
617 sticky: false,
618 offset: 42,
619 offset_unit: OffsetUnit::Bytes,
620 show_time: true,
621 batch_window_ms: 500,
622 mode: InputMode::Stdin,
623 force_chunked: true,
624 disable_chunked: false,
625 ..Default::default()
626 },
627 || {
628 assert_eq!(offset(), 42);
630 assert!(tailing());
631 assert_eq!(batch_window_ms(), 500);
632 assert!(force_chunked());
633
634 "test_successful"
636 },
637 );
638
639 assert_eq!(offset(), original_offset);
641 assert_eq!(tailing(), original_tailing);
642 assert_eq!(result, "test_successful");
643 }
644
645 #[test]
646 fn concurrent_access_to_test_config() {
647 use std::thread;
648 use std::time::Duration;
649
650 let handles: Vec<_> = (0..3)
652 .map(|i| {
653 thread::spawn(move || {
654 let config = ConfigOpts {
655 offset: i * 10,
656 tailing: i % 2 == 0,
657 show_time: i % 2 == 1,
658 ..ConfigOpts::default()
659 };
660
661 set(config).expect("should set config");
662
663 thread::sleep(Duration::from_millis(10));
665
666 assert_eq!(offset(), i * 10);
668 assert_eq!(tailing(), i % 2 == 0);
669 assert_eq!(show_time(), i % 2 == 1);
670
671 i
672 })
673 })
674 .collect();
675
676 let results: Vec<_> = handles
678 .into_iter()
679 .map(|h| h.join().expect("test results should always be ok"))
680 .collect();
681 assert_eq!(results, vec![0, 1, 2]);
682 }
683
684 #[test]
685 fn config_accessors_work() {
686 let test_config = ConfigOpts {
687 tailing: true,
688 sticky: true,
689 offset: -100,
690 offset_unit: OffsetUnit::Bytes,
691 show_time: true,
692 batch_window_ms: 1000,
693 mode: InputMode::SingleFile {
694 path: PathBuf::from("test.log"),
695 },
696 force_chunked: true,
697 disable_chunked: false,
698 ..Default::default()
699 };
700
701 with_config(test_config, || {
703 assert!(tailing());
705 assert!(sticky());
706 assert_eq!(offset(), -100);
707 assert!(matches!(offset_unit(), OffsetUnit::Bytes));
708 assert!(show_time());
709 assert_eq!(batch_window_ms(), 1000);
710 assert!(matches!(mode(), InputMode::SingleFile { .. }));
711 assert!(force_chunked());
712 assert!(!disable_chunked());
713 });
714 }
715}