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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//! # Shellfish
//! 
//! Shellfish is a library to include interactive shells within a program. This may be useful when building terminal application where a persistent state is needed, so a basic cli is not enough; but a full tui is over the scope of the project. Shellfish provides a middle way, allowing interactive command editing whilst saving a state that all commands are given access to.
//! 
//! ## The shell
//! 
//! By default the shell contains only 3 built-in commands:
//! 
//!  * `help` - displays help information.
//!  * `quit` - quits the shell.
//!  * `exit` - exits the shell.
//! 
//! The last two are identical, only the names differ.
//! 
//! When a command is added by the user (see bellow) the help is automatically generated and displayed. Keep in mind this help should be kept rather short, and any additional help should be through a dedicated help option.
//! 
//! ## Example
//! 
//! The following code creates a basic shell, with the added commands:
//!  * `greet`, greets the user.
//!  * `echo`, echoes the input.
//!  * `count`, increments a counter.
//! 
//! Also, if run with arguments than the shell is run non-interactvely.
//! 
//! ```rust
//! use shellfish::{app, Command, Shell};
//! use std::convert::TryInto;
//! use std::error::Error;
//! use std::fmt;
//! use std::ops::AddAssign;
//! 
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Define a shell
//!     let mut shell = Shell::new(0_u64, "<[Shellfish Example]>-$ ");
//! 
//!     // Add some commands
//!     shell.commands.insert(
//!         "greet".to_string(),
//!         Command::new("greets you.".to_string(), greet),
//!     );
//! 
//!     shell.commands.insert(
//!         "echo".to_string(),
//!         Command::new("prints the input.".to_string(), echo),
//!     );
//! 
//!     shell.commands.insert(
//!         "count".to_string(),
//!         Command::new("increments a counter.".to_string(), count),
//!     );
//! 
//!     // Check if we have > 2 args, if so no need for interactive shell
//!     let mut args = std::env::args();
//!     if args.nth(1).is_some() {
//!         // Create the app from the shell.
//!         let mut app: app::App<u64, app::DefaultCommandLineHandler> =
//!             shell.try_into()?;
//! 
//!         // Set the binary name
//!         app.handler.proj_name = Some("shellfish-example".to_string());
//!         app.load_cache()?;
//! 
//!         // Run it
//!         app.run_args()?;
//!     } else {
//!         // Run the shell
//!         shell.run()?;
//!     }
//!     Ok(())
//! }
//! 
//! /// Greets the user
//! fn greet(_state: &mut u64, args: Vec<String>) -> Result<(), Box<dyn Error>> {
//!     let arg = args.get(1).ok_or_else(|| Box::new(GreetingError))?;
//!     println!("Greetings {}, my good friend.", arg);
//!     Ok(())
//! }
//! 
//! /// Echos the input
//! fn echo(_state: &mut u64, args: Vec<String>) -> Result<(), Box<dyn Error>> {
//!     let mut args = args.iter();
//!     args.next();
//!     for arg in args {
//!         print!("{} ", arg);
//!     }
//!     println!();
//!     Ok(())
//! }
//! 
//! /// Acts as a counter
//! fn count(state: &mut u64, _args: Vec<String>) -> Result<(), Box<dyn Error>> {
//!     state.add_assign(1);
//!     println!("You have used this counter {} times", state);
//!     Ok(())
//! }
//! 
//! /// Greeting error
//! #[derive(Debug)]
//! pub struct GreetingError;
//! 
//! impl fmt::Display for GreetingError {
//!     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//!         write!(f, "No name specified")
//!     }
//! }
//! 
//! impl Error for GreetingError {}
//! 
//! ```

use std::collections::HashMap;
use std::fmt::Display;
use std::io;
use std::io::prelude::*;

pub mod command;
pub use command::Command;

pub mod handler;
pub use handler::Handler;

#[cfg(feature = "app")]
pub mod app;
#[cfg(feature = "app")]
pub use app::App;

#[cfg(feature = "rustyline")]
use rustyline::{error::ReadlineError, Editor};

/// A shell represents a shell for editing commands in.
///
/// A command cannot be named `help`.
#[derive(Clone)]
pub struct Shell<T, M: Display, H: Handler<T>> {
    /// The shell prompt.
    ///
    /// It can be anything which implements Display and can therefore be
    /// printed (This allows for prompts that change with the state.)
    pub prompt: M,
    /// This is a list of commands for the shell. The hashmap key is the
    /// name of the command (ie `"greet"`) and the value is a wrapper
    /// to the function it corresponds to (as well as help information.)
    pub commands: HashMap<String, Command<T>>,
    /// This is the state of the shell. This stores any values that you
    /// need to be persisted over multiple shell commands. For example
    /// it may be a simple counter or maybe a session ID.
    pub state: T,
    /// This is the handler for commands. See the [`Handler`](crate::Handler)
    /// documentation for more.
    pub handler: H,
    /// This is the description of the shell as a whole. This is displayed when
    /// requesting help information.
    pub description: String,
}

impl<T, M: Display> Shell<T, M, handler::DefaultHandler> {
    /// Creates a new shell
    pub fn new(state: T, prompt: M) -> Shell<T, M, handler::DefaultHandler> {
        Shell {
            prompt,
            commands: HashMap::new(),
            state,
            handler: handler::DefaultHandler(),
            description: String::new(),
        }
    }
}

impl<T, M: Display, H: Handler<T>> Shell<T, M, H> {
    /// Creates a new shell with the given handler.
    pub fn new_with_handler(state: T, prompt: M, handler: H) -> Self {
        Shell {
            prompt,
            commands: HashMap::new(),
            state,
            handler,
            description: String::new(),
        }
    }

    /// Starts running the shell
    pub fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Get the stdin & stdout.
        #[cfg(not(feature = "rustyline"))]
        let stdin = io::stdin();
        #[cfg(feature = "rustyline")]
        let mut rl = Editor::<()>::new();
        let mut stdout = io::stdout();

        '_shell: loop {
            // Display the prompt
            print!("{}", self.prompt);
            stdout.flush()?;

            // Read a line
            let mut line = String::new();

            #[cfg(not(feature = "rustyline"))]
            {
                stdin.read_line(&mut line)?;
            }
            #[cfg(feature = "rustyline")]
            {
                let readline = rl.readline(&self.prompt.to_string());
                match readline {
                    Ok(rl_line) => {
                        rl.add_history_entry(&rl_line);
                        line = rl_line;
                    }
                    Err(ReadlineError::Interrupted) => continue '_shell,
                    Err(ReadlineError::Eof) => break '_shell,
                    Err(err) => return Err(Box::new(err)),
                }
            }

            // Runs the line
            match Self::unescape(line.trim()) {
                Ok(line) => {
                    self.handler.handle(
                        line,
                        &self.commands,
                        &mut self.state,
                        &self.description,
                    );
                }
                Err(e) => eprintln!("\x1b[91m{}\x1b[0m", e.as_str()),
            }
        }
        Ok(())
    }

    /// Unescapes a line and gets the arguments.
    fn unescape(command: &str) -> Result<Vec<String>, String> {
        // Create a vec to store the split int.
        let mut vec = vec![String::new()];

        // Are we in an escape sequence?
        let mut escape = false;

        // Are we in a string?
        let mut string = false;

        // Go through each char in the string
        for c in command.chars() {
            let segment = vec.last_mut().unwrap();
            if escape {
                match c {
                    '\\' => segment.push('\\'),
                    ' ' if !string => segment.push(' '),
                    'n' => segment.push('\n'),
                    'r' => segment.push('\r'),
                    't' => segment.push('\t'),
                    '"' => segment.push('"'),
                    _ => {
                        return Err(format!(
                            "Error: Unhandled escape sequence \\{}",
                            c
                        ))
                    }
                }
                escape = false;
            } else {
                match c {
                    '\\' => escape = true,
                    '"' => string = !string,
                    ' ' if string => segment.push(c),
                    ' ' if !string => vec.push(String::new()),
                    _ => segment.push(c),
                }
            }
        }

        if vec.len() == 1 && vec[0].is_empty() {
            vec.clear();
        }

        Ok(vec)
    }
}