ishell 0.3.1

Pseudo-interactive shell interface for Rust
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Interactive shell for Rust
//!
//! Provides an IShell interface to run commands through.
//! These are the advantages:
//! - Each command returns an `std::process::Output` type with stdout and stderr captured (while also being logged)
//! - `cd` commands are remembered, despite each command running sequentially, each in a new true shell (i.e. `sh`)

#![warn(missing_docs)]

use std::env;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::sync::{Arc, Mutex};
use std::thread;

/// A module for handling shell initialization errors.
///
/// This module defines the `ShellInitError` enum, which represents various errors
/// that can occur when attempting to initialize a shell. These errors primarily
/// relate to directory access, including issues with directory existence and permissions.
///
/// The `ShellInitError` enum provides a way to handle errors when constructing an
/// `IShell` instance with `IShell::from_path(...).
pub mod error;

use error::ShellInitError;

#[cfg(feature = "logging")]
use log::{error, info, warn};

/// Leech output from stdout/stderr while also storing the resulting output
macro_rules! leech_output {
    ($out:ident, $out_buf:ident, $log_method:ident) => {
        thread::spawn({
            let output_buffer_clone = Arc::clone($out_buf);
            move || {
                if let Some(output) = $out {
                    let reader = BufReader::new(output);
                    for line in reader.lines() {
                        if let Ok(line) = line {
                            #[cfg(feature = "logging")]
                            $log_method!("{}", line);
                            match output_buffer_clone.lock() {
                                Err(_err) => {
                                    #[cfg(feature = "logging")]
                                    error!("Failed to lock {} buffer! {}", stringify!($out), _err);
                                    return;
                                }
                                Ok(mut vec) => {
                                    vec.push(line);
                                }
                            }
                        }
                    }
                }
            }
        })
    };
}

/// Representation of the output of a command executed in an IShell.
///
/// The `ShellOutput` struct holds the results of a command that was run through a shell,
/// including the exit code, standard output, and standard error output.
///
/// # Examples
///
/// ```rust
/// use ishell::{IShell, ShellOutput};
///
/// let shell = IShell::new();
/// let shell_output = shell.run_command("true");
///
/// // equivalent of `shell_output.code.unwrap() == 0`
/// assert!(shell_output.is_success());
/// assert!(shell_output.stdout.is_empty());
/// assert!(shell_output.stderr.is_empty());
/// ```
///
/// ```rust
/// use ishell::{IShell, ShellOutput};
///
/// let shell = IShell::new();
/// let result = shell.run_command("echo 'Hello, world!'");
///
/// assert!(result.is_success());
///
/// let target_result =
///    String::from_utf8(result.stdout).expect("Stdout contained invalid UTF-8!");
///
/// assert_eq!(target_result, "Hello, world!");
/// assert!(result.stderr.is_empty());
/// ```
pub struct ShellOutput {
    /// An optional exit code returned by the command.
    /// - If the command executed successfully, this will typically be `0`.
    /// - If the command failed or was terminated, this will contain a non-zero value.
    /// - If the command did not return an exit code, this will be `None`.
    pub code: Option<i32>,

    /// A vector of bytes containing the standard output produced by the command.
    /// - This field captures any output that the command printed to the standard output stream (if any).
    pub stdout: Vec<u8>,

    /// A vector of bytes containing the standard error output produced by the command.
    /// - This field captures any error messages or diagnostics that the command printed to the standard error stream.
    pub stderr: Vec<u8>,
}

impl ShellOutput {
    /// Check if output indicates a command was successful
    ///
    /// The check is done by comparing to 0.
    /// If no output is found, returns false
    pub fn is_success(&self) -> bool {
        self.code.unwrap_or(1) == 0
    }
}

/// A shell interface with memory
///
/// # Examples
///
/// ```rust
/// use ishell::IShell;
///
/// // Opening an IShell at the same directory as the shell running this program
/// let shell = IShell::new();
///
/// // Create a directory, travel into it and create another directory
/// shell.run_command("mkdir test");
/// shell.run_command("cd test");
/// shell.run_command("mkdir test2");
///
/// // Are we still in the `test` directory?..
/// let result = shell.run_command("ls");
/// let stdout_res = String::from_utf8(result.stdout).expect("Stdout contained invalid UTF-8!");
/// assert_eq!(stdout_res.trim(), "test2"); // Indeed we are
///
/// // Let's clean after ourselves
/// shell.run_command("cd ..");
/// shell.run_command("rm -r test");
/// ```
pub struct IShell {
    initial_dir: PathBuf,
    current_dir: Arc<Mutex<PathBuf>>,
}

impl Default for IShell {
    fn default() -> Self {
        Self::new()
    }
}

impl IShell {
    /// Constructs a new IShell with internal shell's
    /// directory set to the value of `std::env::current_dir()`.
    ///
    /// # Panics
    ///
    /// This function will panic due to `std::env::current_dir()` if any of the following is true:
    /// - Current directory (from where your program is ran) does not exist
    /// - There are insufficient permissions to access the current directory (from where your program is ran)
    /// - Directory (from where your program is ran) contains invalid UTF-8
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ishell::IShell;
    /// // Opening an IShell at the same directory as the shell running this program
    /// let shell = IShell::new();
    ///
    /// // Opening an IShell at the `/home/user/Desktop/` directory
    /// let desktop_shell = IShell::from_path("/home/user/Desktop/");
    ///
    /// // Opening an IShell at the directory "test123" or "./test123",
    /// // relative to the shell running this program
    /// let relative_test123_shell = IShell::from_path("test123");
    /// ```
    pub fn new() -> Self {
        let current_dir = env::current_dir().expect(
            "Failed to get current directory; it may not exist or you may not have permissions",
        );

        IShell {
            initial_dir: current_dir.clone(),
            current_dir: Arc::new(Mutex::new(current_dir)),
        }
    }

    /// Constructs a new IShell with internal shell's directory
    /// set to the value of
    ///
    /// <current_dir> / `initial_dir`
    ///
    /// if it exists.
    /// Otherwise, initial_dir is treated as a full path
    ///
    /// # Examples
    /// ```rust
    /// use ishell::IShell;
    ///
    /// // Opens a shell in relative (to the `std::env::current_dir()`)
    /// // directory `target` if it exists. If it does not,
    /// // tries to treat `target` as a full path
    /// let shell = IShell::from_path("target").unwrap();
    ///
    /// // Opens a shell at resolved path from current user running it
    /// let shell = IShell::from_path("~").unwrap();
    /// let result = shell.run_command("ls -l");
    ///
    /// let result = String::from_utf8(result.stdout).expect("Stdout contained invalid UTF-8!");
    /// println!("{}", result);
    /// ```
    pub fn from_path(initial_dir: impl AsRef<Path>) -> Result<Self, ShellInitError> {
        let initial_dir = initial_dir.as_ref();

        let current_dir = env::current_dir().expect(
            "Failed to get current directory; it may not exist or you may not have permissions.",
        );

        match Self::determine_new_directory(&current_dir, initial_dir) {
            Some(new_dir) => Ok(IShell {
                initial_dir: new_dir.clone(),
                current_dir: Arc::new(Mutex::new(new_dir)),
            }),
            None => Err(ShellInitError::DirectoryError(format!(
                "Couldn't open shell at either of {:#?} or {:#?}",
                initial_dir,
                current_dir.join(initial_dir)
            ))),
        }
    }

    /// Runs a command through IShell within its `current_dir`.
    ///
    /// Any `cd` command will not be _actually_ ran. Instead, inner directory of IShell (`current_dir`) will change
    /// accordingly. If `cd` is aliased to something else, (i.e. `changedir`), and you use this alias instead of `cd`,
    /// then IShell wont understand that you wanted it to change directory.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ishell::{ShellOutput, IShell};
    ///
    /// let shell = IShell::from_path("~").unwrap();
    /// let result: ShellOutput = shell.run_command("ls");
    /// ```
    pub fn run_command(&self, command: &str) -> ShellOutput {
        #[cfg(feature = "logging")]
        info!("Running: `{}`", command);

        if let Some(stripped_command) = command.strip_prefix("cd") {
            let new_dir = stripped_command.trim();
            let mut current_dir = self.current_dir.lock().unwrap();

            match Self::determine_new_directory(&*current_dir, new_dir) {
                Some(new_dir) => {
                    *current_dir = new_dir;
                    return self.create_output(Some(0), Vec::new(), Vec::new());
                }
                None => {
                    #[cfg(feature = "logging")]
                    {
                        error!("Failed to change directory to: {}", new_dir);
                        error!("Current directory: '{}'", current_dir.display());
                    }
                    return self.create_output(
                        Some(1),
                        Vec::new(),
                        Vec::from("Specified directory does not exist!"),
                    );
                }
            }
        }

        let child_process = self.spawn_process(command);
        match child_process {
            Ok(mut process) => {
                let (stdout_buffer, stderr_buffer) = (
                    Arc::new(Mutex::new(Vec::new())),
                    Arc::new(Mutex::new(Vec::new())),
                );

                let (stdout_handle, stderr_handle) = self.spawn_output_threads(
                    process.stdout.take(),
                    process.stderr.take(),
                    &stdout_buffer,
                    &stderr_buffer,
                );

                let status = process.wait().unwrap_or_else(|_err| {
                    #[cfg(feature = "logging")]
                    error!("Failed to wait for process: {}", _err);
                    ExitStatus::default()
                });

                if let Err(_err) = stdout_handle.join() {
                    #[cfg(feature = "logging")]
                    error!("Failed to join stdout thread: {:?}", _err);
                }
                if let Err(_err) = stderr_handle.join() {
                    #[cfg(feature = "logging")]
                    error!("Failed to join stderr thread: {:?}", _err);
                }

                let stdout = self.collect_output(&stdout_buffer);
                let stderr = self.collect_output(&stderr_buffer);

                ShellOutput {
                    code: status.code(),
                    stdout,
                    stderr,
                }
            }
            Err(e) => {
                #[cfg(feature = "logging")]
                error!("Couldn't spawn child process! {}", e);

                self.create_output(Some(-1), Vec::new(), Vec::from(format!("Error: {}", e)))
            }
        }
    }

    /// Forget current directory and go back to the directory initially specified.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ishell::IShell;
    ///
    /// // Opening an IShell at the same directory as the shell running this program
    /// let shell = IShell::new();
    ///
    /// shell.run_command("mkdir test123");
    /// shell.run_command("cd test123");
    ///
    /// // We just created this dir. It should be empty.
    /// let result = shell.run_command("ls");
    ///
    /// let result = String::from_utf8(result.stdout)
    ///     .expect("Stdout contained invalid UTF-8!");
    /// assert_eq!(result, "");
    ///
    /// // This will move us to the initial directory in which
    /// // the IShell was created (the same directory as the shell running this program)
    /// shell.forget_current_directory();
    ///
    /// let result = shell.run_command("ls test123");
    /// assert!(result.is_success());
    ///
    /// shell.run_command("rm -r test123");
    /// ```
    pub fn forget_current_directory(&self) {
        let mut current_dir = self.current_dir.lock().unwrap();
        *current_dir = self.initial_dir.clone();
    }

    fn create_output(&self, code: Option<i32>, stdout: Vec<u8>, stderr: Vec<u8>) -> ShellOutput {
        ShellOutput {
            code,
            stdout,
            stderr,
        }
    }

    fn spawn_process(&self, command: &str) -> std::io::Result<std::process::Child> {
        let current_dir = self.current_dir.lock().unwrap().clone();
        if cfg!(target_os = "windows") {
            Command::new("cmd")
                .args(["/C", command])
                .current_dir(current_dir)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()
        } else {
            Command::new("sh")
                .arg("-c")
                .arg(command)
                .current_dir(current_dir)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()
        }
    }

    fn spawn_output_threads(
        &self,
        stdout: Option<std::process::ChildStdout>,
        stderr: Option<std::process::ChildStderr>,
        stdout_buffer: &Arc<Mutex<Vec<String>>>,
        stderr_buffer: &Arc<Mutex<Vec<String>>>,
    ) -> (thread::JoinHandle<()>, thread::JoinHandle<()>) {
        let stdout_handle = leech_output!(stdout, stdout_buffer, info);
        let stderr_handle = leech_output!(stderr, stderr_buffer, warn);

        (stdout_handle, stderr_handle)
    }

    fn collect_output(&self, buffer: &Arc<Mutex<Vec<String>>>) -> Vec<u8> {
        match buffer.lock() {
            Ok(buffer) => buffer.join("\n").into_bytes(),
            Err(_err) => {
                #[cfg(feature = "logging")]
                error!("Couldn't lock buffer! {}", _err);
                // Need to return SOMETHING here.
                Vec::new()
            }
        }
    }

    /// Method to quickly check if given path is a valid directory
    fn is_valid_directory(path: &Path) -> bool {
        path.exists() && path.is_dir()
    }

    /// Method to determine the new directory
    /// Checks if `current_dir`/`new_dir` is a valid dir (and returns it if it is),
    /// if it isn't - checks if `new_dir` is a valid dir (and returns it if it is);
    /// if it isn't - returns None
    fn determine_new_directory<U: AsRef<Path>, T: AsRef<Path>>(
        current_dir: U,
        new_dir: T,
    ) -> Option<PathBuf> {
        let new_dir = new_dir.as_ref();
        let current_dir = current_dir.as_ref();

        // Perhaps the `new_dir` is relative to `current_dir`?
        let wanted_dir = current_dir.join(new_dir);
        if Self::is_valid_directory(&wanted_dir) {
            return Some(wanted_dir.to_path_buf());
        }

        // Maybe `new_dir` wasn't relative?
        if let Some(sanitized_dir) = Self::sanitize_path(new_dir) {
            if Self::is_valid_directory(&sanitized_dir) {
                return Some(sanitized_dir);
            } else {
                #[cfg(feature = "logging")]
                warn!(
                    "Neither the combined path {:#?} nor the sanitized path {:#?} is a valid directory.",
                    wanted_dir, sanitized_dir
                );
            }
        }

        // I guess `new_dir` doesn't exist...
        None
    }

    /// Expand tilde
    /// Inspired by https://github.com/splurf/simple-expand-tilde/blob/master/src/lib.rs
    fn sanitize_path(path: impl AsRef<Path>) -> Option<PathBuf> {
        let resolved_path = path.as_ref();

        if !resolved_path.starts_with("~") {
            return Some(resolved_path.to_path_buf());
        }
        if resolved_path == Path::new("~") {
            return dirs::home_dir();
        }

        dirs::home_dir().map(|mut home_dir| {
            if home_dir == Path::new("/") {
                // For when running as root
                resolved_path.strip_prefix("~").unwrap().to_path_buf()
            } else {
                home_dir.push(resolved_path.strip_prefix("~/").unwrap());
                home_dir
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn true_command() {
        let shell = IShell::new();

        let result = shell.run_command("true");
        assert!(result.is_success());
    }

    #[test]
    fn false_command() {
        let shell = IShell::new();

        let result = shell.run_command("false");
        assert!(!result.is_success());
    }

    #[test]
    fn echo_command() {
        // Checking stdout capture
        let shell = IShell::new();

        let result = shell.run_command("echo \"Hello, World!\"");
        let stdout_res = String::from_utf8(result.stdout).expect("Stdout contained invalid UTF-8!");
        assert_eq!(stdout_res, "Hello, World!");
    }

    #[test]
    fn dir_memory() {
        // Check for whether CD is remembered

        let shell = IShell::new();

        let unique_dir_1 = format!("test_{}", rand::random::<u32>());
        let unique_dir_2 = format!("test2_{}", rand::random::<u32>());

        shell.run_command(&format!("mkdir {}", unique_dir_1));
        shell.run_command(&format!("cd {}", unique_dir_1));
        shell.run_command(&format!("mkdir {}", unique_dir_2));

        let result = shell.run_command("ls");
        let stdout_res = String::from_utf8(result.stdout).expect("Stdout contained invalid UTF-8!");
        assert_eq!(stdout_res.trim(), unique_dir_2);

        shell.run_command("cd ..");
        shell.run_command(&format!("rm -r {}", unique_dir_1));
    }

    #[test]
    fn forget_current_dir() {
        let shell = IShell::new();

        let result = shell.run_command("echo $PWD");
        let pwd = String::from_utf8(result.stdout).expect("Stdout contained invalid UTF-8!");

        let unique_dir = format!("test_{}", rand::random::<u32>());

        shell.run_command(&format!("mkdir {}", unique_dir));
        shell.run_command(&format!("cd {}", unique_dir));
        shell.forget_current_directory();

        let result = shell.run_command("echo $PWD");
        let forgotten_pwd =
            String::from_utf8(result.stdout).expect("Stdout contained invalid UTF-8!");

        assert_eq!(pwd, forgotten_pwd);

        shell.run_command(&format!("rm -r {}", unique_dir));
    }

    #[test]
    fn dir_doesnt_exist() {
        let shell = IShell::new();

        let current_dir = shell.current_dir.lock().unwrap().clone();
        let res = shell.run_command("cd directory_that_doesnt_exist");
        let next_dir = shell.current_dir.lock().unwrap().clone();

        assert!(!res.is_success());
        assert_eq!(current_dir, next_dir);
    }

    #[test]
    fn relative_construct() {
        let main_shell = IShell::new();
        main_shell.run_command("cd target");
        let main_result = main_shell.run_command("ls");
        assert!(main_result.is_success());

        let target_shell = IShell::from_path("target").unwrap();
        let target_result = target_shell.run_command("ls");

        let target_result =
            String::from_utf8(target_result.stdout).expect("Stdout contained invalid UTF-8!");
        let main_result =
            String::from_utf8(main_result.stdout).expect("Stdout contained invalid UTF-8!");

        assert_eq!(target_result, main_result);
    }

    #[test]
    fn tilda_init() {
        let desktop_shell = IShell::from_path("~").unwrap();
        let shell = IShell::new();

        shell.run_command("cd ~");
        let res = shell.run_command("ls");
        let desktop_res = desktop_shell.run_command("ls");

        let res = String::from_utf8(res.stdout).expect("Stdout contained invalid UTF-8!");
        let desktop_res =
            String::from_utf8(desktop_res.stdout).expect("Stdout contained invalid UTF-8!");

        assert_eq!(res, desktop_res);
    }
}