Skip to main content

oa/core/
cli.rs

1//! Command-line configuration with YAML-file + argv precedence.
2//!
3//! Port provenance: `oa/core/cli.h`. Rust translates the `Cli<TConfig>`
4//! template class to `Cli<C>` with caller-provided closures for YAML loading
5//! and option application.
6//!
7//! # Precedence
8//!
9//! `struct defaults < YAML file (-c / --config) < explicit argv flags`
10//!
11//! # Usage
12//!
13//! ```rust,ignore
14//! use oa::Cli;
15//!
16//! #[derive(Default)]
17//! struct Config { steps: u64, lr: f32, output: String }
18//!
19//! struct MyApp { cli: Cli<Config> }
20//!
21//! impl MyApp {
22//!     fn new() -> Self {
23//!         let mut cli = Cli::new("myapp", "Train a model");
24//!         {
25//!             let cfg = cli.config_mut();
26//!             let _ = cfg; // borrow for defaults; options registered below
27//!         }
28//!         let app_ptr = /* pointer trick not needed — use a builder pattern: */
29//!             MyApp { cli };
30//!         app_ptr
31//!     }
32//! }
33//!
34//! // Simpler usage — register options before calling parse:
35//! let mut config = Config::default();
36//! let mut cli: Cli<Config> = Cli::new("myapp", "Train a model");
37//! cli.add_option("-s,--steps", |c| &mut c.steps, "number of steps");
38//! cli.add_option("-l,--lr",    |c| &mut c.lr,    "learning rate");
39//! let args: Vec<String> = std::env::args().collect();
40//! if !cli.parse_args(&args[1..]) { return Ok(()); }
41//! let cfg = cli.config();
42//! ```
43
44use crate::Path;
45use crate::core::filesystem::Filesystem;
46
47// ─── internal parse trait ────────────────────────────────────────────────────
48
49/// Parse a string slice into a target value.
50///
51/// Implemented for all types that implement [`FromStr`] plus a specialised
52/// `bool` arm that accepts `true/1/on/yes` and `false/0/off/no`.
53fn parse_value<T>(text: &str, out: &mut T) -> bool
54where
55	T: ParseCliValue,
56{
57	T::parse_cli(text, out)
58}
59
60/// Sealed helper for CLI value parsing.
61pub trait ParseCliValue: Sized {
62	fn parse_cli(text: &str, out: &mut Self) -> bool;
63}
64
65impl ParseCliValue for bool {
66	fn parse_cli(text: &str, out: &mut Self) -> bool {
67		match text {
68			"true" | "1" | "on" | "yes" => {
69				*out = true;
70				true
71			}
72			"false" | "0" | "off" | "no" => {
73				*out = false;
74				true
75			}
76			_ => false,
77		}
78	}
79}
80
81macro_rules! impl_parse_cli_via_from_str {
82	($($t:ty),*) => {
83		$(
84			impl ParseCliValue for $t {
85				fn parse_cli(text: &str, out: &mut Self) -> bool {
86					match text.parse::<$t>() {
87						Ok(v) => { *out = v; true }
88						Err(_) => false,
89					}
90				}
91			}
92		)*
93	}
94}
95
96impl_parse_cli_via_from_str!(i8, i16, i32, i64, i128, isize);
97impl_parse_cli_via_from_str!(u8, u16, u32, u64, u128, usize);
98impl_parse_cli_via_from_str!(f32, f64);
99
100impl ParseCliValue for String {
101	fn parse_cli(text: &str, out: &mut Self) -> bool {
102		*out = text.to_owned();
103		true
104	}
105}
106
107// ─── Opt ─────────────────────────────────────────────────────────────────────
108
109struct Alias {
110	name: String,
111	flag_value: bool,
112}
113
114type ParseFn<C> = Box<dyn Fn(&str, &mut C) -> bool>;
115type FlagTarget<C> = Box<dyn Fn(&mut C, bool)>;
116
117struct Opt<C> {
118	aliases: Vec<Alias>,
119	description: String,
120	parse: ParseFn<C>,
121	positional: bool,
122	flag: bool,
123	flag_target: Option<FlagTarget<C>>,
124	multi: bool,
125	required: bool,
126	count: u32,
127}
128
129impl<C> Opt<C> {
130	fn matches(&self, name: &str) -> Option<bool> {
131		for alias in &self.aliases {
132			if alias.name == name {
133				return Some(alias.flag_value);
134			}
135		}
136		None
137	}
138}
139
140// ─── Cmd ─────────────────────────────────────────────────────────────────────
141
142/// A named subcommand (or the implicit root command).
143///
144/// Options registered on a `Cmd` are only matched when that subcommand is
145/// active. The root `Cmd` is always active.
146pub struct Cmd<C> {
147	name: String,
148	description: String,
149	opts: Vec<Opt<C>>,
150	parsed: bool,
151}
152
153impl<C: 'static> Cmd<C> {
154	fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
155		Self {
156			name: name.into(),
157			description: description.into(),
158			opts: Vec::new(),
159			parsed: false,
160		}
161	}
162
163	/// Register a named option that writes through a field accessor.
164	///
165	/// `names` is a comma-separated list of aliases, e.g. `"-s,--steps"`.
166	pub fn add_option<T, F>(&mut self, names: &str, field: F, description: &str)
167	where
168		T: ParseCliValue + 'static,
169		F: Fn(&mut C) -> &mut T + Clone + 'static,
170	{
171		let parse: ParseFn<C> = Box::new(move |text, cfg| parse_value(text, field(cfg)));
172		let mut opt = Opt {
173			aliases: Self::parse_aliases(names),
174			description: description.to_owned(),
175			parse,
176			positional: false,
177			flag: false,
178			flag_target: None,
179			multi: false,
180			required: false,
181			count: 0,
182		};
183		opt.positional = opt
184			.aliases
185			.first()
186			.map(|a| !a.name.starts_with('-'))
187			.unwrap_or(false);
188		self.opts.push(opt);
189	}
190
191	/// Register a `bool` flag (no value argument; presence sets `true`).
192	pub fn add_flag<F>(&mut self, names: &str, field: F, description: &str)
193	where
194		F: Fn(&mut C, bool) + Clone + 'static,
195	{
196		let ft: FlagTarget<C> = Box::new(field.clone());
197		// dummy parse; flags never consume a value token
198		let parse: ParseFn<C> = Box::new(move |_text, _cfg| true);
199		self.opts.push(Opt {
200			aliases: Self::parse_aliases(names),
201			description: description.to_owned(),
202			parse,
203			positional: false,
204			flag: true,
205			flag_target: Some(ft),
206			multi: false,
207			required: false,
208			count: 0,
209		});
210	}
211
212	/// Register a multi-option that appends to a `Vec<String>`.
213	pub fn add_multi<F>(&mut self, names: &str, field: F, description: &str)
214	where
215		F: Fn(&mut C) -> &mut Vec<String> + Clone + 'static,
216	{
217		let parse: ParseFn<C> = Box::new(move |text, cfg| {
218			field(cfg).push(text.to_owned());
219			true
220		});
221		self.opts.push(Opt {
222			aliases: Self::parse_aliases(names),
223			description: description.to_owned(),
224			parse,
225			positional: false,
226			flag: false,
227			flag_target: None,
228			multi: true,
229			required: false,
230			count: 0,
231		});
232	}
233
234	/// Register a positional argument.
235	pub fn add_positional<T, F>(&mut self, name: &str, field: F, description: &str, required: bool)
236	where
237		T: ParseCliValue + 'static,
238		F: Fn(&mut C) -> &mut T + Clone + 'static,
239	{
240		let parse: ParseFn<C> = Box::new(move |text, cfg| parse_value(text, field(cfg)));
241		self.opts.push(Opt {
242			aliases: vec![Alias {
243				name: name.to_owned(),
244				flag_value: true,
245			}],
246			description: description.to_owned(),
247			parse,
248			positional: true,
249			flag: false,
250			flag_target: None,
251			multi: false,
252			required,
253			count: 0,
254		});
255	}
256
257	fn parse_aliases(names: &str) -> Vec<Alias> {
258		let mut out = Vec::new();
259		for part in names.split(',') {
260			let part = part.trim();
261			if part.is_empty() {
262				continue;
263			}
264			let (name, flag_value) = if let Some(stripped) = part.strip_suffix("{false}") {
265				(stripped, false)
266			} else {
267				(part, true)
268			};
269			out.push(Alias {
270				name: name.to_owned(),
271				flag_value,
272			});
273		}
274		out
275	}
276
277	fn find_named(&mut self, name: &str) -> Option<(&mut Opt<C>, bool)> {
278		for opt in &mut self.opts {
279			if !opt.positional
280				&& let Some(flag_value) = opt.matches(name)
281			{
282				return Some((opt, flag_value));
283			}
284		}
285		None
286	}
287
288	fn next_positional(&mut self) -> Option<&mut Opt<C>> {
289		self
290			.opts
291			.iter_mut()
292			.find(|opt| opt.positional && (opt.multi || opt.count == 0))
293	}
294
295	fn validate_required(&self) -> Option<String> {
296		for opt in &self.opts {
297			if opt.required && opt.count == 0 {
298				return Some(format!(
299					"missing required option: {}",
300					opt.aliases.first().map(|a| a.name.as_str()).unwrap_or("?")
301				));
302			}
303		}
304		None
305	}
306}
307
308// ─── Cli ─────────────────────────────────────────────────────────────────────
309
310/// Command-line configuration with YAML + argv precedence.
311///
312/// # Type parameter
313///
314/// `C` is any config struct that implements [`Default`]. Defaults are the
315/// base layer; a YAML file loaded via `-c`/`--config` overrides them; explicit
316/// argv flags override those.
317///
318/// # YAML support
319///
320/// YAML loading is the caller's responsibility. Pass a loader closure to
321/// [`Cli::parse_args_with_yaml`] to apply YAML fields before argv parsing when
322/// a `-c`/`--config` path is present.
323pub struct Cli<C> {
324	root: Cmd<C>,
325	subcommands: Vec<Cmd<C>>,
326	config: C,
327	config_path: String,
328	verbose: i32,
329	epilog: String,
330	fallthrough: bool,
331	help_request: bool,
332	req_sub_min: i32,
333	req_sub_max: i32,
334}
335
336impl<C: Default + 'static> Cli<C> {
337	/// Create a new CLI with the given program name and description.
338	pub fn new(name: &str, description: &str) -> Self {
339		let mut root = Cmd::new(name, description);
340		// Built-in options present on every OA CLI.
341		// These are matched manually; we don't register them as Opt entries
342		// because the config path scan must happen before any option parse.
343		let _ = &mut root; // keep for structure; config/verbose handled inline
344		Self {
345			root,
346			subcommands: Vec::new(),
347			config: C::default(),
348			config_path: String::new(),
349			verbose: 0,
350			epilog: String::new(),
351			fallthrough: true,
352			help_request: false,
353			req_sub_min: 0,
354			req_sub_max: 0,
355		}
356	}
357
358	// ─── Option registration ─────────────────────────────────────────────
359
360	/// Register a named option on the root command.
361	pub fn add_option<T, F>(&mut self, names: &str, field: F, description: &str)
362	where
363		T: ParseCliValue + 'static,
364		F: Fn(&mut C) -> &mut T + Clone + 'static,
365	{
366		self.root.add_option(names, field, description);
367	}
368
369	/// Register a bool flag on the root command.
370	pub fn add_flag<F>(&mut self, names: &str, field: F, description: &str)
371	where
372		F: Fn(&mut C, bool) + Clone + 'static,
373	{
374		self.root.add_flag(names, field, description);
375	}
376
377	/// Register a multi-option on the root command.
378	pub fn add_multi<F>(&mut self, names: &str, field: F, description: &str)
379	where
380		F: Fn(&mut C) -> &mut Vec<String> + Clone + 'static,
381	{
382		self.root.add_multi(names, field, description);
383	}
384
385	/// Register a positional argument on the root command.
386	pub fn add_positional<T, F>(&mut self, name: &str, field: F, description: &str, required: bool)
387	where
388		T: ParseCliValue + 'static,
389		F: Fn(&mut C) -> &mut T + Clone + 'static,
390	{
391		self.root.add_positional(name, field, description, required);
392	}
393
394	/// Add a named subcommand and return a mutable reference to register options on it.
395	pub fn add_subcommand(&mut self, name: &str, description: &str) -> &mut Cmd<C> {
396		self.subcommands.push(Cmd::new(name, description));
397		self.subcommands.last_mut().unwrap()
398	}
399
400	/// Require between `min` and `max` subcommands (0 = unlimited).
401	pub fn require_subcommand(&mut self, min: i32, max: i32) {
402		self.req_sub_min = min;
403		self.req_sub_max = max;
404	}
405
406	/// Set the epilog shown after options in `--help`.
407	pub fn set_epilog(&mut self, text: &str) {
408		self.epilog = text.to_owned();
409	}
410
411	/// Control whether unknown flags fall through to the root command when a
412	/// subcommand is active. Default: `true`.
413	pub fn set_fallthrough(&mut self, enable: bool) {
414		self.fallthrough = enable;
415	}
416
417	// ─── Config access ───────────────────────────────────────────────────
418
419	/// Borrow the current config value.
420	pub fn config(&self) -> &C {
421		&self.config
422	}
423
424	/// Mutably borrow the current config value (for programmatic override).
425	pub fn config_mut(&mut self) -> &mut C {
426		&mut self.config
427	}
428
429	/// Consume the CLI and return the parsed config.
430	pub fn into_config(self) -> C {
431		self.config
432	}
433
434	/// Path provided via `-c`/`--config`, empty if not supplied.
435	pub fn config_path(&self) -> &str {
436		&self.config_path
437	}
438
439	/// Verbose level provided via `-v`/`--verbose`.
440	pub fn verbose(&self) -> i32 {
441		self.verbose
442	}
443
444	/// True when `--help` or `-h` was the only meaningful argument.
445	pub fn help_requested(&self) -> bool {
446		self.help_request
447	}
448
449	/// True when the named subcommand was parsed.
450	pub fn got_subcommand(&self, name: &str) -> bool {
451		self.subcommands.iter().any(|c| c.name == name && c.parsed)
452	}
453
454	/// Name of the active subcommand, or empty string.
455	pub fn active_subcommand(&self) -> &str {
456		self
457			.subcommands
458			.iter()
459			.find(|c| c.parsed)
460			.map(|c| c.name.as_str())
461			.unwrap_or("")
462	}
463
464	// ─── Parse ───────────────────────────────────────────────────────────
465
466	/// Parse `argv` (without the program name).
467	///
468	/// Returns `false` if `--help` was requested or an error occurred.
469	/// The caller should exit cleanly on `false` when `help_requested()` is
470	/// true, and print an error / exit with failure otherwise.
471	///
472	/// Precedence: `struct defaults < load_yaml callback < explicit flags`.
473	pub fn parse_args(&mut self, args: &[String]) -> bool {
474		self.parse_args_with_yaml(args, None::<fn(&str, &mut C)>)
475	}
476
477	/// Parse with an optional YAML loader hook.
478	///
479	/// `yaml_loader` is called with the raw file content (if `-c`/`--config` is
480	/// present) before argv flags are applied. The caller owns the YAML
481	/// parsing dependency.
482	pub fn parse_args_with_yaml<F>(&mut self, args: &[String], yaml_loader: Option<F>) -> bool
483	where
484		F: FnOnce(&str, &mut C),
485	{
486		// Pass 1: scan for -c / --config before anything else.
487		self.scan_config_path(args);
488
489		// Pass 2: YAML file (if present and loader provided).
490		if !self.config_path.is_empty()
491			&& let Some(loader) = yaml_loader
492		{
493			let result = Filesystem::read_text(&Path::from(self.config_path.as_str()));
494			match result {
495				Ok(text) => loader(&text, &mut self.config),
496				Err(e) => eprintln!("[OA CONFIG] YAML load failed: {e} (using defaults)"),
497			}
498		}
499
500		// Pass 3: parse argv flags.
501		self.parse_argv(args)
502	}
503
504	/// Convenience: parse `std::env::args()` (skips `argv[0]`).
505	pub fn parse(&mut self) -> bool {
506		let args: Vec<String> = std::env::args().skip(1).collect();
507		self.parse_args(&args)
508	}
509
510	// ─── internals ───────────────────────────────────────────────────────
511
512	fn scan_config_path(&mut self, args: &[String]) {
513		let mut i = 0;
514		while i < args.len() {
515			let a = &args[i];
516			if (a == "--config" || a == "-c") && i + 1 < args.len() {
517				self.config_path = args[i + 1].clone();
518				return;
519			}
520			if let Some(rest) = a.strip_prefix("--config=") {
521				self.config_path = rest.to_owned();
522				return;
523			}
524			if let Some(rest) = a.strip_prefix("-c=") {
525				self.config_path = rest.to_owned();
526				return;
527			}
528			i += 1;
529		}
530	}
531
532	fn parse_argv(&mut self, args: &[String]) -> bool {
533		self.help_request = false;
534		let mut selected: Option<usize> = None; // index into self.subcommands
535		let mut i = 0;
536
537		while i < args.len() {
538			let arg = &args[i];
539
540			// Help flags.
541			if arg == "--help" || arg == "-h" || arg == "--help-all" {
542				self.help_request = true;
543				self.print_help(selected, arg == "--help-all");
544				return false;
545			}
546
547			// Built-in: -v / --verbose
548			if arg == "-v" || arg == "--verbose" {
549				if i + 1 < args.len() {
550					if let Ok(v) = args[i + 1].parse::<i32>() {
551						self.verbose = v;
552						i += 1;
553					}
554				} else {
555					self.verbose += 1;
556				}
557				i += 1;
558				continue;
559			}
560			if let Some(rest) = arg.strip_prefix("--verbose=") {
561				if let Ok(v) = rest.parse::<i32>() {
562					self.verbose = v;
563				}
564				i += 1;
565				continue;
566			}
567
568			// Built-in: -c / --config (already consumed in scan; skip here)
569			if (arg == "-c" || arg == "--config") && i + 1 < args.len() {
570				i += 2;
571				continue;
572			}
573			if arg.starts_with("--config=") || arg.starts_with("-c=") {
574				i += 1;
575				continue;
576			}
577
578			// Subcommand detection (first non-flag token).
579			if selected.is_none() && !starts_with_dash(arg) {
580				let found_idx = self.subcommands.iter().position(|c| c.name == *arg);
581				if let Some(idx) = found_idx {
582					self.subcommands[idx].parsed = true;
583					selected = Some(idx);
584					i += 1;
585					continue;
586				}
587			}
588
589			if starts_with_dash(arg) {
590				// Named option / flag.
591				let (name, inline_value) = if let Some(eq) = arg.find('=') {
592					(arg[..eq].to_owned(), Some(arg[eq + 1..].to_owned()))
593				} else {
594					(arg.clone(), None)
595				};
596
597				// Look up in selected subcommand first, then root if fallthrough.
598				let found = if let Some(idx) = selected {
599					self.subcommands[idx]
600						.find_named(&name)
601						.map(|(opt, fv)| (opt as *mut Opt<C>, fv))
602				} else {
603					None
604				};
605				let found = found.or_else(|| {
606					if selected.is_none() || self.fallthrough {
607						self
608							.root
609							.find_named(&name)
610							.map(|(opt, fv)| (opt as *mut Opt<C>, fv))
611					} else {
612						None
613					}
614				});
615
616				let (opt_ptr, flag_value) = match found {
617					Some(p) => p,
618					None => return self.fail(&format!("unknown option: {name}"), ""),
619				};
620				// SAFETY: we hold &mut self and no other borrow to opts exists.
621				let opt = unsafe { &mut *opt_ptr };
622
623				if opt.flag {
624					if inline_value.is_some() {
625						return self.fail(&format!("flag does not take a value: {name}"), "");
626					}
627					if let Some(ref ft) = opt.flag_target {
628						ft(&mut self.config, flag_value);
629					}
630					opt.count += 1;
631					i += 1;
632					continue;
633				}
634
635				let value = if let Some(v) = inline_value {
636					i += 1;
637					v
638				} else {
639					if i + 1 >= args.len() {
640						return self.fail(&format!("option requires a value: {name}"), "");
641					}
642					i += 2;
643					args[i - 1].clone()
644				};
645
646				if !(opt.parse)(&value, &mut self.config) {
647					return self.fail(&format!("invalid value for {name}: {value}"), "");
648				}
649				opt.count += 1;
650				continue;
651			}
652
653			// Positional.
654			let cmd: *mut Cmd<C> = if let Some(idx) = selected {
655				&mut self.subcommands[idx]
656			} else {
657				&mut self.root
658			};
659			let opt = unsafe { (*cmd).next_positional() };
660			match opt {
661				None => return self.fail(&format!("unexpected positional argument: {arg}"), ""),
662				Some(opt) => {
663					if !(opt.parse)(arg, &mut self.config) {
664						return self.fail(&format!("invalid positional argument: {arg}"), "");
665					}
666					opt.count += 1;
667				}
668			}
669			i += 1;
670		}
671
672		// Validate subcommand count.
673		let sub_count = if selected.is_some() { 1 } else { 0 };
674		if sub_count < self.req_sub_min || (self.req_sub_max > 0 && sub_count > self.req_sub_max) {
675			return self.fail("required subcommand missing", "");
676		}
677
678		// Validate required options.
679		if let Some(err) = self.root.validate_required() {
680			return self.fail(&err, "");
681		}
682		if let (Some(idx), Some(err)) = (
683			selected,
684			selected.and_then(|i| self.subcommands[i].validate_required()),
685		) {
686			let _ = idx;
687			return self.fail(&err, "");
688		}
689		// (selected validated above)
690		true
691	}
692
693	fn fail(&self, message: &str, detail: &str) -> bool {
694		eprint!("{message}");
695		if !detail.is_empty() {
696			eprint!(": {detail}");
697		}
698		eprintln!("\nUse --help for usage.");
699		false
700	}
701
702	fn print_help(&self, selected: Option<usize>, all: bool) {
703		let cmd = if let Some(idx) = selected {
704			&self.subcommands[idx]
705		} else {
706			&self.root
707		};
708		eprintln!("{} — {}", cmd.name, cmd.description);
709		eprintln!("  -c, --config <path>    YAML config file");
710		eprintln!("  -v, --verbose [level]  verbose level (0-3)");
711		for opt in &cmd.opts {
712			Self::print_opt(opt);
713		}
714		if selected.is_none() && !self.subcommands.is_empty() {
715			eprintln!("\nCommands:");
716			for sub in &self.subcommands {
717				eprintln!("  {}\n      {}", sub.name, sub.description);
718				if all {
719					for opt in &sub.opts {
720						Self::print_opt(opt);
721					}
722				}
723			}
724		}
725		if !self.epilog.is_empty() {
726			eprintln!("\n{}", self.epilog);
727		}
728	}
729
730	fn print_opt(opt: &Opt<C>) {
731		let names: Vec<&str> = opt.aliases.iter().map(|a| a.name.as_str()).collect();
732		let lhs = names.join(", ");
733		let value_hint = if opt.flag || opt.positional {
734			""
735		} else {
736			" <value>"
737		};
738		let req = if opt.required { " (required)" } else { "" };
739		eprintln!("  {lhs}{value_hint}\n      {}{req}", opt.description);
740	}
741}
742
743fn starts_with_dash(s: &str) -> bool {
744	s.starts_with('-')
745}