plox 0.3.7

Turn messy logs into clean graphs. Plot fields or regex matches over time, mark events, count occurrences — all from your terminal.
Documentation
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! Handles the graph config expansion.
//!
//! Once a raw graph configuration is loaded, this module resolves it into a ready-to-use form.
//! It fills in defaults, validates values, and produces concrete plotting layout by binding lines and panels to input
//! log files.
//! This is the bridge between user input and the internal structures the tool relies on.

#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(private_interfaces)]
#![allow(unused_variables)]
use crate::{
	error::Error,
	graph_config::{
		DataSource, GraphConfig, GraphFullContext, Line, LineParams, OutputGraphContext,
		PanelParams,
	},
};
use chrono::NaiveDateTime;
use clap::Args;
use serde::{Deserialize, Serialize};
use std::{
	fmt::Display,
	fs,
	path::{Path, PathBuf},
	str::FromStr,
};
use tracing::info;

#[derive(Debug)]
pub struct ResolvedGraphConfig {
	pub panels: Vec<ResolvedPanel>,
}

impl ResolvedGraphConfig {
	//implement the function that counts all the lines from all the panels
	pub fn all_lines(&self) -> impl Iterator<Item = &ResolvedLine> {
		self.panels.iter().flat_map(|panel| panel.lines.iter())
	}

	pub fn all_lines_count(&self) -> usize {
		self.panels.iter().map(|panel| panel.lines.len()).sum()
	}
}

#[derive(Debug, Default)]
pub struct ResolvedPanel {
	pub lines: Vec<ResolvedLine>,
	pub params: PanelParams,

	/// If panel was duplicated due to per-file-panels this will be set to the source file name.
	input_file_name: Option<PathBuf>,

	/// Final time range to use for this panel when plotting.
	///
	/// This is derived from the time ranges of all its lines, using the
	/// configured range mode (e.g. full span or best-fit intersection),
	/// and may be overridden by manual range provided in CLI.
	///
	/// Used to generate the `set xrange [...]` directive for Gnuplot.
	//todo: do something with pub
	pub(crate) time_range: Option<(NaiveDateTime, NaiveDateTime)>,
}

impl ResolvedPanel {
	pub fn new_with_lines(lines: Vec<ResolvedLine>) -> Self {
		Self { lines, ..Default::default() }
	}

	pub fn is_empty(&self) -> bool {
		self.lines.is_empty() || self.lines.iter().all(ResolvedLine::is_empty)
	}

	pub fn input_file(&self) -> &Option<PathBuf> {
		&self.input_file_name
	}

	pub fn title(&self) -> Vec<String> {
		match (&self.params.panel_title, &self.input_file_name) {
			(Some(panel_title), Some(input_file_name)) => {
				let file_stem = input_file_name
					.file_stem()
					.expect("filename is validated at this point")
					.to_string_lossy();
				vec![panel_title.clone(), format!("[{}]", file_stem)]
			},
			(Some(panel_title), None) => vec![panel_title.clone()],
			(None, Some(input_file_name)) => {
				let file_stem = input_file_name
					.file_stem()
					.expect("filename is validated at this point")
					.to_string_lossy();
				vec![format!("[{}]", file_stem)]
			},
			(None, None) => Default::default(),
		}
	}

	pub fn time_range(&self) -> &Option<(NaiveDateTime, NaiveDateTime)> {
		&self.time_range
	}

	pub fn set_time_range(&mut self, start: NaiveDateTime, end: NaiveDateTime) {
		self.time_range = Some((start, end));
	}
}

#[derive(Debug, Clone)]
pub struct ResolvedLine {
	pub line: Line,
	pub source: ResolvedSource,

	/// Optional path to a shared CSV file used for multiple lines with the same (guard,
	/// pattern/field).
	///
	/// This allows avoiding redundant log processing by reusing the output of a previously matched
	/// line, typically one using `PlotField`, across other compatible line data sources like
	/// [`DataSource::EventCount`] or [`DataSource::EventDelta`].
	shared_csv_file: Option<PathBuf>,

	///Indicates if line contains any data.
	///
	///Should be set just after processing input files.
	data_points_count: usize,

	/// Time range of this line's data, based on the earliest and latest
	/// timestamps parsed from its CSV file.
	///
	///`Some((start, end))` if the file contains valid timestamps,
	/// or `None` if the file is empty or failed to parse.
	///
	/// This is used for panel-level range calculations and alignment.
	//todo pub
	time_range: Option<(NaiveDateTime, NaiveDateTime)>,
}

impl ResolvedLine {
	pub fn is_empty(&self) -> bool {
		self.data_points_count == 0
	}

	pub fn from_explicit_name(line: Line, file_name: PathBuf) -> Self {
		Self {
			line,
			source: ResolvedSource::FileName(file_name),
			shared_csv_file: None,
			data_points_count: 0,
			time_range: None,
		}
	}

	fn try_from_populated_inputs(
		line: Line,
		poulated_input: Option<(usize, &PathBuf)>,
	) -> Option<Self> {
		match poulated_input {
			None => ResolvedSource::try_from_explicit(line.source()).map(|source| Self {
				line,
				source,
				shared_csv_file: None,
				data_points_count: 0,
				time_range: None,
			}),
			Some((file_id, file_name)) => {
				ResolvedSource::try_match_input(line.source(), file_id, file_name).map(|source| {
					Self {
						line,
						source,
						shared_csv_file: None,
						data_points_count: 0,
						time_range: None,
					}
				})
			},
		}
	}

	/// The name of final csv file to be used.
	pub fn shared_csv_filename(&self) -> Option<PathBuf> {
		self.shared_csv_file.clone()
	}

	pub fn expect_shared_csv_filename(&self) -> PathBuf {
		self.shared_csv_filename().expect("All shared CVS are resolved at this point.")
	}

	/// Set the name of final csv file to be used.
	pub fn set_shared_csv_filename(&mut self, path: &Path) {
		self.shared_csv_file = Some(path.to_path_buf());
	}

	pub fn set_data_points_count(&mut self, count: usize) {
		self.data_points_count = count;
	}

	pub fn set_time_range(&mut self, start: NaiveDateTime, end: NaiveDateTime) {
		self.time_range = Some((start, end));
	}

	pub fn time_range(&self) -> &Option<(NaiveDateTime, NaiveDateTime)> {
		&self.time_range
	}
}

/// Represents the fully resolved source of a log line after expansion.
///
/// This is used in the `ResolvedGraphConfig` to indicate which concrete input file
/// a line should be read from. It is the result of resolving any `LineSource`
/// (e.g. `file`, `file-id`, or all-files) into a concrete file path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedSource {
	/// A line originally intended for all inputs, now bound to a specific input file.
	PopulatedInput {
		/// Index of the input in `SharedGraphContext::input_files`.
		index: usize,
		/// Resolved file path.
		path: PathBuf,
	},

	/// A line that explicitly used `--file <path>`, preserved as-is.
	FileName(PathBuf),

	/// A line that targeted `--file-id <N>`, resolved to the corresponding input file.
	FileId {
		/// Index of the file in the input list, as provided in graph config.
		index: usize,
		/// Resolved file path.
		path: PathBuf,
	},
}

impl ResolvedSource {
	pub fn file_name(&self) -> &PathBuf {
		match self {
			ResolvedSource::PopulatedInput { path, .. }
			| ResolvedSource::FileName(path)
			| ResolvedSource::FileId { path, .. } => path,
		}
	}
}

impl ResolvedSource {
	/// Attempts to resolve a `LineSource` into a `ResolvedSource` for a specific input file and its
	/// index.
	///
	/// Used during config expansion to assign sources to specific log files.
	///
	/// - Returns `Some` if the source matches the given input file (by ID or for all files).
	/// - Returns `None` if the line is not associated with provided input.
	fn try_match_input(
		source: LineSource,
		input_id: usize,
		input_file_name: &Path,
	) -> Option<Self> {
		match source {
			LineSource::FileId(id) if id == input_id => {
				Some(Self::FileId { index: input_id, path: input_file_name.to_path_buf() })
			},
			LineSource::AllInputFiles => {
				Some(Self::PopulatedInput { index: input_id, path: input_file_name.to_path_buf() })
			},
			_ => None,
		}
	}

	/// Attempts to resolve a line source if it's explicitly bound to a file name.
	fn try_from_explicit(source: LineSource) -> Option<Self> {
		match source {
			LineSource::FileName(name) => Some(Self::FileName(name.clone())),
			_ => None,
		}
	}
}

#[derive(Clone, PartialEq)]
enum LineSource {
	/// from `--file`
	FileName(PathBuf),
	/// from `--file-id`
	FileId(usize),
	/// fallback if neither is given
	AllInputFiles,
}

impl Line {
	fn source(&self) -> LineSource {
		match (&self.params.file_name, self.params.file_id) {
			(Some(path), _) => LineSource::FileName(PathBuf::from(path)),
			(None, Some(id)) => LineSource::FileId(id),
			_ => LineSource::AllInputFiles,
		}
	}
}
pub fn expand_graph_config_with_ctx(
	graph: &GraphConfig,
	ctx: &GraphFullContext,
) -> Result<ResolvedGraphConfig, Error> {
	expand_graph_config(graph, ctx.input(), ctx.output_graph_ctx.per_file_panels())
}

/// Expands a generic `GraphConfig` using the given `SharedGraphContext`, producing a fully resolved
/// `ResolvedGraphConfig`.
///
/// This function performs the following transformations:
/// - Duplicates panels if `per_file_panels` is enabled (one per input file) and panel contains any
///   line that requires input-file population,
/// - Resolves each line's source by:
///   - Using `.file` as-is if explicitly set
///   - Mapping `.file_id` to the corresponding entry in `ctx.input_files`
///   - Applying the line to all input files if no file or file_id is provided
///
/// The result is a `ResolvedGraphConfig` with each line assigned to an exact file and input index.
pub fn expand_graph_config(
	graph: &GraphConfig,
	input: &[PathBuf],
	per_file_panels: bool,
) -> Result<ResolvedGraphConfig, Error> {
	let mut resolved_panels = vec![];

	if per_file_panels {
		for panel in &graph.panels {
			let is_any_line_to_be_populated =
				panel.lines.iter().any(|l| l.source() == LineSource::AllInputFiles);

			if is_any_line_to_be_populated {
				let fixed_lines = panel
					.lines
					.iter()
					.flat_map(|line| match line.source() {
						LineSource::FileName(file) => {
							vec![ResolvedLine::from_explicit_name(line.clone(), file)]
						},

						LineSource::FileId(id) => vec![
							ResolvedLine::try_from_populated_inputs(
								line.clone(),
								Some((id, &input[id])),
							)
							.expect("Line shall be resolvable"),
						],
						_ => {
							vec![]
						},
					})
					.collect::<Vec<_>>();

				for (file_id, input_file) in input.iter().enumerate() {
					let resolved_lines = panel
						.lines
						.iter()
						.filter_map(|line| {
							if let LineSource::AllInputFiles = line.source() {
								ResolvedLine::try_from_populated_inputs(
									line.clone(),
									Some((file_id, input_file)),
								)
							} else {
								None
							}
						})
						.collect::<Vec<_>>();

					let mut lines = fixed_lines.clone();
					lines.extend(resolved_lines);

					resolved_panels.push(ResolvedPanel {
						params: panel.params.clone(),
						lines,
						time_range: None,
						input_file_name: Some(input_file.clone()),
					});
				}
			} else {
				let resolved_lines = panel
					.lines
					.iter()
					.flat_map(|line| match line.source() {
						LineSource::FileName(file) => {
							vec![ResolvedLine::from_explicit_name(line.clone(), file)]
						},

						LineSource::FileId(id) => vec![
							ResolvedLine::try_from_populated_inputs(
								line.clone(),
								Some((id, &input[id])),
							)
							.expect("Line shall be resolvable"),
						],
						_ => {
							panic!(
								"Should not be here. Lines to be populated are handled in other branch. (This is bug)."
							)
						},
					})
					.collect::<Vec<_>>();

				resolved_panels.push(ResolvedPanel {
					params: panel.params.clone(),
					lines: resolved_lines,
					..Default::default()
				});
			}
		}
	} else {
		for panel in &graph.panels {
			let resolved_lines = panel
				.lines
				.iter()
				.flat_map(|line| match line.source() {
					LineSource::FileName(file) => {
						vec![ResolvedLine::from_explicit_name(line.clone(), file)]
					},

					LineSource::FileId(_) | LineSource::AllInputFiles => input
						.iter()
						.enumerate()
						.filter_map(|(i, f)| {
							ResolvedLine::try_from_populated_inputs(line.clone(), Some((i, f)))
						})
						.collect(),
				})
				.collect::<Vec<_>>();

			resolved_panels.push(ResolvedPanel {
				params: panel.params.clone(),
				lines: resolved_lines,
				..Default::default()
			});
		}
	}

	Ok(ResolvedGraphConfig { panels: resolved_panels })
}

#[cfg(test)]
mod tests {
	use tracing::trace;

	use super::*;
	use crate::{
		graph_cli_builder,
		graph_config::{
			DEFAULT_TIMESTAMP_FORMAT, DataSource, EventDeltaSpec, FieldCaptureSpec, Panel,
			TimestampFormat,
		},
		logging::init_tracing_test,
	};

	impl Line {
		fn test_line_name(&self) -> String {
			match self.data_source {
				DataSource::EventValue { ref pattern, .. }
				| DataSource::EventCount { ref pattern, .. }
				| DataSource::EventDelta(EventDeltaSpec { ref pattern, .. })
				| DataSource::FieldValue(FieldCaptureSpec { field: ref pattern, .. })
				| DataSource::FieldValueSum(FieldCaptureSpec { field: ref pattern, .. }) => pattern.clone(),
			}
		}
	}

	macro_rules! check_lines {
		($resolved:expr, $expected_panels:expr, $panel_lens:expr, $file_names:expr, $line_names:expr) => {
			assert_eq!($resolved.panels.len(), $expected_panels);
			for (panel_index, &panel_len) in $panel_lens.iter().enumerate() {
				assert_eq!($resolved.panels[panel_index].lines.len(), panel_len);
				for ((line_index, &file_name), &line_name) in
					$file_names[panel_index].iter().enumerate().zip($line_names[panel_index].iter())
				{
					assert_eq!(
						$resolved.panels[panel_index].lines[line_index]
							.source
							.file_name()
							.to_string_lossy(),
						file_name
					);
					assert_eq!(
						$resolved.panels[panel_index].lines[line_index].line.test_line_name(),
						line_name
					);
				}
			}
		};
		($resolved:expr, $expected_panels:expr, $panel_lens:expr, $file_names:expr) => {
			tracing::trace!("resolved: {:#?}", $resolved);
			tracing::trace!(
				"resolved: {:#?}",
				$resolved
					.panels
					.iter()
					.map(|p| {
						p.lines
							.iter()
							.map(|l| l.source.file_name().to_string_lossy())
							.collect::<Vec<_>>()
					})
					.collect::<Vec<_>>()
			);
			assert_eq!($resolved.panels.len(), $expected_panels);
			for (panel_index, &panel_len) in $panel_lens.iter().enumerate() {
				assert_eq!($resolved.panels[panel_index].lines.len(), panel_len);
				for (line_index, &file_name) in $file_names[panel_index].iter().enumerate() {
					assert_eq!(
						$resolved.panels[panel_index].lines[line_index]
							.source
							.file_name()
							.to_string_lossy(),
						file_name
					);
				}
			}
		};
	}

	#[test]
	fn test_populate_to_panel_01() {
		let input = vec![
			"--input",
			"A,B",
			"--plot",
			"x",
			"--file-id",
			"0",
			"--plot",
			"y",
			"--file-id",
			"1",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(resolved, 1, [2], vec![vec!["A", "B"]], vec![vec!["x", "y"]]);
	}

	#[test]
	fn test_populate_to_panel_02() {
		let input = vec!["--input", "A,B,C", "--plot", "x", "--plot", "y"];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			1,
			[6],
			vec![vec!["A", "B", "C", "A", "B", "C"]],
			vec![vec!["x", "x", "x", "y", "y", "y"]]
		);
	}

	#[test]
	fn test_populate_to_panel_03() {
		let input = vec!["--input", "A,B,C", "--plot", "x", "--plot", "y", "--file-id", "1"];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			1,
			[4],
			vec![vec!["A", "B", "C", "B"]],
			vec![vec!["x", "x", "x", "y"]]
		);
	}

	#[test]
	fn test_populate_to_panel_04() {
		let input = vec!["--input", "A,B,C", "--plot", "x", "--file-id", "1", "--plot", "y"];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			1,
			[4],
			vec![vec!["B", "A", "B", "C"]],
			vec![vec!["x", "y", "y", "y"]]
		);
	}

	#[test]
	fn test_populate_to_panel_05() {
		let input = vec!["--input", "A,B,C", "--plot", "x", "--file-name", "E", "--plot", "y"];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			1,
			[4],
			vec![vec!["E", "A", "B", "C"]],
			vec![vec!["x", "y", "y", "y"]]
		);
	}

	#[test]
	fn test_populate_to_panel_06() {
		#[rustfmt::skip]
		let input = vec![
			"--input", "A,B,C", 
			"--plot", "x", "--file-name", "D", 
			"--plot", "y",
			"--panel",
			"--plot", "u", "--file-name", "E", 
			"--plot", "t"
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			2,
			[4, 4],
			vec![vec!["D", "A", "B", "C"], vec!["E", "A", "B", "C"]],
			vec![vec!["x", "y", "y", "y"], vec!["u", "t", "t", "t"]]
		);
	}

	#[test]
	fn test_populate_to_panel_07() {
		#[rustfmt::skip]
		let input = vec![
			"--input", "A,B,C", 
			"--plot", "x", "--file-name", "D", 
			"--plot", "y", "--file-id", "1", 
			"--plot", "z",
			"--panel",
			"--plot", "u", "--file-name", "E", 
			"--plot", "t"
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			2,
			[5, 4],
			vec![vec!["D", "B", "A", "B", "C"], vec!["E", "A", "B", "C"]],
			vec![vec!["x", "y", "z", "z", "z"], vec!["u", "t", "t", "t"]]
		);
	}

	#[test]
	fn test_populate_to_multiple_panels_01() {
		init_tracing_test();
		#[rustfmt::skip]
		let input = vec![
			"--input", "A,B,C", 
			"--per-file-panels",
			"--plot", "z",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		trace!("ctx: {ctx:#?}");
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			3,
			[1, 1, 1],
			vec![vec!["A"], vec!["B"], vec!["C"]],
			vec![vec!["z"], vec!["z"], vec!["z"]]
		);
	}

	#[test]
	fn test_populate_to_multiple_panels_02() {
		#[rustfmt::skip]
		let input = vec![
			"--input", "A,B,C", 
			"--per-file-panels",
			"--plot", "x",
			"--plot", "y",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			3,
			[2, 2, 2],
			vec![vec!["A", "A"], vec!["B", "B"], vec!["C", "C"]],
			vec![vec!["x", "y"], vec!["x", "y"], vec!["x", "y"]]
		);
	}

	#[test]
	fn test_populate_to_multiple_panels_03() {
		#[rustfmt::skip]
		let input = vec![
			"--input", "A,B,C", 
			"--per-file-panels",
			"--plot", "z",
			"--panel",
			"--plot", "x",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			6,
			[1, 1, 1, 1, 1, 1],
			vec![vec!["A"], vec!["B"], vec!["C"], vec!["A"], vec!["B"], vec!["C"]],
			vec![vec!["z"], vec!["z"], vec!["z"], vec!["x"], vec!["x"], vec!["x"]]
		);
	}

	#[test]
	fn test_populate_to_multiple_panels_04() {
		init_tracing_test();
		#[rustfmt::skip]
		let input = vec![
			"--input", "A,B,C", 
			"--per-file-panels",
			"--plot", "z",
			"--panel",
			"--plot", "x",
			"--plot", "y", "--file-id", "1",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		tracing::trace!("config: {:#?}", config);
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			6,
			[1, 1, 1, 2, 2, 2],
			vec![vec!["A"], vec!["B"], vec!["C"], vec!["B", "A"], vec!["B", "B"], vec!["B", "C"]],
			vec![vec!["z"], vec!["z"], vec!["z"], vec!["y", "x"], vec!["y", "x"], vec!["y", "x"]]
		);
	}

	#[test]
	fn test_populate_to_multiple_panels_05() {
		init_tracing_test();
		#[rustfmt::skip]
		let input = vec![
			"--input", "A,B,C", 
			"--per-file-panels",
			"--plot", "z",
			"--panel",
			"--plot", "x",
			"--plot", "y", "--file-name", "D",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		tracing::trace!("config: {:#?}", config);
		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		check_lines!(
			resolved,
			6,
			[1, 1, 1, 2, 2, 2],
			vec![vec!["A"], vec!["B"], vec!["C"], vec!["D", "A"], vec!["D", "B"], vec!["D", "C"]],
			vec![vec!["z"], vec!["z"], vec!["z"], vec!["y", "x"], vec!["y", "x"], vec!["y", "x"]]
		);
	}

	#[test]
	fn test_per_file_panel_flag() {
		init_tracing_test();
		#[rustfmt::skip]
		let input = vec![
			"--per-file-panels",
			"--plot", "x",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert_eq!(ctx.per_file_panels_option(), Some(true));

		let input = vec!["--per-file-panels", "false", "--plot", "x"];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert_eq!(ctx.per_file_panels_option(), Some(false));

		let input = vec!["--plot", "x"];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert_eq!(ctx.per_file_panels_option(), None);
	}

	#[test]
	fn test_args_or_config_file() {
		init_tracing_test();

		#[rustfmt::skip]
		let input = vec![
			"--config", "tests/test-files/config01.toml",
			"--per-file-panels",
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert_eq!(ctx.per_file_panels_option(), Some(true));
		assert!(ctx.per_file_panels());

		#[rustfmt::skip]
		let input = vec![
			"--config", "tests/test-files/config01-with-per-file-panel.toml"
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert!(ctx.per_file_panels());

		#[rustfmt::skip]
		let input = vec![
			"--config", "tests/test-files/config01-with-per-file-panel.toml",
			"--per-file-panels", "false"
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert!(!ctx.per_file_panels());

		#[rustfmt::skip]
		let input = vec![
			"--config", "tests/test-files/config01-with-timestamp-format.toml"
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert_eq!(*ctx.timestamp_format(), TimestampFormat::from("%s"));

		#[rustfmt::skip]
		let input = vec![
			"--config", "tests/test-files/config01-with-timestamp-format.toml",
			"--timestamp-format", "%j %I:%M:%S %p"
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert_eq!(*ctx.timestamp_format(), TimestampFormat::from("%j %I:%M:%S %p"));

		#[rustfmt::skip]
		let input = vec![
			"--config", "tests/test-files/config01-with-timestamp-format-with-per-file-panel.toml",
			"--per-file-panels", "false",
			"--timestamp-format", "%j %I:%M:%S %p"
		];
		let (config, ctx) = graph_cli_builder::build_from_cli_args(input).unwrap();
		assert!(!ctx.per_file_panels());
		assert_eq!(*ctx.timestamp_format(), TimestampFormat::from("%j %I:%M:%S %p"));
	}

	#[test]
	#[should_panic(expected = "unknown field")]
	fn test_bad_config_file() {
		let input = vec!["--config", "tests/test-files/invalid-config.toml"];
		let res = graph_cli_builder::build_from_cli_args(input);
		if res.is_err() {
			panic!("{:?}", res.err());
		}
	}

	#[test]
	fn test_expand_graph_config_minimal() {
		let config = GraphConfig {
			panels: vec![Panel {
				params: PanelParams::default(),
				lines: vec![
					Line {
						data_source: DataSource::FieldValue(FieldCaptureSpec {
							guard: None,
							field: "duration".into(),
						}),
						params: LineParams::default(),
					},
					Line {
						data_source: DataSource::EventCount {
							guard: None,
							pattern: "ERROR".into(),
						},
						params: LineParams::default(),
					},
				],
			}],
		};

		let ctx = GraphFullContext::new_with_input(vec!["log1.txt".into(), "log2.txt".into()]);

		let resolved = expand_graph_config_with_ctx(&config, &ctx).unwrap();
		assert_eq!(resolved.panels.len(), 1);
		assert_eq!(resolved.panels[0].lines.len(), 4); // 2 lines * 2 files
		assert_eq!(resolved.panels[0].lines[0].source.file_name().to_string_lossy(), "log1.txt");
		assert_eq!(resolved.panels[0].lines[1].source.file_name().to_string_lossy(), "log2.txt");
		assert_eq!(resolved.panels[0].lines[2].source.file_name().to_string_lossy(), "log1.txt");
		assert_eq!(resolved.panels[0].lines[3].source.file_name().to_string_lossy(), "log2.txt");
	}

	#[test]
	fn test_resolved_source_match_input() {
		let a = PathBuf::from("a");
		let b = PathBuf::from("b");
		let c = PathBuf::from("c");
		let x = PathBuf::from("x");

		let line_source_id = LineSource::FileId(3);
		let line_source_fn = LineSource::FileName(x.clone());
		let line_source_all = LineSource::AllInputFiles;

		assert_eq!(
			ResolvedSource::try_match_input(line_source_id.clone(), 3, &c)
				.unwrap()
				.file_name(),
			&c
		);
		assert!(ResolvedSource::try_match_input(line_source_id.clone(), 2, &c).is_none());

		assert!(ResolvedSource::try_match_input(line_source_fn.clone(), 2, &c).is_none());
		assert_eq!(
			ResolvedSource::try_from_explicit(line_source_fn.clone()).unwrap().file_name(),
			&x
		);

		assert_eq!(
			ResolvedSource::try_match_input(line_source_all.clone(), 1, &a)
				.unwrap()
				.file_name(),
			&a
		);
		assert_eq!(
			ResolvedSource::try_match_input(line_source_all.clone(), 2, &b)
				.unwrap()
				.file_name(),
			&b
		);
		assert_eq!(
			ResolvedSource::try_match_input(line_source_all.clone(), 3, &c)
				.unwrap()
				.file_name(),
			&c
		);
	}
}