1use std::{collections::HashMap, fmt, fs, path::PathBuf};
2
3use etcetera::{choose_base_strategy, BaseStrategy};
4use serde::Deserialize;
5
6pub fn get_config() -> color_eyre::Result<ConfigFile> {
7 let config_file = config_dir().join("config.toml");
8 let mut config = if config_file.exists() {
9 parse_config_file(&config_file)?
10 } else {
11 ConfigFile::default()
12 };
13
14 let ws_dir = find_workspace();
15 let ws_config_file1 = ws_dir.join("jlf.toml");
16 let ws_config_file2 = ws_dir.join(".jlf.toml");
17 let ws_config = if ws_config_file1.exists() {
18 Some(parse_config_file(&ws_config_file1)?)
19 } else if ws_config_file2.exists() {
20 Some(parse_config_file(&ws_config_file2)?)
21 } else {
22 None
23 };
24
25 if let Some(ws_config) = ws_config {
26 config.merge(ws_config);
27 }
28
29 Ok(config)
30}
31
32fn parse_config_file(path: &std::path::Path) -> color_eyre::Result<ConfigFile> {
36 let raw = fs::read_to_string(path).map_err(|e| {
37 color_eyre::eyre::eyre!(
38 "failed to read config `{}`: {e}",
39 path.display()
40 )
41 })?;
42 toml::from_str(&raw).map_err(|e| {
43 color_eyre::eyre::eyre!("invalid config `{}`:\n\n{e}", path.display())
44 })
45}
46
47enum Content<'a> {
49 Template(&'a str),
53 Field {
56 path: &'a str,
57 mods: Option<&'a str>,
58 },
59 Columns(Vec<&'a str>),
61}
62
63fn is_field_path(s: &str) -> bool {
68 !s.is_empty()
69 && s.bytes().all(|b| {
70 b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'|' | b'-')
71 })
72}
73
74#[derive(Debug, Default, Clone, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct Recipe {
81 pub out: Option<String>,
85 pub filter: Option<String>,
87 pub redact: Option<String>,
88 pub format: Option<String>,
91 pub escape: Option<String>,
92 pub count: Option<String>,
93 pub stats: Option<String>,
94 pub top: Option<String>,
95 pub uniq: Option<String>,
96 pub by: Option<String>,
97 pub n: Option<usize>,
98 pub base: Option<String>,
100 #[serde(default)]
103 pub compact: Option<Box<Recipe>>,
104 #[serde(default)]
105 pub no_color: Option<Box<Recipe>>,
106 #[serde(default)]
107 pub strict: Option<Box<Recipe>>,
108}
109
110impl Recipe {
111 fn content(&self) -> Option<Content<'_>> {
117 let raw = self.out.as_deref()?;
118 let trimmed = raw.trim();
119 if raw.contains('$') || trimmed.is_empty() {
120 return Some(Content::Template(raw));
121 }
122 let colon = trimmed.find(':');
123 let comma = trimmed.find(',');
124 Some(match (colon, comma) {
125 (Some(c), maybe)
129 if maybe.is_none_or(|m| c < m)
130 && is_field_path(trimmed[..c].trim()) =>
131 {
132 Content::Field {
133 path: trimmed[..c].trim(),
134 mods: Some(trimmed[c + 1..].trim()),
135 }
136 }
137 (_, Some(_)) => Content::Columns(
139 trimmed
140 .split(',')
141 .map(str::trim)
142 .filter(|s| !s.is_empty())
143 .collect(),
144 ),
145 _ if is_field_path(trimmed) => Content::Field {
148 path: trimmed,
149 mods: None,
150 },
151 _ => Content::Template(raw),
152 })
153 }
154
155 fn inline_body(&self) -> Option<String> {
160 Some(match self.content()? {
161 Content::Template(t) => t.to_owned(),
162 Content::Field { path, mods } => match mods {
163 Some(m) => format!("${{?{path}:{m}}}"),
164 None => format!("${{?{path}}}"),
165 },
166 Content::Columns(cols) => cols
167 .iter()
168 .map(|c| format!("${{?{c}}}"))
169 .collect::<Vec<_>>()
170 .join(" "),
171 })
172 }
173
174 fn accessor(&self) -> Option<String> {
177 match self.content()? {
178 Content::Field { path, .. } => Some(path.to_owned()),
179 _ => None,
180 }
181 }
182
183 fn preset_template(&self) -> Option<String> {
188 if self.is_format() {
189 return None;
190 }
191 match self.content()? {
192 Content::Template(t) => Some(t.to_owned()),
193 Content::Field { path, mods } => Some(match mods {
194 Some(m) => format!("${{{path}:{m}}}"),
195 None => format!("${{{path}}}"),
196 }),
197 Content::Columns(_) => None,
198 }
199 }
200
201 fn preset_columns(&self) -> Option<String> {
203 match self.content()? {
204 Content::Columns(cols) => Some(cols.join(",")),
205 _ => None,
206 }
207 }
208
209 fn overlay(&mut self, other: &Recipe) {
212 macro_rules! take {
213 ($($f:ident),*) => { $( if other.$f.is_some() { self.$f = other.$f.clone(); } )* };
214 }
215 take!(
216 out, filter, redact, format, escape, count, stats, top, uniq, by,
217 n, base
218 );
219 }
220
221 fn override_for(&self, flag: &str) -> Option<&Recipe> {
223 match flag {
224 "compact" => self.compact.as_deref(),
225 "no_color" => self.no_color.as_deref(),
226 "strict" => self.strict.as_deref(),
227 _ => None,
228 }
229 }
230
231 fn is_format(&self) -> bool {
235 self.escape.is_some()
236 || self
237 .out
238 .as_deref()
239 .is_some_and(|b| b.contains("$rows(") || b.contains("$cols("))
240 }
241}
242
243#[derive(Debug, Default, Deserialize)]
244pub struct ConfigFile {
245 #[serde(default)]
246 pub config: Config,
247 #[serde(default, deserialize_with = "de_map_to_list")]
248 pub variables: Option<Vec<(String, String)>>,
249 #[serde(default, rename = "format")]
253 pub formats: HashMap<String, FormatDef>,
254 #[serde(default, rename = "preset")]
256 pub presets: HashMap<String, PresetDef>,
257 #[serde(default)]
259 pub recipes: HashMap<String, String>,
260 #[serde(default, rename = "recipe")]
262 pub recipe: HashMap<String, Recipe>,
263 #[serde(skip)]
268 pub field_aliases: HashMap<String, String>,
269}
270
271pub fn builtin_formats() -> HashMap<String, FormatDef> {
276 HashMap::from([
277 ("csv".to_owned(), FormatDef {
278 escape: None,
279 body: "$cols( $key ),*\n$rows( $cols( ${value:csv} ),* )*"
280 .to_owned(),
281 }),
282 ("tsv".to_owned(), FormatDef {
283 escape: None,
284 body: "$cols( $key )\t*\n$rows( $cols( ${value:tsv} )\t* )*"
285 .to_owned(),
286 }),
287 ("md".to_owned(), FormatDef {
288 escape: None,
289 body: "| $cols( $key )\" | \"* |\n| $cols( --- )\" | \"* \
290 |\n$rows( | $cols( ${value:md} )\" | \"* | )*"
291 .to_owned(),
292 }),
293 ])
294}
295
296#[derive(Debug, Default, Clone, Deserialize)]
300pub struct FormatDef {
301 pub escape: Option<String>,
302 pub body: String,
303}
304
305#[derive(Debug, Default, Clone, Deserialize)]
308pub struct PresetDef {
309 #[serde(rename = "where")]
311 pub filter: Option<String>,
312 pub template: Option<String>,
313 pub fields: Option<String>,
314 pub redact: Option<String>,
315 pub compact: Option<bool>,
316 pub format: Option<String>,
317 pub count: Option<String>,
319 pub stats: Option<String>,
320 pub top: Option<String>,
321 pub uniq: Option<String>,
322 pub by: Option<String>,
323 pub n: Option<usize>,
324}
325
326pub fn default_variables() -> Vec<(String, String)> {
334 [
335 (
336 "output",
337 "${@timestamp}${@level}${@message}$config(compact => \
338 \\t)$else(\\n)${@data}",
339 ),
340 ("timestamp", "${?timestamp:dimmed} "),
341 (
342 "level",
343 concat!(
344 "$match(lvl|level|severity\n",
345 r#" $when("ERROR"|"error" => ${value:fg=red})"#,
346 "\n",
347 r#" $when("WARN"|"warn" => ${value:fg=yellow})"#,
348 "\n",
349 r#" $when("INFO"|"info" => ${value:fg=cyan})"#,
350 "\n",
351 r#" $when("DEBUG"|"debug" => ${value:fg=green})"#,
352 "\n",
353 r#" $when("TRACE"|"trace" => ${value:fg=cyan,dimmed})"#,
354 "\n",
355 r#" $else(${value})"#,
356 "\n) ",
357 ),
358 ),
359 ("message", "${?message|msg|body|fields.message}"),
360 ("data", "${?..:json}"),
361 ]
362 .into_iter()
363 .map(|(k, v)| (k.to_owned(), v.to_owned()))
364 .collect()
365}
366
367fn de_map_to_list<'de, D>(
368 de: D,
369) -> Result<Option<Vec<(String, String)>>, D::Error>
370where
371 D: serde::Deserializer<'de>,
372{
373 struct Visitor;
374
375 impl<'de> serde::de::Visitor<'de> for Visitor {
376 type Value = Option<Vec<(String, String)>>;
377
378 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
379 write!(formatter, "A hex encoded OpId")
380 }
381
382 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
383 where
384 D: serde::Deserializer<'de>,
385 {
386 deserializer.deserialize_map(Visitor)
387 }
388
389 fn visit_none<E>(self) -> Result<Self::Value, E>
390 where
391 E: serde::de::Error,
392 {
393 Ok(None)
394 }
395
396 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
397 where
398 A: serde::de::MapAccess<'de>,
399 {
400 let mut list =
401 map.size_hint().map(Vec::with_capacity).unwrap_or_default();
402
403 while let Some((k, v)) = map.next_entry()? {
404 list.push((k, v));
405 }
406
407 Ok(Some(list))
408 }
409 }
410
411 de.deserialize_any(Visitor)
412}
413
414#[derive(Debug, Default, Deserialize)]
415pub struct Config {
416 pub out: Option<String>,
419 pub compact: Option<bool>,
420 pub no_color: Option<bool>,
421 pub strict: Option<bool>,
422}
423
424impl ConfigFile {
425 fn merge(&mut self, other: Self) {
426 let Self {
427 config: config2,
428 variables: variables2,
429 formats: formats2,
430 presets: presets2,
431 recipes: recipes2,
432 recipe: recipe2,
433 field_aliases: _,
434 } = other;
435
436 if let Some(out) = config2.out {
437 self.config.out = Some(out);
438 }
439 if let Some(compact) = config2.compact {
440 self.config.compact = Some(compact);
441 }
442 if let Some(no_color) = config2.no_color {
443 self.config.no_color = Some(no_color);
444 }
445 if let Some(strict) = config2.strict {
446 self.config.strict = Some(strict);
447 }
448
449 self.formats.extend(formats2);
452 self.presets.extend(presets2);
453 self.recipes.extend(recipes2);
454 self.recipe.extend(recipe2);
455
456 match (&mut self.variables, variables2) {
457 (_, None) => (),
458 (v1, Some(v2)) => {
459 if let Some(v1) = v1 {
460 for (k2, v2) in v2 {
461 let v = v1
462 .iter_mut()
463 .find_map(|(k, v)| (k == &k2).then_some(v));
464
465 if let Some(v) = v {
466 *v = v2;
467 } else {
468 v1.push((k2, v2));
469 }
470 }
471 } else {
472 *v1 = Some(v2);
473 }
474 }
475 }
476 }
477
478 pub fn resolve_recipes(&mut self, active: &[&str]) {
484 for (name, def) in builtin_formats() {
487 self.formats.entry(name.clone()).or_insert(def);
488 self.presets
489 .entry(name.clone())
490 .or_insert_with(|| PresetDef {
491 format: Some(name),
492 ..Default::default()
493 });
494 }
495
496 let shorthand: Vec<(String, String)> = self.recipes.drain().collect();
499 for (name, body) in shorthand {
500 self.set_variable(name.clone(), body.clone());
501 self.presets.entry(name).or_insert_with(|| PresetDef {
502 template: Some(body),
503 ..Default::default()
504 });
505 }
506
507 let recipes: Vec<(String, Recipe)> =
508 self.recipe.clone().into_iter().collect();
509 for (name, _) in &recipes {
510 let resolved = self.resolve_one(name, active, &mut Vec::new());
511 self.install_recipe(name, &resolved);
512 }
513 self.recipe.clear();
514 }
515
516 fn resolve_one(
520 &self,
521 name: &str,
522 active: &[&str],
523 stack: &mut Vec<String>,
524 ) -> Recipe {
525 let Some(raw) = self.recipe.get(name) else {
526 return Recipe::default();
527 };
528 if stack.iter().any(|n| n == name) {
529 return raw.clone(); }
531 stack.push(name.to_owned());
532
533 let mut resolved = Recipe::default();
534 if let Some(base) = &raw.base {
535 let base_name = base.strip_prefix('@').unwrap_or(base);
536 resolved = self.resolve_one(base_name, active, stack);
537 }
538 resolved.overlay(raw);
539 for cond in active {
540 if let Some(ov) = raw.override_for(cond) {
541 resolved.overlay(ov);
542 }
543 }
544 stack.pop();
545 resolved
546 }
547
548 fn install_recipe(&mut self, name: &str, r: &Recipe) {
551 if let Some(accessor) = r.accessor() {
554 self.field_aliases.insert(name.to_owned(), accessor);
555 }
556 if let Some(body) = r.inline_body() {
557 self.set_variable(name.to_owned(), body);
558 }
559 if r.is_format() {
560 self.formats.insert(name.to_owned(), FormatDef {
561 escape: r.escape.clone(),
562 body: r.inline_body().unwrap_or_default(),
563 });
564 }
565 let preset = PresetDef {
569 filter: r.filter.clone(),
570 template: r.preset_template(),
571 fields: r.preset_columns(),
572 redact: r.redact.clone(),
573 compact: None,
574 format: r
576 .format
577 .clone()
578 .or_else(|| r.is_format().then(|| name.to_owned())),
579 count: r.count.clone(),
580 stats: r.stats.clone(),
581 top: r.top.clone(),
582 uniq: r.uniq.clone(),
583 by: r.by.clone(),
584 n: r.n,
585 };
586 self.presets.insert(name.to_owned(), preset);
587 }
588
589 fn set_variable(&mut self, key: String, value: String) {
590 let vars = self.variables.get_or_insert_with(Vec::new);
591 match vars.iter_mut().find(|(k, _)| *k == key) {
592 Some((_, v)) => *v = value,
593 None => vars.push((key, value)),
594 }
595 }
596}
597
598fn config_dir() -> PathBuf {
599 let strategy =
601 choose_base_strategy().expect("Unable to find the config directory!");
602 let mut path = strategy.config_dir();
603 path.push("jlf");
604 path
605}
606
607fn find_workspace() -> PathBuf {
612 let current_dir = current_working_dir();
613 for ancestor in current_dir.ancestors() {
614 if ancestor.join(".git").exists()
615 || ancestor.join("jlf.toml").exists()
616 || ancestor.join(".jlf.toml").exists()
617 || ancestor.join(".svn").exists()
618 || ancestor.join(".jj").exists()
619 {
620 return ancestor.to_owned();
621 }
622 }
623
624 current_dir
625}
626
627fn current_working_dir() -> PathBuf {
631 let mut cwd = std::env::current_dir()
634 .expect("Couldn't determine current working directory");
635
636 let pwd = std::env::var_os("PWD");
637 #[cfg(windows)]
638 let pwd = pwd.or_else(|| std::env::var_os("CD"));
639
640 if let Some(pwd) = pwd.map(PathBuf::from) {
641 if pwd.canonicalize().ok().as_ref() == Some(&cwd) {
642 cwd = pwd;
643 }
644 }
645
646 cwd
647}
648
649#[cfg(test)]
650mod tests {
651 use super::*;
652
653 fn parse(s: &str) -> ConfigFile { toml::from_str(s).unwrap() }
654
655 fn var<'a>(c: &'a ConfigFile, name: &str) -> Option<&'a str> {
656 c.variables
657 .as_ref()?
658 .iter()
659 .find(|(k, _)| k == name)
660 .map(|(_, v)| v.as_str())
661 }
662
663 #[test]
664 fn shorthand_recipe_becomes_variable_and_preset() {
665 let mut c = parse("[recipes]\noneline = \"${level} ${msg}\"\n");
666 c.resolve_recipes(&[]);
667 assert_eq!(var(&c, "oneline"), Some("${level} ${msg}"));
668 assert_eq!(
669 c.presets["oneline"].template.as_deref(),
670 Some("${level} ${msg}")
671 );
672 }
673
674 #[test]
675 fn single_field_out_becomes_value_variable() {
676 let mut c = parse("[recipe.host]\nout = \"host|hostname:dimmed\"\n");
677 c.resolve_recipes(&[]);
678 assert_eq!(var(&c, "host"), Some("${?host|hostname:dimmed}"));
681 }
682
683 #[test]
684 fn out_key_classified_by_shape() {
685 let mut field =
688 parse("[recipe.ts]\nout = \"timestamp|ts:dimmed,red\"\n");
689 field.resolve_recipes(&[]);
690 assert_eq!(var(&field, "ts"), Some("${?timestamp|ts:dimmed,red}"));
691 assert_eq!(
692 field.field_aliases.get("ts").map(String::as_str),
693 Some("timestamp|ts")
694 );
695 assert_eq!(
696 field.presets["ts"].template.as_deref(),
697 Some("${timestamp|ts:dimmed,red}")
698 );
699
700 let mut cols =
702 parse("[recipe.req]\nout = \"timestamp,level,message\"\n");
703 cols.resolve_recipes(&[]);
704 assert_eq!(
705 var(&cols, "req"),
706 Some("${?timestamp} ${?level} ${?message}")
707 );
708 assert_eq!(
709 cols.presets["req"].fields.as_deref(),
710 Some("timestamp,level,message")
711 );
712 assert_eq!(cols.presets["req"].template, None);
713 assert!(!cols.field_aliases.contains_key("req"));
714
715 let mut tpl =
717 parse("[recipe.lvl]\nout = \"$match(level $else(${value}))\"\n");
718 tpl.resolve_recipes(&[]);
719 assert!(!tpl.field_aliases.contains_key("lvl"));
720 assert_eq!(
721 tpl.presets["lvl"].template.as_deref(),
722 Some("$match(level $else(${value}))")
723 );
724 }
725
726 #[test]
727 fn filter_body_recipe_becomes_preset() {
728 let mut c = parse(
729 "[recipe.errors]\nfilter = \"level=error\"\nout = \"${ts} \
730 ${msg}\"\n",
731 );
732 c.resolve_recipes(&[]);
733 let p = &c.presets["errors"];
734 assert_eq!(p.filter.as_deref(), Some("level=error"));
735 assert_eq!(p.template.as_deref(), Some("${ts} ${msg}"));
736 }
737
738 #[test]
739 fn format_recipe_becomes_format() {
740 let mut c = parse(
741 "[recipe.report]\nescape = \"html\"\nout = \"<table>\\n$rows( \
742 <r>${msg}</r> )*</table>\"\n",
743 );
744 c.resolve_recipes(&[]);
745 let f = &c.formats["report"];
746 assert_eq!(f.escape.as_deref(), Some("html"));
747 assert_eq!(f.body, "<table>\n$rows( <r>${msg}</r> )*</table>");
748 assert_eq!(c.presets["report"].format.as_deref(), Some("report"));
750 }
751
752 #[test]
753 fn conditional_override_applies_when_active() {
754 let toml =
755 "[recipe.sep]\nout = \"\\n\"\n[recipe.sep.compact]\nout = \" \"\n";
756 let mut normal = parse(toml);
757 normal.resolve_recipes(&[]);
758 assert_eq!(var(&normal, "sep"), Some("\n"));
759
760 let mut compact = parse(toml);
761 compact.resolve_recipes(&["compact"]);
762 assert_eq!(var(&compact, "sep"), Some(" "));
763 }
764
765 #[test]
766 fn base_inheritance_overlays_keys() {
767 let mut c = parse(
768 "[recipe.base]\nout = \"${a}\"\nfilter = \
769 \"x=1\"\n[recipe.child]\nbase = \"@base\"\nout = \"${b}\"\n",
770 );
771 c.resolve_recipes(&[]);
772 assert_eq!(c.presets["child"].template.as_deref(), Some("${b}"));
774 assert_eq!(c.presets["child"].filter.as_deref(), Some("x=1"));
775 }
776}