Skip to main content

jlf_core/
config.rs

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
32/// Read and parse one config file, turning a TOML error into a message that
33/// names the file and points at the exact offending span (the `toml` crate
34/// renders a `line | … | ^^^` caret under the error).
35fn 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
47/// How a recipe's `out` string is interpreted, decided purely by its shape.
48enum Content<'a> {
49    /// A `$`-DSL template, verbatim literal text, or a whitespace-only string
50    /// (e.g. a `"\n"` separator). Rendered as-is — whitespace can be
51    /// meaningful.
52    Template(&'a str),
53    /// A single `field[:mods]` value accessor — the only shape usable as a
54    /// value (`@name` in filters/summaries).
55    Field {
56        path: &'a str,
57        mods: Option<&'a str>,
58    },
59    /// An `a,b,c` list of columns (a table / view projection).
60    Columns(Vec<&'a str>),
61}
62
63/// Whether `s` looks like a value accessor path — a fallback chain of dotted
64/// field names (`latency_ms|duration|elapsed`, `fields.message`, `..`).
65/// Anything with other characters (spaces, brackets, `/`) is treated as literal
66/// text.
67fn 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/// A unified recipe: one named, reusable definition that can act as a template
75/// fragment (`{@name}`), a saved command (`@name` / `-p`), a named field, or a
76/// custom output format. See the README (Recipes and configuration). Recipes
77/// translate down to the existing variable/preset/format machinery.
78#[derive(Debug, Default, Clone, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct Recipe {
81    /// The one content key: what the recipe shows, decided by shape — a `$…`
82    /// template, an `a,b,c` column list, or a single `field[:mods]` value
83    /// accessor.
84    pub out: Option<String>,
85    /// Records to keep (`key=value`, space-separated).
86    pub filter: Option<String>,
87    pub redact: Option<String>,
88    /// Reference an output format (built-in `csv`/`tsv`/`md` or another
89    /// recipe).
90    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    /// Inherit another recipe (`@other` or `other`), then override its keys.
99    pub base: Option<String>,
100    /// Conditional overrides from `[recipe.NAME.<flag>]` sub-tables: when the
101    /// flag holds, these keys override. Only the three CLI/config flags exist.
102    #[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    /// Classify `out` by shape. A `$` (or a whitespace-only string) is a
112    /// template used verbatim; a top-level `:` before any comma is a single
113    /// styled field; a top-level comma is a column list; a bare field-path is a
114    /// value accessor; anything else (literal text) is a template rendered
115    /// as-is.
116    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            // `:` before any comma -> a single field with (comma-separated)
126            // mods, as long as the part before the `:` is a field
127            // path (else literal).
128            (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            // a top-level comma -> a plain column list.
138            (_, Some(_)) => Content::Columns(
139                trimmed
140                    .split(',')
141                    .map(str::trim)
142                    .filter(|s| !s.is_empty())
143                    .collect(),
144            ),
145            // a bare field path -> a value accessor; any other literal string
146            // is a verbatim template.
147            _ if is_field_path(trimmed) => Content::Field {
148                path: trimmed,
149                mods: None,
150            },
151            _ => Content::Template(raw),
152        })
153    }
154
155    /// The string used when this recipe is inlined (`${@name}`): a template
156    /// verbatim, else an optional `${?field[:mods]}`, else a `${?a} ${?b}` from
157    /// the columns. Optional by default, so an absent field collapses its space
158    /// — you write `${@name}`, not `${?@name}`.
159    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    /// The value accessor for `@name` in filter/summary positions. Only a
175    /// single-field `out` is a value; templates and column lists are not.
176    fn accessor(&self) -> Option<String> {
177        match self.content()? {
178            Content::Field { path, .. } => Some(path.to_owned()),
179            _ => None,
180        }
181    }
182
183    /// The template used when the recipe is run as a preset (`@name`),
184    /// non-optional so a bare value still renders. A format renders through its
185    /// own format map and a column list drives `$cols`/tables, so both are
186    /// `None` here (the columns travel via [`Self::preset_columns`]).
187    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    /// The `a,b,c` columns a preset selects, when `out` is a column list.
202    fn preset_columns(&self) -> Option<String> {
203        match self.content()? {
204            Content::Columns(cols) => Some(cols.join(",")),
205            _ => None,
206        }
207    }
208
209    /// Shallow-merge `other`'s set keys over `self` (used for base inheritance
210    /// and conditional overrides). `self` is the lower-priority base.
211    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    /// The conditional override sub-recipe for an active flag, if present.
222    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    /// Does this recipe describe a custom output format — one with a global
232    /// `escape`, or an `out` that emits its own frame/table via
233    /// `$rows(`/`$cols(`?
234    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    /// Output formats: the built-ins `csv`/`tsv`/`md` plus any `[recipe.*]`
250    /// with an `escape` or an `out` that frames its own table via
251    /// `$rows(`/`$cols(`.
252    #[serde(default, rename = "format")]
253    pub formats: HashMap<String, FormatDef>,
254    /// Saved argument bundles from `[preset.NAME]` tables.
255    #[serde(default, rename = "preset")]
256    pub presets: HashMap<String, PresetDef>,
257    /// Body-only recipe shorthand: `[recipes]` maps name -> body string.
258    #[serde(default)]
259    pub recipes: HashMap<String, String>,
260    /// Full recipes from `[recipe.NAME]` tables.
261    #[serde(default, rename = "recipe")]
262    pub recipe: HashMap<String, Recipe>,
263    /// Field recipes as `name -> value accessor` (e.g. `latency ->
264    /// latency_ms|duration|elapsed`), so `@name` resolves in filter and
265    /// summary positions. Filled by `resolve_recipes`; not read from
266    /// config directly.
267    #[serde(skip)]
268    pub field_aliases: HashMap<String, String>,
269}
270
271/// The built-in `csv`/`tsv`/`md` output formats, as single `$`-DSL templates:
272/// a `$cols( $key )` header row, then `$rows( … )` per record. Seeded so
273/// they're runnable by name (`@csv`, `--format md`) and overridable by a
274/// `[recipe.*]`.
275pub 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/// A custom output format: one `$`-DSL `body` template (a `$rows( … )` marks
297/// the per-record part; text around it prints once), with interpolated values
298/// escaped per `escape`.
299#[derive(Debug, Default, Clone, Deserialize)]
300pub struct FormatDef {
301    pub escape: Option<String>,
302    pub body: String,
303}
304
305/// A saved bundle of arguments invoked by name (`@name` / `-p name`). Keys
306/// mirror the explicit flag forms; explicit CLI args layer on top.
307#[derive(Debug, Default, Clone, Deserialize)]
308pub struct PresetDef {
309    /// Filters, as a single `key=value ...` string (space-separated).
310    #[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    // summary verbs: at most one is set
318    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
326/// The built-in default template variables, used when no config overrides them.
327/// Shared by the CLI and the TUI so both render records identically.
328///
329/// The recipe-style form (see README): `output` joins reusable field
330/// variables; each field is optional (`{?…}`) so an absent one collapses its
331/// space, and the separator before the JSON is chosen by the `compact` flag.
332/// Overriding any field variable (e.g. `-v level=…`) still recolors the output.
333pub 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    /// The default output template — a `$`-DSL string, usually `${@output}`.
417    /// Named `out` to match a recipe's content key.
418    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        // Workspace-defined formats/presets/recipes override same-named base
450        // ones.
451        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    /// Translate recipes (`[recipes]` + `[recipe.NAME]`) into the variable,
479    /// preset, and format maps the rest of the engine consumes. `active` is the
480    /// set of currently-true condition flags (e.g. `["compact"]`), used to
481    /// apply `[recipe.NAME.<cond>]` overrides. Idempotent; call once flags
482    /// are known.
483    pub fn resolve_recipes(&mut self, active: &[&str]) {
484        // Seed the built-in csv/tsv/md formats first, so a user recipe of the
485        // same name can override them. Each is also runnable by name (`@csv`).
486        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        // Body-only shorthand: a variable, and a runnable preset
497        // (template=body).
498        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    /// Resolve a recipe by name: apply `base` inheritance (depth-first) then
517    /// the active conditional overrides. `stack` guards against base
518    /// cycles.
519    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(); // cycle: stop inheriting
530        }
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    /// Register a resolved recipe as a variable (inline), a preset (run),
549    /// and/or a custom output format (header/body/footer).
550    fn install_recipe(&mut self, name: &str, r: &Recipe) {
551        // A single-field recipe is a named value accessor, usable as `@name` in
552        // filter and summary positions as well as `${@name}` in templates.
553        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        // Any recipe with content is runnable as a preset. A format recipe's
566        // body lives in the formats map, and a column list drives `$cols`, so
567        // neither sets a template (that would shadow the columns).
568        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            // A format recipe runs through its own named output format.
575            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    // TODO: allow env var override
600    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
607/// This function starts searching the FS upward from the CWD
608/// and returns the first directory that contains either `.git`, `.svn`, `.jj`
609/// If no workspace was found returns (CWD, true).
610/// Otherwise (workspace, false) is returned
611fn 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
627// Get the current working directory.
628// This information is managed internally as the call to std::env::current_dir
629// might fail if the cwd has been deleted.
630fn current_working_dir() -> PathBuf {
631    // implementation of crossplatform pwd -L
632    // we want pwd -L so that symlinked directories are handled correctly
633    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        // Field recipes are optional by default, so `${@host}` collapses when
679        // absent.
680        assert_eq!(var(&c, "host"), Some("${?host|hostname:dimmed}"));
681    }
682
683    #[test]
684    fn out_key_classified_by_shape() {
685        // single field with inline mods -> optional value + accessor (mods
686        // stripped)
687        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        // comma list -> columns (not a value accessor)
701        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        // `$` -> template (not a value accessor)
716        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        // and it's runnable as a preset that points at its own format
749        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        // child overrides out, inherits filter
773        assert_eq!(c.presets["child"].template.as_deref(), Some("${b}"));
774        assert_eq!(c.presets["child"].filter.as_deref(), Some("x=1"));
775    }
776}