1use crate::Path;
45use crate::core::filesystem::Filesystem;
46
47fn parse_value<T>(text: &str, out: &mut T) -> bool
54where
55 T: ParseCliValue,
56{
57 T::parse_cli(text, out)
58}
59
60pub 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
107struct 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
140pub 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 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 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 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 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 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
308pub 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 pub fn new(name: &str, description: &str) -> Self {
339 let mut root = Cmd::new(name, description);
340 let _ = &mut root; 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 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 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 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 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 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 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 pub fn set_epilog(&mut self, text: &str) {
408 self.epilog = text.to_owned();
409 }
410
411 pub fn set_fallthrough(&mut self, enable: bool) {
414 self.fallthrough = enable;
415 }
416
417 pub fn config(&self) -> &C {
421 &self.config
422 }
423
424 pub fn config_mut(&mut self) -> &mut C {
426 &mut self.config
427 }
428
429 pub fn into_config(self) -> C {
431 self.config
432 }
433
434 pub fn config_path(&self) -> &str {
436 &self.config_path
437 }
438
439 pub fn verbose(&self) -> i32 {
441 self.verbose
442 }
443
444 pub fn help_requested(&self) -> bool {
446 self.help_request
447 }
448
449 pub fn got_subcommand(&self, name: &str) -> bool {
451 self.subcommands.iter().any(|c| c.name == name && c.parsed)
452 }
453
454 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 pub fn parse_args(&mut self, args: &[String]) -> bool {
474 self.parse_args_with_yaml(args, None::<fn(&str, &mut C)>)
475 }
476
477 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 self.scan_config_path(args);
488
489 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 self.parse_argv(args)
502 }
503
504 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 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; let mut i = 0;
536
537 while i < args.len() {
538 let arg = &args[i];
539
540 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 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 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 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 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 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 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 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 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 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 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}