flodl_cli/config/command.rs
1//! Sub-command config loading from registered command directories.
2
3use std::path::{Path, PathBuf};
4
5use super::loading::{CONFIG_NAMES, EXAMPLE_SUFFIXES, try_copy_example};
6use super::schema::{CommandConfig, validate_schema};
7
8/// Load a command config from a sub-directory.
9///
10/// Applies the same `.example`/`.dist` fallback as [`super::loading::find_config`]. If a
11/// `schema:` block is present, validates it before returning.
12pub fn load_command(dir: &Path) -> Result<CommandConfig, String> {
13 load_command_with_env(dir, None)
14}
15
16/// Load a sub-command config with an optional environment overlay.
17///
18/// Applies the same `.example`/`.dist` fallback as [`super::loading::find_config`] to locate
19/// the base file, then deep-merges a sibling `fdl.<env>.yml` overlay if one
20/// exists. A *missing* overlay is silently accepted here (different from
21/// [`super::loading::load_project_with_env`]) — envs declared at the project root don't
22/// have to exist for every sub-command.
23pub fn load_command_with_env(dir: &Path, env: Option<&str>) -> Result<CommandConfig, String> {
24 // Resolve the base config path (with .example fallback, same as before).
25 let mut base_path: Option<PathBuf> = None;
26 for name in CONFIG_NAMES {
27 let path = dir.join(name);
28 if path.is_file() {
29 base_path = Some(path);
30 break;
31 }
32 }
33 if base_path.is_none() {
34 for name in CONFIG_NAMES {
35 for suffix in EXAMPLE_SUFFIXES {
36 let example = dir.join(format!("{name}{suffix}"));
37 if example.is_file() {
38 let target = dir.join(name);
39 let src = if try_copy_example(&example, &target) {
40 target
41 } else {
42 example
43 };
44 base_path = Some(src);
45 break;
46 }
47 }
48 if base_path.is_some() {
49 break;
50 }
51 }
52 }
53 let base_path = base_path.ok_or_else(|| format!("no fdl.yml found in {}", dir.display()))?;
54
55 // Layered load: base chain + optional env overlay chain. Both sides
56 // run through `resolve_chain` so `inherit-from:` composes the same
57 // way for nested commands as for the project root.
58 let mut layers = crate::overlay::resolve_chain(&base_path)?;
59 if let Some(name) = env
60 && let Some(p) = crate::overlay::find_env_file(&base_path, name)
61 {
62 layers.extend(crate::overlay::resolve_chain(&p)?);
63 }
64 let mut seen = std::collections::HashSet::new();
65 layers.retain(|(path, _)| seen.insert(path.clone()));
66 let merged =
67 crate::overlay::merge_layers(layers.into_iter().map(|(_, v)| v).collect::<Vec<_>>());
68 // Re-serialize so `from_str`'s parser tracks line/col through
69 // deserialize (`from_value` discards positional info). With
70 // `deny_unknown_fields` on the config structs, unknown-key errors
71 // carry a location this way. Positions refer to the merged
72 // document, not any single source file, when overlays are in play.
73 let merged_str = serde_yaml_ng::to_string(&merged).map_err(|e| {
74 format!(
75 "{}: failed to re-serialize merged YAML for diagnostics: {e}",
76 base_path.display()
77 )
78 })?;
79 let mut cfg: CommandConfig = serde_yaml_ng::from_str(&merged_str)
80 .map_err(|e| format!("{}: {}", base_path.display(), e))?;
81
82 if let Some(schema) = &cfg.schema {
83 validate_schema(schema)
84 .map_err(|e| format!("schema error in {}/fdl.yml: {e}", dir.display()))?;
85 // Preset validation (choice values + strict unknown-key rejection)
86 // is intentionally deferred to the exec path. Load-time validation
87 // would block `fdl <cmd> --help` whenever ANY preset in the config
88 // has a typo — worse UX than letting help render and erroring only
89 // when the broken preset is actually invoked.
90 }
91
92 // Cache precedence: a valid, fresh cached schema (written by `fdl <cmd>
93 // --refresh-schema` or auto-probed below) wins over the inline YAML
94 // schema. This lets a binary become the source of truth for its own
95 // surface once it opts into the `--fdl-schema` contract. A cache that
96 // is older than the command's fdl.yml is treated as stale and skipped
97 // — the inline schema (if any) reasserts until a refresh happens.
98 let cmd_name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("_");
99 let cache = crate::schema_cache::cache_path(dir, cmd_name);
100 // Reference mtimes: everything whose edit could change the cached schema.
101 //
102 // The config file, because `entry:` might now point somewhere else — and,
103 // when the binary declares its own surface, the sources that surface is
104 // compiled from. Watching only the config meant editing a CLI struct left
105 // the cache stale with NO signal: `-h` kept rendering the previous flags
106 // until someone happened to touch the yml. Silent and repeatedly confusing,
107 // since the binary itself was correct all along.
108 let mut refs: Vec<std::path::PathBuf> = CONFIG_NAMES
109 .iter()
110 .map(|n| dir.join(n))
111 .filter(|p| p.exists())
112 .collect();
113 if cfg.compile.unwrap_or(false) {
114 refs.extend(crate::schema_cache::schema_source_refs(dir));
115 }
116 if !crate::schema_cache::is_stale(&cache, &refs) {
117 if let Some(cached) = crate::schema_cache::read_cache(&cache) {
118 cfg.schema = Some(cached);
119 }
120 } else if let Some(entry) = cfg.entry.as_deref() {
121 // Auto-probe non-cargo entries when the cache is stale or missing.
122 // Cargo entries are skipped by default — `cargo run --fdl-schema`
123 // triggers a full compile which is unacceptable latency for `-h`
124 // — unless the yml explicitly opts in via `compile: true`.
125 // Scripts and pre-built binaries are expected to handle the flag
126 // cheaply (emit JSON and exit), so probing them on demand is safe.
127 // Probe failures are swallowed: an entry that doesn't implement
128 // `--fdl-schema` simply falls through to the inline schema (or no
129 // schema) — help still renders.
130 let opts_into_compile = cfg.compile.unwrap_or(false);
131 let should_probe = !crate::schema_cache::is_cargo_entry(entry) || opts_into_compile;
132 if should_probe
133 && let Ok(probed) = crate::schema_cache::probe(entry, dir, cfg.docker.as_deref())
134 {
135 // Best-effort cache write: if the dir is read-only, the
136 // schema still applies to this invocation, we just re-probe
137 // next time. Non-fatal.
138 let _ = crate::schema_cache::write_cache(&cache, &probed);
139 cfg.schema = Some(probed);
140 }
141 }
142
143 Ok(cfg)
144}
145
146// ── Strict-mode validation ──────────────────────────────────────────────