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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//! # 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 command of `greet` which requires one argument, and if not given returns an error. It is as follows:
//! 
//! ```rust
//! use shellfish::Command;
//! use shellfish::Shell;
//! use std::error::Error;
//! use std::fmt;
//! 
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Define a shell
//!     let mut shell = Shell::new((), "<[Shellfish Example]>-$ ");
//! 
//!     // Add a command
//!     shell.commands.insert(
//!         "greet".to_string(),
//!         Command::new("greets you.".to_string(), greet),
//!     );
//! 
//!     // Run the shell
//!     shell.run()?;
//! 
//!     Ok(())
//! }
//! 
//! /// Greets the user
//! fn greet(_state: &mut (), 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(())
//! }
//! 
//! /// 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::io;
use std::io::prelude::*;
use std::fmt::Display;

pub mod command;
pub use command::Command;

#[cfg(feature = "crossterm")]
use crossterm::{
    cursor, event,
    event::{read, Event},
    execute, queue, terminal,
};

/// A shell represents a shell for editing commands in.
///
/// A command cannot be named `help`.
#[derive(Clone)]
pub struct Shell<T, M: Display> {
    /// 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,
}

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

    /// Starts running the shell
    pub fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Command history
        let mut history: Vec<String> = Vec::new();

        // Get the stdin & stdout
        #[cfg(not(feature = "crossterm"))]
        let stdin = io::stdin();
        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 = "crossterm"))]
            {
                stdin.read_line(&mut line)?;
            }
            #[cfg(feature = "crossterm")]
            {
                // Get the length of the prompt.
                let prompt_len = self.prompt.to_string().len();

                // Move to the end of the prompt and enable raw mode.
                execute!(
                    stdout,
                    cursor::MoveToColumn(prompt_len as u16 + 1)
                )?;
                crossterm::terminal::enable_raw_mode()?;

                // Gets our place in history
                let mut history_place = history.len() as i64;

                loop {
                    if let Event::Key(k) = read()? {
                        match k.code {
                            // Up & Down arrows go forwards and back in history
                            event::KeyCode::Down | event::KeyCode::Up => {
                                // Goes back or forwards
                                match k.code {
                                    event::KeyCode::Up => history_place -= 1,
                                    event::KeyCode::Down => history_place += 1,
                                    _ => (),
                                }

                                // Tries to get the corresponsing line. If it can then we
                                // read the line to replace the current one.
                                if let Some(hist_line) =
                                    history.get(history_place as usize)
                                {
                                    // Get the line
                                    line = hist_line.to_string();

                                    // Clear the current line
                                    execute!(
                                        stdout,
                                        terminal::Clear(
                                            terminal::ClearType::CurrentLine
                                        )
                                    )?;
                                    execute!(stdout, cursor::MoveToColumn(0))?;

                                    // Print a new prompt and the historic line.
                                    print!("{}{}", self.prompt, line);
                                }
                            }
                            event::KeyCode::Char(c) => {
                                // Checks if the user pressed a Ctrl command
                                if k.modifiers
                                    .contains(event::KeyModifiers::CONTROL)
                                {
                                    // Ctrl+D quits the shell, if there is an
                                    // empty line.
                                    if c == 'd' && line.is_empty() {
                                        terminal::disable_raw_mode()?;
                                        break '_shell;
                                    }
                                    // Ctrl+C quits entering the current
                                    // command.
                                    if c == 'c' {
                                        // Print a new prompt.
                                        execute!(
                                            stdout,
                                            cursor::MoveToColumn(0)
                                        )?;
                                        println!();
                                        continue '_shell;
                                    }
                                } else {
                                    // Get the cursor position
                                    let pos =
                                        usize::from(cursor::position()?.0)
                                            - prompt_len;

                                    // Insert into the string at said position.
                                    line.insert(pos, c);

                                    // Get the rest of the line and insert it.
                                    let line_chars =
                                        line.chars().collect::<Vec<char>>();
                                    let mut rest_of_line = String::new();
                                    for i in &line_chars[pos..] {
                                        rest_of_line.push(*i)
                                    }
                                    print!("{}", rest_of_line);

                                    queue!(
                                        stdout,
                                        cursor::MoveLeft(
                                            (rest_of_line.len() as u16) - 1
                                        )
                                    )?;
                                }
                            }
                            event::KeyCode::Enter => break,
                            event::KeyCode::Backspace => {
                                // Get the cursor position
                                let pos = usize::from(cursor::position()?.0)
                                    - prompt_len;

                                if pos <= line.len() && pos > 0 {
                                    line.remove(pos - 1);
                                    execute!(
                                        stdout,
                                        terminal::Clear(
                                            terminal::ClearType::CurrentLine
                                        )
                                    )?;
                                    execute!(stdout, cursor::MoveToColumn(0))?;
                                    print!("{}{}", self.prompt, line);
                                    execute!(
                                        stdout,
                                        cursor::MoveToColumn(
                                            (prompt_len + pos) as u16
                                        )
                                    )?;
                                }
                            }
                            event::KeyCode::Left => {
                                if (cursor::position()?.0 as usize)
                                    > prompt_len
                                {
                                    execute!(stdout, cursor::MoveLeft(1))?;
                                }
                            }
                            event::KeyCode::Right => {
                                if (cursor::position()?.0 as usize)
                                    <= (prompt_len + line.len())
                                {
                                    execute!(stdout, cursor::MoveRight(1))?;
                                }
                            }
                            _ => (),
                        }
                    }
                    stdout.flush()?;
                }
                execute!(stdout, cursor::MoveToColumn(0))?;
                crossterm::terminal::disable_raw_mode()?;
            }

            // Append this to the history
            history.push(line);

            let line = history.last().unwrap();

            // Tokenise the line
            match Self::unescape(line.trim()) {
                Ok(line) => {
                    if let Some(command) = line.get(0) {
                        // Add some padding.
                        println!("\n");

                        match command.as_str() {
                            "quit" | "exit" => break '_shell,
                            "help" => {
                                // Print information about built-in commands
                                println!(
                                    "    help - displays help information."
                                );
                                println!("    quit - quits the shell.");
                                println!("    exit - exits the shell.");
                                for (name, command) in &self.commands {
                                    println!("    {} - {}", name, command.help);
                                }
                            }
                            _ => {
                                // Attempt to find the command
                                let command = self.commands.get(&line[0]);

                                // Checks if we got it
                                match command {
                                    Some(command) => {
                                        if let Err(e) = (command.command)(
                                            &mut self.state,
                                            line,
                                        ) {
                                            eprintln!("\x1b[91mCommand exited unsuccessfully:\n{}\n({:?})\x1b[0m", &e, &e)
                                        }
                                    }
                                    None => {
                                        eprintln!("\x1b[91mCommand not found: {}\x1b[0m", line[0])
                                    }
                                }
                            }
                        }
                    }
                }
                Err(e) => eprintln!("\x1b[91m{}\x1b[0m", e.as_str()),
            }

            // Add some padding
            println!();
        }
        Ok(())
    }

    /// Unescapes a line and gets the arguments.
    fn unescape(r#str: &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 r#str.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)
    }
}