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
#![cfg_attr(not(feature = "std"), no_std)]

pub(crate) mod re_exports {
  #[cfg(not(feature = "std"))]
  pub extern crate alloc;
  #[cfg(feature = "std")]
  pub use std as alloc;

  pub use alloc::{boxed::Box, collections::BTreeMap, format, string::String, sync::Arc, vec::Vec};
  pub use core::{future::Future, pin::Pin};
}

use core::future::Future as Future_;
use re_exports::*;

mod state;

pub use state::State;

pub mod commands;

pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");

#[derive(Clone)]
pub struct SeaShell<'a> {
  pub state: State,
  pub exit_handler: Arc<Box<dyn Fn(i32, &mut Self) + 'a>>,
  pub logger: Arc<Box<dyn Logger + 'a>>,
}

impl<'a> SeaShell<'a> {
  pub fn new(
    exit_handler: impl Fn(i32, &mut Self) + 'a,
    logger: impl Logger + 'a,
    unicode_supported: bool,
  ) -> Self {
    logger.info(&format!("Welcome to pirs version: {}", VERSION));
    logger.info(DESCRIPTION);
    logger.info("Type 'help' for a list of commands");
    logger.raw("\n");

    Self {
      exit_handler: Arc::new(Box::new(exit_handler)),
      state: State::new(commands::BUILT_IN_COMMANDS, unicode_supported),
      logger: Arc::new(Box::new(logger)),
    }
  }

  pub async fn handle_command(&mut self, input: impl AsRef<str>) {
    let input_ = input.as_ref();

    let input = input_
      .split_whitespace()
      .filter_map(|input| {
        let trimmed = input.trim();

        if trimmed.is_empty() {
          None
        } else {
          Some(trimmed.into())
        }
      })
      .collect::<Vec<String>>();

    if input.is_empty() {
      return;
    }

    self.state.history.push(input_.into());

    let code = match self.get_command(&input[0]) {
      Some(command) => {
        self.logger.debug(&format!("executing: {}...", input[0]));

        let out = (command.handler)(self.clone(), input.into_iter().skip(1).collect()).await;

        if let Some(self_) = out.0 {
          *self = self_;
        } else {
          return;
        }

        out.1
      }
      None => {
        self
          .logger
          .error(&format!("command not found: {}", input[0]));

        1
      }
    };

    self.state.set_last_exit_code(code);
  }

  pub fn get_command(&self, command: impl AsRef<str>) -> Option<&Command> {
    let command = command.as_ref();

    self.state.commands.iter().find(|c| c.name == command)
  }
}

#[derive(Clone)]
pub struct Command {
  name: &'static str,
  #[allow(clippy::type_complexity)]
  handler: for<'a> fn(SeaShell<'a>, Vec<String>) -> Future<'a, (Option<SeaShell<'a>>, i32)>,
}

pub trait Logger {
  fn debug(&self, message: &str);

  fn info(&self, message: &str);

  fn warn(&self, message: &str);

  fn error(&self, message: &str);

  fn raw(&self, message: &str);
}

pub(crate) type Future<'a, T> = Pin<Box<dyn Future_<Output = T> + 'a>>;

#[cfg(feature = "default-logger")]
pub mod default_logger;