schala/schala-repl/src/help.rs

64 lines
2.2 KiB
Rust
Raw Normal View History

2019-06-04 15:02:51 -07:00
use std::fmt::Write as FmtWrite;
2021-10-07 01:19:35 -07:00
use colored::*;
2019-06-04 15:02:51 -07:00
2021-11-24 23:51:30 -08:00
use crate::{
command_tree::CommandTree, language::ProgrammingLanguageInterface, InterpreterDirectiveOutput, Repl,
};
2021-10-14 00:56:01 -07:00
pub fn help<L: ProgrammingLanguageInterface>(
repl: &mut Repl<L>,
arguments: &[&str],
) -> InterpreterDirectiveOutput {
2021-10-07 01:19:35 -07:00
match arguments {
2021-10-14 02:08:32 -07:00
[] => global_help(repl),
2021-10-07 01:19:35 -07:00
commands => {
let dirs = repl.get_directives();
Some(match get_directive_from_commands(commands, &dirs) {
None => format!("Directive `{}` not found", commands.last().unwrap()),
Some(dir) => {
let mut buf = String::new();
let cmd = dir.get_cmd();
let children = dir.get_children();
writeln!(buf, "`{}` - {}", cmd, dir.get_help()).unwrap();
for sub in children.iter() {
2021-11-24 23:51:30 -08:00
writeln!(buf, "\t`{} {}` - {}", cmd, sub.get_cmd(), sub.get_help()).unwrap();
2021-10-07 01:19:35 -07:00
}
buf
}
})
2019-06-06 23:52:41 -07:00
}
2019-06-04 15:02:51 -07:00
}
}
2021-11-24 23:51:30 -08:00
fn get_directive_from_commands<'a>(commands: &[&str], dirs: &'a CommandTree) -> Option<&'a CommandTree> {
2021-10-07 01:19:35 -07:00
let mut directive_list = dirs.get_children();
let mut matched_directive = None;
for cmd in commands {
2021-11-24 23:51:30 -08:00
let found = directive_list.iter().find(|directive| directive.get_cmd() == *cmd);
2021-10-07 01:19:35 -07:00
if let Some(dir) = found {
directive_list = dir.get_children();
}
2019-06-06 22:36:44 -07:00
2021-10-07 01:19:35 -07:00
matched_directive = found;
}
matched_directive
2019-06-06 22:36:44 -07:00
}
2021-10-14 00:56:01 -07:00
fn global_help<L: ProgrammingLanguageInterface>(repl: &mut Repl<L>) -> InterpreterDirectiveOutput {
2021-10-07 01:19:35 -07:00
let mut buf = String::new();
2019-06-04 15:02:51 -07:00
2021-11-24 23:51:30 -08:00
writeln!(buf, "{} version {}", "Schala REPL".bright_red().bold(), crate::VERSION_STRING).unwrap();
2021-10-07 01:19:35 -07:00
writeln!(buf, "-----------------------").unwrap();
2019-06-04 15:02:51 -07:00
2021-10-07 01:19:35 -07:00
for directive in repl.get_directives().get_children() {
2021-11-24 23:51:30 -08:00
writeln!(buf, "{}{} - {}", repl.sigil, directive.get_cmd(), directive.get_help()).unwrap();
2021-10-07 01:19:35 -07:00
}
2019-06-04 15:02:51 -07:00
2021-10-14 02:08:32 -07:00
writeln!(buf).unwrap();
2021-11-24 23:51:30 -08:00
writeln!(buf, "Language-specific help for {}", <L as ProgrammingLanguageInterface>::language_name())
.unwrap();
2021-10-07 01:19:35 -07:00
writeln!(buf, "-----------------------").unwrap();
Some(buf)
2019-06-04 15:02:51 -07:00
}