JFLib

26. Command trees: base::cmdtree#

lib/base/cmdtree.rs parses the lines of IOS-like command lines: any unique prefix of a keyword works (sh ip int br), ? lists what may follow with its help text, Tab completes, modes have their prompts, no negates, parameters are typed, and an error knows its position for the ^ marker. The tree holds no actions: the app matches on its own command type C (an enum) and does the work; JFNetworker's IOS-like console (crates/jfn_sim/cli/ios.rs in JFNetworker) is the large example, apps/coretest's group cmdtree the small one.

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum C { Enable, ShowRoute, Hostname, Interface, IpAddr, Shutdown }

let mut t: Tree<C> = Tree::new();
let exec = t.mode("#", "Commands at the privileged level:", None, None);
let conf = t.mode("(config)#", "Commands for the whole device:", Some(exec), Some("Undo a setting or restore its default"));
let ifm = t.mode("(config-if)#", "Commands for this interface:", Some(conf), Some("Undo a setting or restore its default"));
t.add(exec, "enable", "Switch to the privileged level", Some(C::Enable), 0);
t.add(exec, "show", "Display the state of the device", None, 0);
t.add(exec, "show ip", "IPv4 state", None, 0);
t.add(exec, "show ip route", "Routes this device knows", Some(C::ShowRoute), 0);
t.add(conf, "hostname", "Give the device a name", None, F_NO);      // "no hostname" too
t.add(conf, "hostname WORD=name", "The new name", Some(C::Hostname), 0);
t.add_no(conf, "hostname", C::Hostname);                            // the no-form ends early
t.add(conf, "interface NAME=if", "", Some(C::Interface), 0);        // names from the app
t.add(ifm, "ip address A.B.C.D=addr MASK=mask", "The network mask", Some(C::IpAddr), 0);
t.add(ifm, "shutdown", "Switch the interface off", Some(C::Shutdown), F_NO);

match t.parse(conf, line, &names) {
    Ok(p) if p.cmd == C::Hostname => set_name(if p.no { "Router" } else { p.text("name").unwrap_or("") }),
    Ok(p) => run(p),
    Err(e) => out(&e.render(prompt.len(), line)),   // "% Invalid input detected at '^' marker."
}
out(&t.help(ifm, "ip address 10.0.0.1 ", &names).render(prompt.len(), line));   // "?" after a line
let c = t.complete(conf, "int gi", &names);   // c.line == Some("int GigabitEthernet")
  • Paths are words: a keyword stands for itself (trunk=mode stores it under the key mode); parameters are <lo-hi>, A.B.C.D, MASK (its length), A.B.C.D/nn, H.H.H (MAC), WORD, LINE (the rest of the line) and NAME .. NAME9 (lists the app gives through the Names trait, e.g. its interfaces; * in a name is a number: "Loopback*"). Shared prefixes merge; add on an existing path only sets its help, command and flags. A later value of a key hides an earlier one, so name WORD=name reads as the word.
  • also(mode, path, target): the words after target may follow path too, for options in any order (ping X repeat 5 size 100 df-bit).
  • Matching: case is ignored, a whole keyword wins over a longer one it prefixes (ip / ipv6), WORD and LINE take only what no keyword takes, a name's type may be abbreviated and stand apart from its number (Gi 0/0/0). Ambiguity is an error (% Ambiguous command: "s").
  • Error::Invalid(byte) is the first character no candidate accepts (show ip routee marks the second e); Error::render(col, line) writes the console text with the marker under it. Incomplete and Ambiguous render as the usual short % lines; knows_first tells an unknown first word (an IOS-like EXEC looks those up as host names) from a later error.
  • Help (Help::render) lists labels in ASCII order (parameters and capitalised interface types before lowercase keywords), two spaces after the longest, <cr> when the line may end, the mode's title for an empty line; a partly typed word lists what it may become (show shutdown ). F_HIDDEN keeps a command out of help and Tab.
  • Modes carry their prompt suffix and the mode they fall back to (mode_info(m).parent): an IOS-like console tries a line that fails in a configuration submode again in the global configuration; the app decides when to do that. find_mode(prompt) finds a mode by its prompt, so a part of an app that adds its own modes later (JFNetworker's access-list modes) needs no fixed mode number.
  • Write the help texts, mode titles and status lines in your own words; only the command words, their syntax, configuration lines and short % errors should follow the original (JFNetworker's rule, see its README).
  • IPv6 parameters: X:X:X:X::X (an address in the text of RFC 4291 2.2; Parsed::ip6 gives its 16 bytes) and X:X:X:X::X/<0-128> (with a prefix length; Parsed::prefix6); cmdtree::parse_ipv6 reads such an address alone.

Source: docs/GUIDE.md in the JFLib repository.