1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
//! # Menu
//!
//! A basic command-line interface for `#![no_std]` Rust programs. Peforms
//! zero heap allocation.
#![no_std]
pub mod menu_manager;
/// The type of function we call when we enter/exit a menu.
pub type MenuCallbackFn<I, T> = fn(menu: &Menu<I, T>, interface: &mut I, context: &mut T);
/// The type of function we call when we a valid command has been entered.
pub type ItemCallbackFn<I, T> =
fn(menu: &Menu<I, T>, item: &Item<I, T>, args: &[&str], interface: &mut I, context: &mut T);
#[derive(Debug)]
/// Describes a parameter to the command
pub enum Parameter<'a> {
/// A mandatory positional parameter
Mandatory {
/// A name for this mandatory positional parameter
parameter_name: &'a str,
/// Help text
help: Option<&'a str>,
},
/// An optional positional parameter. Must come after the mandatory positional arguments.
Optional {
/// A name for this optional positional parameter
parameter_name: &'a str,
/// Help text
help: Option<&'a str>,
},
/// An optional named parameter with no argument (e.g. `--verbose` or `--dry-run`)
Named {
/// The bit that comes after the `--`
parameter_name: &'a str,
/// Help text
help: Option<&'a str>,
},
/// A optional named parameter with argument (e.g. `--mode=foo` or `--level=3`)
NamedValue {
/// The bit that comes after the `--`
parameter_name: &'a str,
/// The bit that comes after the `--name=`, e.g. `INT` or `FILE`. It's mostly for help text.
argument_name: &'a str,
/// Help text
help: Option<&'a str>,
},
}
/// Do we enter a sub-menu when this command is entered, or call a specific
/// function?
pub enum ItemType<'a, I, T>
where
T: 'a,
{
/// Call a function when this command is entered
Callback {
/// The function to call
function: ItemCallbackFn<I, T>,
/// The list of parameters for this function. Pass an empty list if there aren't any.
parameters: &'a [Parameter<'a>],
},
/// This item is a sub-menu you can enter
Menu(&'a Menu<'a, I, T>),
/// Internal use only - do not use
_Dummy,
}
/// An `Item` is a what our menus are made from. Each item has a `name` which
/// you have to enter to select this item. Each item can also have zero or
/// more parameters, and some optional help text.
pub struct Item<'a, I, T>
where
T: 'a,
{
/// The word you need to enter to activate this item. It is recommended
/// that you avoid whitespace in this string.
pub command: &'a str,
/// Optional help text. Printed if you enter `help`.
pub help: Option<&'a str>,
/// The type of this item - menu, callback, etc.
pub item_type: ItemType<'a, I, T>,
}
/// A `Menu` is made of one or more `Item`s.
pub struct Menu<'a, I, T>
where
T: 'a,
{
/// Each menu has a label which is visible in the prompt, unless you are
/// the root menu.
pub label: &'a str,
/// A slice of menu items in this menu.
pub items: &'a [&'a Item<'a, I, T>],
/// A function to call when this menu is entered. If this is the root menu, this is called when the runner is created.
pub entry: Option<MenuCallbackFn<I, T>>,
/// A function to call when this menu is exited. Never called for the root menu.
pub exit: Option<MenuCallbackFn<I, T>>,
}
/// This structure handles the menu. You feed it bytes as they are read from
/// the console and it executes menu actions when commands are typed in
/// (followed by Enter).
pub struct Runner<'a, I, T>
where
I: core::fmt::Write,
{
buffer: &'a mut [u8],
used: usize,
menu_mgr: menu_manager::MenuManager<'a, I, T>,
pub interface: I,
}
/// Describes the ways in which the API can fail
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// Tried to find arguments on an item that was a `Callback` item
NotACallbackItem,
/// The argument you asked for was not found
NotFound,
}
/// Looks for the named parameter in the parameter list of the item, then
/// finds the correct argument.
///
/// * Returns `Ok(None)` if `parameter_name` gives an optional or named
/// parameter and that argument was not given.
/// * Returns `Ok(arg)` if the argument corresponding to `parameter_name` was
/// found. `arg` is the empty string if the parameter was `Parameter::Named`
/// (and hence doesn't take a value).
/// * Returns `Err(())` if `parameter_name` was not in `item.parameter_list`
/// or `item` wasn't an Item::Callback
pub fn argument_finder<'a, I, T>(
item: &'a Item<'a, I, T>,
argument_list: &'a [&'a str],
name_to_find: &'a str,
) -> Result<Option<&'a str>, Error> {
let ItemType::Callback { parameters, .. } = item.item_type else {
return Err(Error::NotACallbackItem);
};
// Step 1 - Find `name_to_find` in the parameter list.
let mut found_param = None;
let mut mandatory_count = 0;
let mut optional_count = 0;
for param in parameters.iter() {
match param {
Parameter::Mandatory { parameter_name, .. } => {
mandatory_count += 1;
if *parameter_name == name_to_find {
found_param = Some((param, mandatory_count));
}
}
Parameter::Optional { parameter_name, .. } => {
optional_count += 1;
if *parameter_name == name_to_find {
found_param = Some((param, optional_count));
}
}
Parameter::Named { parameter_name, .. } => {
if *parameter_name == name_to_find {
found_param = Some((param, 0));
}
}
Parameter::NamedValue { parameter_name, .. } => {
if *parameter_name == name_to_find {
found_param = Some((param, 0));
}
}
}
}
// Step 2 - What sort of parameter is it?
match found_param {
// Step 2a - Mandatory Positional
Some((Parameter::Mandatory { .. }, mandatory_idx)) => {
// We want positional parameter number `mandatory_idx`.
let mut positional_args_seen = 0;
for arg in argument_list.iter().filter(|x| !x.starts_with("--")) {
// Positional
positional_args_seen += 1;
if positional_args_seen == mandatory_idx {
return Ok(Some(arg));
}
}
// Valid thing to ask for but we don't have it
Ok(None)
}
// Step 2b - Optional Positional
Some((Parameter::Optional { .. }, optional_idx)) => {
// We want positional parameter number `mandatory_count + optional_idx`.
let mut positional_args_seen = 0;
for arg in argument_list.iter().filter(|x| !x.starts_with("--")) {
// Positional
positional_args_seen += 1;
if positional_args_seen == (mandatory_count + optional_idx) {
return Ok(Some(arg));
}
}
// Valid thing to ask for but we don't have it
Ok(None)
}
// Step 2c - Named (e.g. `--verbose`)
Some((Parameter::Named { parameter_name, .. }, _)) => {
for arg in argument_list {
if arg.starts_with("--") && (&arg[2..] == *parameter_name) {
return Ok(Some(""));
}
}
// Valid thing to ask for but we don't have it
Ok(None)
}
// Step 2d - NamedValue (e.g. `--level=123`)
Some((Parameter::NamedValue { parameter_name, .. }, _)) => {
let name_start = 2;
let equals_start = name_start + parameter_name.len();
let value_start = equals_start + 1;
for arg in argument_list {
if arg.starts_with("--")
&& (arg.len() >= value_start)
&& (arg.get(equals_start..=equals_start) == Some("="))
&& (arg.get(name_start..equals_start) == Some(*parameter_name))
{
return Ok(Some(&arg[value_start..]));
}
}
// Valid thing to ask for but we don't have it
Ok(None)
}
// Step 2e - not found
_ => Err(Error::NotFound),
}
}
enum Outcome {
CommandProcessed,
NeedMore,
}
impl<'a, I, T> core::clone::Clone for Menu<'a, I, T> {
fn clone(&self) -> Menu<'a, I, T> {
Menu {
label: self.label,
items: self.items,
entry: self.entry,
exit: self.exit,
}
}
}
impl<'a, I, T> Runner<'a, I, T>
where
I: core::fmt::Write,
{
/// Create a new `Runner`. You need to supply a top-level menu, and a
/// buffer that the `Runner` can use. Feel free to pass anything as the
/// `context` type - the only requirement is that the `Runner` can
/// `write!` to the context, which it will do for all text output.
pub fn new(
menu: Menu<'a, I, T>,
buffer: &'a mut [u8],
mut interface: I,
context: &mut T,
) -> Self {
if let Some(cb_fn) = menu.entry {
cb_fn(&menu, &mut interface, context);
}
let mut r = Runner {
menu_mgr: menu_manager::MenuManager::new(menu),
buffer,
used: 0,
interface,
};
r.prompt(true);
r
}
/// Print out a new command prompt, including sub-menu names if
/// applicable.
pub fn prompt(&mut self, newline: bool) {
if newline {
writeln!(self.interface).unwrap();
}
for i in 0..self.menu_mgr.depth() {
if i > 1 {
write!(self.interface, "/").unwrap();
}
let menu = self.menu_mgr.get_menu(Some(i));
write!(self.interface, "/{}", menu.label).unwrap();
}
write!(self.interface, "> ").unwrap();
}
/// Add a byte to the menu runner's buffer. If this byte is a
/// carriage-return, the buffer is scanned and the appropriate action
/// performed.
/// By default, an echo feature is enabled to display commands on the terminal.
pub fn input_byte(&mut self, input: u8, context: &mut T) {
// Strip carriage returns
if input == 0x0A {
return;
}
let outcome = if input == 0x0D {
#[cfg(not(feature = "echo"))]
{
// Echo the command
write!(self.interface, "\r").unwrap();
if let Ok(s) = core::str::from_utf8(&self.buffer[0..self.used]) {
write!(self.interface, "{}", s).unwrap();
}
}
// Handle the command
self.process_command(context);
Outcome::CommandProcessed
} else if (input == 0x08) || (input == 0x7F) {
// Handling backspace or delete
if self.used > 0 {
write!(self.interface, "\u{0008} \u{0008}").unwrap();
self.used -= 1;
}
Outcome::NeedMore
} else if self.used < self.buffer.len() {
self.buffer[self.used] = input;
self.used += 1;
#[cfg(feature = "echo")]
{
// We have to do this song and dance because `self.prompt()` needs
// a mutable reference to self, and we can't have that while
// holding a reference to the buffer at the same time.
// This line grabs the buffer, checks it's OK, then releases it again
let valid = core::str::from_utf8(&self.buffer[0..self.used]).is_ok();
// Now we've released the buffer, we can draw the prompt
if valid {
write!(self.interface, "\r").unwrap();
self.prompt(false);
}
// Grab the buffer again to render it to the screen
if let Ok(s) = core::str::from_utf8(&self.buffer[0..self.used]) {
write!(self.interface, "{}", s).unwrap();
}
}
Outcome::NeedMore
} else {
writeln!(self.interface, "Buffer overflow!").unwrap();
Outcome::NeedMore
};
match outcome {
Outcome::CommandProcessed => {
self.used = 0;
self.prompt(true);
}
Outcome::NeedMore => {}
}
}
/// Scan the buffer and do the right thing based on its contents.
fn process_command(&mut self, context: &mut T) {
// Go to the next line, below the prompt
writeln!(self.interface).unwrap();
if let Ok(command_line) = core::str::from_utf8(&self.buffer[0..self.used]) {
// We have a valid string
let mut parts = command_line.split_whitespace();
if let Some(cmd) = parts.next() {
let menu = self.menu_mgr.get_menu(None);
if cmd == "help" {
match parts.next() {
Some(arg) => match menu.items.iter().find(|i| i.command == arg) {
Some(item) => {
self.print_long_help(item);
}
None => {
writeln!(self.interface, "I can't help with {:?}", arg).unwrap();
}
},
_ => {
writeln!(self.interface, "AVAILABLE ITEMS:").unwrap();
for item in menu.items {
self.print_short_help(item);
}
if self.menu_mgr.depth() != 0 {
self.print_short_help(&Item {
command: "exit",
help: Some("Leave this menu."),
item_type: ItemType::_Dummy,
});
}
self.print_short_help(&Item {
command: "help [ <command> ]",
help: Some("Show this help, or get help on a specific command."),
item_type: ItemType::_Dummy,
});
}
}
} else if cmd == "exit" && self.menu_mgr.depth() != 0 {
if let Some(cb_fn) = menu.exit {
cb_fn(menu, &mut self.interface, context);
}
self.menu_mgr.pop_menu();
} else {
let mut found = false;
for (i, item) in menu.items.iter().enumerate() {
if cmd == item.command {
match item.item_type {
ItemType::Callback {
function,
parameters,
} => Self::call_function(
&mut self.interface,
context,
function,
parameters,
menu,
item,
command_line,
),
ItemType::Menu(_) => {
if let Some(cb_fn) = self.menu_mgr.get_menu(None).entry {
cb_fn(menu, &mut self.interface, context);
}
self.menu_mgr.push_menu(i);
}
ItemType::_Dummy => {
unreachable!();
}
}
found = true;
break;
}
}
if !found {
writeln!(self.interface, "Command {:?} not found. Try 'help'.", cmd)
.unwrap();
}
}
} else {
writeln!(self.interface, "Input was empty?").unwrap();
}
} else {
// Hmm .. we did not have a valid string
writeln!(self.interface, "Input was not valid UTF-8").unwrap();
}
}
fn print_short_help(&mut self, item: &Item<I, T>) {
let mut has_options = false;
match item.item_type {
ItemType::Callback { parameters, .. } => {
write!(self.interface, " {}", item.command).unwrap();
if !parameters.is_empty() {
for param in parameters.iter() {
match param {
Parameter::Mandatory { parameter_name, .. } => {
write!(self.interface, " <{}>", parameter_name).unwrap();
}
Parameter::Optional { parameter_name, .. } => {
write!(self.interface, " [ <{}> ]", parameter_name).unwrap();
}
Parameter::Named { .. } => {
has_options = true;
}
Parameter::NamedValue { .. } => {
has_options = true;
}
}
}
}
}
ItemType::Menu(_menu) => {
write!(self.interface, " {}", item.command).unwrap();
}
ItemType::_Dummy => {
write!(self.interface, " {}", item.command).unwrap();
}
}
if has_options {
write!(self.interface, " [OPTIONS...]").unwrap();
}
writeln!(self.interface).unwrap();
}
fn print_long_help(&mut self, item: &Item<I, T>) {
writeln!(self.interface, "SUMMARY:").unwrap();
match item.item_type {
ItemType::Callback { parameters, .. } => {
write!(self.interface, " {}", item.command).unwrap();
if !parameters.is_empty() {
for param in parameters.iter() {
match param {
Parameter::Mandatory { parameter_name, .. } => {
write!(self.interface, " <{}>", parameter_name).unwrap();
}
Parameter::Optional { parameter_name, .. } => {
write!(self.interface, " [ <{}> ]", parameter_name).unwrap();
}
Parameter::Named { parameter_name, .. } => {
write!(self.interface, " [ --{} ]", parameter_name).unwrap();
}
Parameter::NamedValue {
parameter_name,
argument_name,
..
} => {
write!(
self.interface,
" [ --{}={} ]",
parameter_name, argument_name
)
.unwrap();
}
}
}
writeln!(self.interface, "\n\nPARAMETERS:").unwrap();
let default_help = "Undocumented option";
for param in parameters.iter() {
match param {
Parameter::Mandatory {
parameter_name,
help,
} => {
writeln!(
self.interface,
" <{0}>\n {1}\n",
parameter_name,
help.unwrap_or(default_help),
)
.unwrap();
}
Parameter::Optional {
parameter_name,
help,
} => {
writeln!(
self.interface,
" <{0}>\n {1}\n",
parameter_name,
help.unwrap_or(default_help),
)
.unwrap();
}
Parameter::Named {
parameter_name,
help,
} => {
writeln!(
self.interface,
" --{0}\n {1}\n",
parameter_name,
help.unwrap_or(default_help),
)
.unwrap();
}
Parameter::NamedValue {
parameter_name,
argument_name,
help,
} => {
writeln!(
self.interface,
" --{0}={1}\n {2}\n",
parameter_name,
argument_name,
help.unwrap_or(default_help),
)
.unwrap();
}
}
}
}
}
ItemType::Menu(_menu) => {
write!(self.interface, " {}", item.command).unwrap();
}
ItemType::_Dummy => {
write!(self.interface, " {}", item.command).unwrap();
}
}
if let Some(help) = item.help {
writeln!(self.interface, "\n\nDESCRIPTION:\n{}", help).unwrap();
}
}
fn call_function(
interface: &mut I,
context: &mut T,
callback_function: ItemCallbackFn<I, T>,
parameters: &[Parameter],
parent_menu: &Menu<I, T>,
item: &Item<I, T>,
command: &str,
) {
let mandatory_parameter_count = parameters
.iter()
.filter(|p| matches!(p, Parameter::Mandatory { .. }))
.count();
let positional_parameter_count = parameters
.iter()
.filter(|p| matches!(p, Parameter::Mandatory { .. } | Parameter::Optional { .. }))
.count();
if command.len() >= item.command.len() {
// Maybe arguments
let mut argument_buffer: [&str; 16] = [""; 16];
let mut argument_count = 0;
let mut positional_arguments = 0;
for (slot, arg) in argument_buffer
.iter_mut()
.zip(command[item.command.len()..].split_whitespace())
{
*slot = arg;
argument_count += 1;
if let Some(tail) = arg.strip_prefix("--") {
// Validate named argument
let mut found = false;
for param in parameters.iter() {
match param {
Parameter::Named { parameter_name, .. } => {
if tail == *parameter_name {
found = true;
break;
}
}
Parameter::NamedValue { parameter_name, .. } => {
if arg.contains('=') {
if let Some(given_name) = tail.split('=').next() {
if given_name == *parameter_name {
found = true;
break;
}
}
}
}
_ => {
// Ignore
}
}
}
if !found {
writeln!(interface, "Error: Did not understand {:?}", arg).unwrap();
return;
}
} else {
positional_arguments += 1;
}
}
if positional_arguments < mandatory_parameter_count {
writeln!(interface, "Error: Insufficient arguments given").unwrap();
} else if positional_arguments > positional_parameter_count {
writeln!(interface, "Error: Too many arguments given").unwrap();
} else {
callback_function(
parent_menu,
item,
&argument_buffer[0..argument_count],
interface,
context,
);
}
} else {
// Definitely no arguments
if mandatory_parameter_count == 0 {
callback_function(parent_menu, item, &[], interface, context);
} else {
writeln!(interface, "Error: Insufficient arguments given").unwrap();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dummy(
_menu: &Menu<(), u32>,
_item: &Item<(), u32>,
_args: &[&str],
_interface: &mut (),
_context: &mut u32,
) {
}
#[test]
fn find_arg_mandatory() {
let item = Item {
command: "dummy",
help: None,
item_type: ItemType::Callback {
function: dummy,
parameters: &[
Parameter::Mandatory {
parameter_name: "foo",
help: Some("Some help for foo"),
},
Parameter::Mandatory {
parameter_name: "bar",
help: Some("Some help for bar"),
},
Parameter::Mandatory {
parameter_name: "baz",
help: Some("Some help for baz"),
},
],
},
};
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "foo"),
Ok(Some("a"))
);
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "bar"),
Ok(Some("b"))
);
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "baz"),
Ok(Some("c"))
);
// Not an argument
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "quux"),
Err(Error::NotFound)
);
}
#[test]
fn find_arg_optional() {
let item = Item {
command: "dummy",
help: None,
item_type: ItemType::Callback {
function: dummy,
parameters: &[
Parameter::Mandatory {
parameter_name: "foo",
help: Some("Some help for foo"),
},
Parameter::Mandatory {
parameter_name: "bar",
help: Some("Some help for bar"),
},
Parameter::Optional {
parameter_name: "baz",
help: Some("Some help for baz"),
},
],
},
};
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "foo"),
Ok(Some("a"))
);
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "bar"),
Ok(Some("b"))
);
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "baz"),
Ok(Some("c"))
);
// Not an argument
assert_eq!(
argument_finder(&item, &["a", "b", "c"], "quux"),
Err(Error::NotFound)
);
// Missing optional
assert_eq!(argument_finder(&item, &["a", "b"], "baz"), Ok(None));
}
#[test]
fn find_arg_named() {
let item = Item {
command: "dummy",
help: None,
item_type: ItemType::Callback {
function: dummy,
parameters: &[
Parameter::Mandatory {
parameter_name: "foo",
help: Some("Some help for foo"),
},
Parameter::Named {
parameter_name: "bar",
help: Some("Some help for bar"),
},
Parameter::Named {
parameter_name: "baz",
help: Some("Some help for baz"),
},
],
},
};
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "foo"),
Ok(Some("a"))
);
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "bar"),
Ok(Some(""))
);
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "baz"),
Ok(Some(""))
);
// Not an argument
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "quux"),
Err(Error::NotFound)
);
// Missing named
assert_eq!(argument_finder(&item, &["a"], "baz"), Ok(None));
}
#[test]
fn find_arg_namedvalue() {
let item = Item {
command: "dummy",
help: None,
item_type: ItemType::Callback {
function: dummy,
parameters: &[
Parameter::Mandatory {
parameter_name: "foo",
help: Some("Some help for foo"),
},
Parameter::Named {
parameter_name: "bar",
help: Some("Some help for bar"),
},
Parameter::NamedValue {
parameter_name: "baz",
argument_name: "TEST",
help: Some("Some help for baz"),
},
],
},
};
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "foo"),
Ok(Some("a"))
);
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "bar"),
Ok(Some(""))
);
// No argument so mark as not found
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "baz"),
Ok(None)
);
// Empty argument
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz="], "baz"),
Ok(Some(""))
);
// Short argument
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz=1"], "baz"),
Ok(Some("1"))
);
// Long argument
assert_eq!(
argument_finder(
&item,
&["a", "--bar", "--baz=abcdefghijklmnopqrstuvwxyz"],
"baz"
),
Ok(Some("abcdefghijklmnopqrstuvwxyz"))
);
// Not an argument
assert_eq!(
argument_finder(&item, &["a", "--bar", "--baz"], "quux"),
Err(Error::NotFound)
);
// Missing named
assert_eq!(argument_finder(&item, &["a"], "baz"), Ok(None));
}
}