schala/schala-repl/src/repl/command_tree.rs
greg ac0050e5d1 Truncate command list passed to command function
Only pass it the arguments after its own path, if any exist
2019-03-16 18:33:31 -07:00

59 lines
1.8 KiB
Rust

use super::Repl;
pub type BoxedCommandFunction = Box<(fn(&mut Repl, &[&str]) -> Option<String>)>;
#[derive(Clone)]
pub enum CommandTree {
Terminal {
name: String,
help_msg: Option<String>,
function: Option<BoxedCommandFunction>,
},
NonTerminal {
name: String,
children: Vec<CommandTree>,
help_msg: Option<String>,
},
Top(Vec<CommandTree>),
}
impl CommandTree {
pub fn term(s: &str, help: Option<&str>) -> CommandTree {
CommandTree::Terminal {name: s.to_string(), help_msg: help.map(|x| x.to_string()), function: None }
}
pub fn term_with_function(s: &str, help: Option<&str>, func: BoxedCommandFunction) -> CommandTree {
CommandTree::Terminal {name: s.to_string(), help_msg: help.map(|x| x.to_string()), function: Some(func) }
}
pub fn nonterm(s: &str, help: Option<&str>, children: Vec<CommandTree>) -> CommandTree {
CommandTree::NonTerminal {
name: s.to_string(),
help_msg: help.map(|x| x.to_string()),
children,
}
}
pub fn get_cmd(&self) -> &str {
match self {
CommandTree::Terminal { name, .. } => name.as_str(),
CommandTree::NonTerminal {name, ..} => name.as_str(),
CommandTree::Top(_) => "",
}
}
pub fn get_help(&self) -> &str {
match self {
CommandTree::Terminal { help_msg, ..} => help_msg.as_ref().map(|s| s.as_str()).unwrap_or(""),
CommandTree::NonTerminal { help_msg, .. } => help_msg.as_ref().map(|s| s.as_str()).unwrap_or(""),
CommandTree::Top(_) => ""
}
}
pub fn get_children(&self) -> Vec<&str> {
match self {
CommandTree::Terminal { .. } => vec![],
CommandTree::NonTerminal { children, .. } => children.iter().map(|x| x.get_cmd()).collect(),
CommandTree::Top(children) => children.iter().map(|x| x.get_cmd()).collect(),
}
}
}