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
use super::*;

type CommandAction = fn(&mut Repl, &str);

/// A command definition.
pub struct Command {
	/// The command name.
	pub name: &'static str,
	/// Arguments expected type.
	pub arg_type: CmdArgs,
	/// Help string.
	pub help: &'static str,
	/// Action to take.
	pub action: CommandAction,
}

/// Command arguments variants.
#[derive(Clone)]
pub enum CmdArgs {
	/// No arguments.
	None,
	/// Command accepts a local filename.
	Filename,
	/// Optional unprocessed text may be accepted.
	Text,
	/// A Rust expression.
	Expr,
}

impl Command {
	pub fn new(
		name: &'static str,
		arg_type: CmdArgs,
		help: &'static str,
		action: CommandAction,
	) -> Self {
		Command {
			name: name,
			arg_type: arg_type,
			help: help,
			action: action,
		}
	}
}

impl Clone for Command{
	fn clone(&self) -> Self {
		Command {
	 name: self.name,
	 arg_type: self.arg_type.clone(),
	 help: self.help,
	 action: self.action,
	}
	}
}

pub trait Commands {
	/// Builds the help string of the commands.
	fn build_help_response(&self, command: Option<&str>) -> String;
	/// Conveniance function to lookup the Commands and return if found.
	fn find_command(&self, command: &str) -> Result<Command, String>;
}

impl Commands for Vec<Command> {
	fn build_help_response(&self, command: Option<&str>) -> String {
		let mut ret = String::new();

		let write_cmd_line = |cmd: &Command, str_builder: &mut String| {
			str_builder.push_str(cmd.name);

			match cmd.arg_type {
				CmdArgs::None => (),
				CmdArgs::Filename => str_builder.push_str(" <filename>"),
				CmdArgs::Text => str_builder.push_str(" [text]"),
				CmdArgs::Expr => str_builder.push_str(" <expr>"),
			}
			str_builder.push(' ');
			str_builder.push_str(cmd.help);
			str_builder.push('\n');
		};

		if let Some(cmd) = command {
			match self.find_command(cmd) {
				Err(e) => ret.push_str(&e),
				Ok(cmd) => write_cmd_line(&cmd, &mut ret),
			}
		} else {
			ret.push_str("Available commands:\n");
			self.iter().for_each(|cmd| write_cmd_line(cmd, &mut ret));
		}
		ret
	}

	fn find_command(&self, command: &str) -> Result<Command, String> {
		match self.iter().find(|c| c.name == command) {
				None => Err(format!("unrecognized command: {}", command)),
				Some(cmd) => Ok(cmd.clone()),
			}
	}
}