Skip to main content

kellnr_settings/
cli.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use clap::{CommandFactory, Parser, Subcommand};
6
7use crate::compile_time_config;
8use crate::settings::{
9    Settings, SettingsArgs, SettingsError, SettingsPartial, SettingsProv, build_prov_with_cli,
10};
11
12#[derive(Parser)]
13#[command(name = "kellnr", version, about)]
14pub struct Cli {
15    /// Path to configuration file
16    #[arg(id = "config", short = 'c', long = "config", global = true)]
17    pub config_file: Option<PathBuf>,
18
19    #[command(subcommand)]
20    pub command: Option<Command>,
21}
22
23#[derive(Subcommand)]
24#[allow(clippy::large_enum_variant)]
25pub enum Command {
26    /// Start the kellnr server
27    Start {
28        /// All section flags live on `SettingsArgs`, which is generated by
29        /// `provcfg-clap::ClapArgs`. Each section is flattened in, so flags
30        /// like `--registry-data-dir` and `--log-level` appear under `start`.
31        #[command(flatten)]
32        server: SettingsArgs,
33    },
34    /// Configuration management commands
35    Config {
36        #[command(subcommand)]
37        action: ConfigAction,
38    },
39    /// Build the rustdoc of an unpacked crate. Used internally by the docs
40    /// queue to run untrusted builds in a separate process.
41    #[command(name = DOC_BUILD_SUBCOMMAND, hide = true)]
42    DocBuild {
43        /// Path to the unpacked crate
44        crate_path: PathBuf,
45
46        /// Sparse index URL that replaces the crates.io source
47        #[arg(long = DOC_BUILD_CRATESIO_INDEX_ARG)]
48        cratesio_index: Option<String>,
49    },
50}
51
52/// Name of the hidden subcommand that builds the docs of a single crate.
53pub const DOC_BUILD_SUBCOMMAND: &str = "doc-build";
54/// Long flag of [`DOC_BUILD_SUBCOMMAND`] for the crates.io index override.
55pub const DOC_BUILD_CRATESIO_INDEX_ARG: &str = "cratesio-index";
56
57#[derive(Subcommand)]
58pub enum ConfigAction {
59    /// Show the current configuration
60    Show {
61        /// Hide settings that have their default value
62        #[arg(long = "no-defaults")]
63        no_defaults: bool,
64
65        /// Show the source (toml, env, cli) for each setting
66        #[arg(long = "sources")]
67        show_sources: bool,
68    },
69    /// Initialize a new configuration file with default values
70    Init {
71        /// Output file path (default: ./kellnr.toml)
72        #[arg(short = 'o', long = "output")]
73        output: Option<PathBuf>,
74    },
75}
76
77/// Options for the `config show` command
78#[derive(Debug, Clone, Default)]
79pub struct ShowConfigOptions {
80    /// Hide settings that have their default value
81    pub no_defaults: bool,
82    /// Show the source (toml, env, cli) for each setting
83    pub show_sources: bool,
84}
85
86/// A `Settings` paired with its per-leaf `SettingsProv`. Bundled because every
87/// non-init `CliResult` variant needs both, the active values for runtime use
88/// and the provenance for source attribution (`/settings` API and
89/// `config show`). `prov` is `Arc` so it can move into the app state without a
90/// re-allocation; `SettingsProv` is also large enough that an inline owned
91/// value would balloon `CliResult`.
92pub struct ResolvedSettings {
93    pub settings: Settings,
94    pub prov: Arc<SettingsProv>,
95}
96
97pub enum CliResult {
98    RunServer(ResolvedSettings),
99    ShowConfig {
100        resolved: ResolvedSettings,
101        options: ShowConfigOptions,
102    },
103    /// `config init` writes a fresh `Settings::default()` to `output`; no
104    /// settings field is carried because there's nothing to vary per call.
105    InitConfig {
106        output: PathBuf,
107    },
108    ShowHelp,
109    /// Build the docs of a crate in the current process and exit.
110    BuildDocs {
111        crate_path: PathBuf,
112        cratesio_index: Option<String>,
113    },
114}
115
116pub fn parse_cli() -> Result<CliResult, SettingsError> {
117    let cli = Cli::parse();
118
119    match cli.command {
120        // No subcommand → print help and exit without touching the config
121        // pipeline. Doing this before any file/env resolution means
122        // `kellnr` with no args always succeeds, even if `KELLNR_CONFIG_FILE`
123        // happens to point at a missing path.
124        None => {
125            Cli::command().print_help().ok();
126            Ok(CliResult::ShowHelp)
127        }
128
129        // `config init` doesn't need to merge sources, it writes the
130        // compiled-in defaults.
131        Some(Command::Config {
132            action: ConfigAction::Init { output },
133        }) => Ok(CliResult::InitConfig {
134            output: output.unwrap_or_else(|| PathBuf::from("kellnr.toml")),
135        }),
136
137        // The docs build runs untrusted code and gets no settings on purpose.
138        Some(Command::DocBuild {
139            crate_path,
140            cratesio_index,
141        }) => Ok(CliResult::BuildDocs {
142            crate_path,
143            cratesio_index,
144        }),
145
146        Some(ref command) => build_from_command(cli.config_file, command),
147    }
148}
149
150/// Settings of the running `kellnr start`, resolved from the same command
151/// line, environment and config file as at startup. For code that runs before
152/// the settings are passed around, like the database migrations. `None` if the
153/// process was not started with valid `kellnr` arguments, for example in tests.
154#[must_use]
155pub fn settings_from_process() -> Option<Settings> {
156    let cli = Cli::try_parse().ok()?;
157    let command = cli.command?;
158    let prov = build_prov(cli.config_file, &command).ok()?;
159    Some(Settings::from(&prov))
160}
161
162fn build_prov(
163    cli_config_file: Option<PathBuf>,
164    command: &Command,
165) -> Result<SettingsProv, SettingsError> {
166    // Config file priority: CLI > env var > compile-time > None.
167    let env_config_file = std::env::var("KELLNR_CONFIG_FILE").ok();
168    let config_file: Option<PathBuf> = cli_config_file
169        .or(env_config_file.map(PathBuf::from))
170        .or(compile_time_config::KELLNR_COMPTIME__CONFIG_FILE.map(PathBuf::from));
171
172    // `SettingsPartial::from(&SettingsArgs)` is macro-generated by
173    // `provcfg-clap`: it walks every section and copies the user-supplied
174    // `Some(...)` values from clap. Unset flags stay `None`, so the CLI
175    // source contributes provenance only for fields explicitly passed.
176    let cli_partial: Option<SettingsPartial> = match command {
177        Command::Start { server } => Some(SettingsPartial::from(server)),
178        Command::Config { .. } | Command::DocBuild { .. } => None,
179    };
180
181    build_prov_with_cli(config_file.as_deref(), cli_partial)
182}
183
184fn build_from_command(
185    cli_config_file: Option<PathBuf>,
186    command: &Command,
187) -> Result<CliResult, SettingsError> {
188    let prov = build_prov(cli_config_file, command)?;
189    let resolved = ResolvedSettings {
190        settings: Settings::from(&prov),
191        prov: Arc::new(prov),
192    };
193
194    match command {
195        Command::Start { .. } => Ok(CliResult::RunServer(resolved)),
196        Command::Config {
197            action:
198                ConfigAction::Show {
199                    no_defaults,
200                    show_sources,
201                },
202        } => Ok(CliResult::ShowConfig {
203            resolved,
204            options: ShowConfigOptions {
205                no_defaults: *no_defaults,
206                show_sources: *show_sources,
207            },
208        }),
209        Command::Config {
210            action: ConfigAction::Init { .. },
211        } => unreachable!("`Init` is handled by `parse_cli` before this point"),
212        Command::DocBuild { .. } => {
213            unreachable!("`DocBuild` is handled by `parse_cli` before this point")
214        }
215    }
216}
217
218/// Map every settings leaf (dotted path) to its user-facing CLI flag(s).
219///
220/// Walks `start`'s flattened `SettingsArgs` via clap reflection so the
221/// `/settings` UI doesn't have to hand-maintain a parallel table that drifts
222/// from the actual flags. Output format: `"--registry-data-dir, -d"` (long,
223/// then short if any). Args whose id doesn't follow the `<prefix>-<field>`
224/// convention (e.g. the top-level `--config` flag, clap's built-in `--help`)
225/// are skipped, they don't correspond to a settings leaf.
226#[must_use]
227pub fn cli_flag_map() -> HashMap<String, String> {
228    let cmd = Cli::command();
229    let Some(start) = cmd.find_subcommand("start") else {
230        return HashMap::new();
231    };
232
233    let mut map = HashMap::new();
234    for arg in start.get_arguments() {
235        let id = arg.get_id().as_str();
236        let Some(path) = id_to_dotted_path(id) else {
237            continue;
238        };
239        let mut flag = String::new();
240        if let Some(long) = arg.get_long() {
241            flag.push_str("--");
242            flag.push_str(long);
243        }
244        if let Some(short) = arg.get_short() {
245            if !flag.is_empty() {
246                flag.push_str(", ");
247            }
248            flag.push('-');
249            flag.push(short);
250        }
251        if !flag.is_empty() {
252            map.insert(path, flag);
253        }
254    }
255    map
256}
257
258/// Convert a clap arg id like `registry-data-dir` into its `SettingsProv`
259/// dotted path `registry.data_dir`. Returns `None` for ids without at least
260/// one `-` (those don't come from a `clap_prefix`-ed section and so don't
261/// map to a leaf).
262fn id_to_dotted_path(id: &str) -> Option<String> {
263    let (section, rest) = id.split_once('-')?;
264    Some(format!("{section}.{}", rest.replace('-', "_")))
265}
266
267#[cfg(test)]
268mod tests {
269    use std::io::Write;
270    use std::path::Path;
271
272    use provcfg::Category;
273    use tempfile::NamedTempFile;
274
275    use super::*;
276
277    // Env-source precedence (env wins over TOML, CLI wins over env) is covered
278    // by provcfg's own suite, `full_layered_stack_defaults_toml_env_cli` in
279    // `provcfg/src/tests/defaults.rs`. Re-asserting it here would require
280    // mutating `KELLNR_*` process env vars, which means `unsafe` (edition 2024)
281    // and is forbidden workspace-wide. These tests instead pin down the
282    // kellnr-level wiring, TOML and CLI, through the same `parse_cli` path,
283    // and the `build_prov_with_cli` body documents the env layer's position.
284
285    fn write_toml(contents: &str) -> NamedTempFile {
286        let mut file = NamedTempFile::new().expect("tempfile");
287        file.write_all(contents.as_bytes()).expect("write toml");
288        file
289    }
290
291    /// Drive `Cli::try_parse_from` + `build_from_command` end-to-end, the
292    /// same code path `parse_cli` takes once `Cli::parse()` has read argv.
293    fn run_start(config_file: Option<&Path>, extra_args: &[&str]) -> CliResult {
294        let mut argv: Vec<&str> = vec!["kellnr", "start"];
295        argv.extend(extra_args.iter().copied());
296        let cli = Cli::try_parse_from(&argv).expect("clap should accept argv");
297        let command = cli.command.expect("start subcommand present");
298        build_from_command(config_file.map(PathBuf::from), &command).expect("build")
299    }
300
301    #[test]
302    fn toml_only_marks_overridden_leaves_with_file_provenance() {
303        let file = write_toml("[registry]\ndata_dir = \"/tmp/from-toml\"\n");
304        let CliResult::RunServer(resolved) = run_start(Some(file.path()), &[]) else {
305            panic!("expected RunServer");
306        };
307
308        assert_eq!(resolved.settings.registry.data_dir, "/tmp/from-toml");
309        assert_eq!(
310            resolved.prov.registry.data_dir.source().category(),
311            Category::File,
312        );
313    }
314
315    #[test]
316    fn cli_flag_overrides_toml_with_cli_provenance() {
317        let file = write_toml("[registry]\ndata_dir = \"/tmp/from-toml\"\n");
318        let CliResult::RunServer(resolved) =
319            run_start(Some(file.path()), &["--registry-data-dir", "/tmp/from-cli"])
320        else {
321            panic!("expected RunServer");
322        };
323
324        assert_eq!(resolved.settings.registry.data_dir, "/tmp/from-cli");
325        assert_eq!(
326            resolved.prov.registry.data_dir.source().category(),
327            Category::Cli,
328        );
329    }
330
331    #[test]
332    fn cookie_secure_defaults_to_unset_and_reads_from_toml_and_cli() {
333        let file = write_toml("[registry]\ndata_dir = \"/tmp/x\"\n");
334        let CliResult::RunServer(resolved) = run_start(Some(file.path()), &[]) else {
335            panic!("expected RunServer");
336        };
337        assert_eq!(resolved.settings.origin.cookie_secure, None);
338
339        let file = write_toml("[origin]\ncookie_secure = true\n");
340        let CliResult::RunServer(resolved) = run_start(Some(file.path()), &[]) else {
341            panic!("expected RunServer");
342        };
343        assert_eq!(resolved.settings.origin.cookie_secure, Some(true));
344
345        let CliResult::RunServer(resolved) =
346            run_start(Some(file.path()), &["--origin-cookie-secure", "false"])
347        else {
348            panic!("expected RunServer");
349        };
350        assert_eq!(resolved.settings.origin.cookie_secure, Some(false));
351    }
352
353    #[test]
354    fn config_show_returns_show_config_variant_with_options() {
355        // `config show --sources` flows through `build_from_command` like
356        // `start` does, so it must also produce a usable `SettingsProv`.
357        let file = write_toml("[registry]\ndata_dir = \"/tmp/from-toml\"\n");
358        let argv = ["kellnr", "config", "show", "--sources"];
359        let cli = Cli::try_parse_from(argv).expect("clap parse");
360        let command = cli.command.expect("config subcommand present");
361
362        let result = build_from_command(Some(file.path().to_path_buf()), &command).unwrap();
363        let CliResult::ShowConfig { resolved, options } = result else {
364            panic!("expected ShowConfig variant");
365        };
366        assert!(options.show_sources);
367        assert!(!options.no_defaults);
368        assert_eq!(resolved.settings.registry.data_dir, "/tmp/from-toml");
369        assert_eq!(
370            resolved.prov.registry.data_dir.source().category(),
371            Category::File,
372        );
373    }
374
375    #[test]
376    fn id_to_dotted_path_converts_dashes_after_first_segment() {
377        assert_eq!(
378            id_to_dotted_path("registry-data-dir"),
379            Some("registry.data_dir".to_string())
380        );
381        assert_eq!(
382            id_to_dotted_path("registry-token-cache-ttl-seconds"),
383            Some("registry.token_cache_ttl_seconds".to_string())
384        );
385        // Single-segment ids (top-level flags like `--config`, clap's --help)
386        // don't map to a settings leaf.
387        assert_eq!(id_to_dotted_path("config"), None);
388        assert_eq!(id_to_dotted_path("help"), None);
389    }
390
391    #[test]
392    fn cli_flag_map_covers_every_section_with_correct_paths() {
393        let map = cli_flag_map();
394
395        // A long-only flag: clap auto-derives `--registry-data-dir` from the
396        // `clap_prefix = "registry"` section and field name `data_dir`.
397        assert_eq!(
398            map.get("registry.data_dir").map(String::as_str),
399            Some("--registry-data-dir, -d"),
400            "registry.data_dir must surface its auto-derived long plus the manual `-d` short"
401        );
402        // A user-supplied `#[arg(long = "...")]` overrides the auto-derive
403        // while the id (and therefore our lookup key) still follows the
404        // section.field convention.
405        assert_eq!(
406            map.get("registry.token_cache_ttl_seconds")
407                .map(String::as_str),
408            Some("--registry-token-cache-ttl"),
409        );
410        // Spot-check leaves from other sections so a missing wiring on any
411        // single section shows up here.
412        assert_eq!(
413            map.get("docs.enabled").map(String::as_str),
414            Some("--docs-enabled")
415        );
416        assert_eq!(
417            map.get("s3.allow_http").map(String::as_str),
418            Some("--s3-allow-http")
419        );
420        assert_eq!(
421            map.get("local.port").map(String::as_str),
422            Some("--local-port, -p")
423        );
424        // The top-level `--config` arg is not a settings leaf, must not leak in.
425        assert!(
426            !map.contains_key("config"),
427            "top-level `--config` is not a leaf"
428        );
429    }
430
431    #[test]
432    fn doc_build_subcommand_is_hidden_and_parses_arguments() {
433        let cli = Cli::try_parse_from([
434            "kellnr",
435            DOC_BUILD_SUBCOMMAND,
436            "/tmp/crate",
437            "--cratesio-index",
438            "https://proxy/index/",
439        ])
440        .expect("clap should accept argv");
441
442        let Some(Command::DocBuild {
443            crate_path,
444            cratesio_index,
445        }) = cli.command
446        else {
447            panic!("expected DocBuild");
448        };
449        assert_eq!(crate_path, PathBuf::from("/tmp/crate"));
450        assert_eq!(cratesio_index.as_deref(), Some("https://proxy/index/"));
451        assert!(
452            Cli::command()
453                .find_subcommand(DOC_BUILD_SUBCOMMAND)
454                .unwrap()
455                .is_hide_set()
456        );
457    }
458}