rusty_cmd/
command_handler.rs

1/// Trait for creating new commands
2///
3/// Returning CommandResult::Break instructs the Cmd.run() loop to break.
4///
5/// # Examples
6///
7/// ```rust
8/// // CommandHandler that prints out help message
9/// use std::io;
10/// use std::io::Write;
11/// use rusty_cmd::command_handler::{CommandHandler, CommandResult};
12///
13/// #[derive(Default)]
14/// pub struct Help;
15///
16/// impl<W> CommandHandler<W> for Help
17///     where W: std::io::Write {
18///     fn execute(&self, output: &mut W, args: &[&str]) -> CommandResult {
19///         writeln!(output, "Help message").unwrap();
20///         CommandResult::Continue
21///     }
22/// }
23///
24/// /// CommandHandler that prints out a greeting
25/// #[derive(Default)]
26/// pub struct Greet;
27///
28/// impl<W> CommandHandler<W> for Greet
29///     where W: std::io::Write {
30///     fn execute(&self, output: &mut W, args: &[&str]) -> CommandResult {
31///         let joined_args = args.join(", ");
32///         match args.len() {
33///             0 => output.write(format!("Hello, {}!", joined_args).as_bytes()).unwrap(),
34///             _ => output.write(b"Hello!").unwrap(),
35///         };
36///         CommandResult::Continue
37///     }
38/// }
39/// ```
40pub trait CommandHandler<W>
41where
42    W: std::io::Write,
43{
44    /// Required method to execute a command
45    fn execute(&self, output: &mut W, args: &[&str]) -> CommandResult;
46}
47
48/// Enum to determine whether to continue or break the Cmd.run() loop
49pub enum CommandResult {
50    Continue,
51    Break,
52}
53
54/// Blanket CommandHandler implementation for Fn(&mut W, &[&str]) -> CommandResult
55/// allows CommandHandlers to be registered as closures
56impl<F, W> CommandHandler<W> for F
57where
58    W: std::io::Write,
59    F: Fn(&mut W, &[&str]) -> CommandResult,
60{
61    fn execute(&self, output: &mut W, args: &[&str]) -> CommandResult {
62        self(output, args)
63    }
64}