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 #[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 {
28 #[command(flatten)]
32 server: SettingsArgs,
33 },
34 Config {
36 #[command(subcommand)]
37 action: ConfigAction,
38 },
39 #[command(name = DOC_BUILD_SUBCOMMAND, hide = true)]
42 DocBuild {
43 crate_path: PathBuf,
45
46 #[arg(long = DOC_BUILD_CRATESIO_INDEX_ARG)]
48 cratesio_index: Option<String>,
49 },
50}
51
52pub const DOC_BUILD_SUBCOMMAND: &str = "doc-build";
54pub const DOC_BUILD_CRATESIO_INDEX_ARG: &str = "cratesio-index";
56
57#[derive(Subcommand)]
58pub enum ConfigAction {
59 Show {
61 #[arg(long = "no-defaults")]
63 no_defaults: bool,
64
65 #[arg(long = "sources")]
67 show_sources: bool,
68 },
69 Init {
71 #[arg(short = 'o', long = "output")]
73 output: Option<PathBuf>,
74 },
75}
76
77#[derive(Debug, Clone, Default)]
79pub struct ShowConfigOptions {
80 pub no_defaults: bool,
82 pub show_sources: bool,
84}
85
86pub 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 InitConfig {
106 output: PathBuf,
107 },
108 ShowHelp,
109 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 None => {
125 Cli::command().print_help().ok();
126 Ok(CliResult::ShowHelp)
127 }
128
129 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 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#[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 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 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#[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
258fn 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 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 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 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 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 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 assert_eq!(
406 map.get("registry.token_cache_ttl_seconds")
407 .map(String::as_str),
408 Some("--registry-token-cache-ttl"),
409 );
410 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 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}