8 Commits

13 changed files with 419 additions and 311 deletions

81
Cargo.lock generated
View File

@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "bitflags"
version = "2.6.0"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
[[package]]
name = "bstr"
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]]
name = "cc"
version = "1.2.7"
version = "1.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7"
checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229"
dependencies = [
"shlex",
]
@ -139,9 +139,9 @@ dependencies = [
[[package]]
name = "js-sys"
version = "0.3.76"
version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7"
checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
dependencies = [
"once_cell",
"wasm-bindgen",
@ -169,7 +169,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "liblambdashell"
name = "libloading"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
dependencies = [
"cfg-if",
"windows-targets",
]
[[package]]
name = "libpse"
version = "0.1.0"
dependencies = [
"color-print",
@ -182,16 +192,6 @@ dependencies = [
"whoami",
]
[[package]]
name = "libloading"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
dependencies = [
"cfg-if",
"windows-targets",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@ -210,9 +210,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.22"
version = "0.4.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
checksum = "04cbf5b083de1c7e0222a7a51dbfdba1cbe1c6ab0b15e29fff3f6c077fd9cd9f"
[[package]]
name = "lua-src"
@ -351,9 +351,9 @@ checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
[[package]]
name = "proc-macro2"
version = "1.0.92"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
dependencies = [
"unicode-ident",
]
@ -465,9 +465,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "syn"
version = "2.0.95"
version = "2.0.96"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a"
checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80"
dependencies = [
"proc-macro2",
"quote",
@ -476,18 +476,18 @@ dependencies = [
[[package]]
name = "thiserror"
version = "2.0.10"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3ac7f54ca534db81081ef1c1e7f6ea8a3ef428d2fc069097c079443d24124d3"
checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.10"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9465d30713b56a37ede7185763c3492a91be2f5fa68d958c44e41ab9248beb"
checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2"
dependencies = [
"proc-macro2",
"quote",
@ -530,9 +530,9 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
[[package]]
name = "wasm-bindgen"
version = "0.2.99"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396"
checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
dependencies = [
"cfg-if",
"once_cell",
@ -541,9 +541,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.99"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79"
checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
dependencies = [
"bumpalo",
"log",
@ -555,9 +555,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.99"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe"
checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@ -565,9 +565,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.99"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2"
checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
dependencies = [
"proc-macro2",
"quote",
@ -578,15 +578,18 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.99"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6"
checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.76"
version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc"
checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2"
dependencies = [
"js-sys",
"wasm-bindgen",

View File

@ -1,5 +1,5 @@
[package]
name = "liblambdashell"
name = "libpse"
version = "0.1.0"
edition = "2021"

View File

@ -1,24 +1,18 @@
use std::{io, process, str::SplitWhitespace, path::{Path, PathBuf}};
use uzers::User;
use std::{
io,
process,
str::SplitWhitespace,
path::{Path, PathBuf},
};
use crate::MapDisplay;
enum ValidStatus {
NoRootFolder,
TryExists(io::Error)
}
use crate::{history::History, session::MapDisplay, valid_pbuf::IsValid};
trait PathBufIsValid {
fn is_valid(&self) -> Result<PathBuf, ValidStatus>;
fn is_valid_or_home(&self) -> Option<PathBuf>;
}
impl PathBufIsValid for PathBuf {
fn is_valid_or_home(&self) -> Option<PathBuf> {
self.is_valid_or(self.is_dir(), home::home_dir)
}
}
trait ChangeDirectory {
trait ChangeDirectory<'a> {
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>;
fn specific_user_dir(&self, user: String) -> Option<PathBuf>;
@ -26,31 +20,7 @@ trait ChangeDirectory {
fn previous_dir(&self) -> Option<PathBuf>;
fn home_dir(&self) -> Option<PathBuf>;
}
impl PathBufIsValid for PathBuf {
fn is_valid(&self) -> Result<PathBuf, ValidStatus> {
match self.try_exists() {
Ok(true) => Ok(self.to_path_buf()),
Ok(false) => Err(ValidStatus::NoRootFolder),
Err(trye_error) => Err(ValidStatus::TryExists(trye_error))
}
}
fn is_valid_or_home(&self) -> Option<PathBuf> {
match self.is_valid() {
Ok(valid) => Some(valid),
Err(valid_status) => {
match valid_status {
ValidStatus::NoRootFolder => println!("cd: /root: No such file or directory"),
ValidStatus::TryExists(error) => println!("cd: {error}"),
};
None
},
}
}
}
impl ChangeDirectory for Command {
impl<'a> ChangeDirectory<'a> for Command<'a> {
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf> {
std::env::set_current_dir(new_path).map_or_display_none(|()| Some(new_path.to_path_buf()))
}
@ -117,26 +87,28 @@ impl ChangeDirectory for Command {
}
}
pub struct Command(String);
impl Command {
pub fn new(input: String) -> Self {
pub struct Command<'a>(&'a String);
impl<'a> Command<'a> {
pub const fn new(input: &'a String) -> Self {
Self(input)
}
pub fn spawn(&self, command_process: io::Result<process::Child>) {
command_process.map_or_display_none(|mut child| Some(child.wait()));
pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
match command_process {
Ok(mut child) => {
history.add(self.0.as_str());
child.wait().ok();
},
Err(_) => println!("pse: Unknown command: {}", self.0),
}
}
pub fn exec(&self) {
pub fn exec(&mut self, history: &mut History) {
let mut args = self.0.split_whitespace();
if let Some(command) = args.next() {
match command {
"cd" => {
self.change_directory(args);
},
command => {
self.spawn(process::Command::new(command).args(args).spawn());
}
"cd" => if self.change_directory(args).is_some() { history.add(self.0.as_str()) },
command => { self.spawn_sys_cmd(history, process::Command::new(command).args(args).spawn()); }
}
}
}

51
src/history.rs Normal file
View File

@ -0,0 +1,51 @@
use std::{fs::{File, OpenOptions}, io::{BufRead, BufReader, Write}, path::PathBuf};
use crate::{rc::{self}, session::{self, MapDisplay}, valid_pbuf::IsValid};
#[derive(Debug, Clone)]
pub struct History {
fs_history: Option<Vec<String>>,
history: Vec<String>,
file: Option<PathBuf>,
}
impl History {
pub fn init() -> Self {
let file = rc::config_dir().map(|mut config_dir| {
config_dir.push(".history");
config_dir.is_valid_file_or_create(b"");
config_dir
});
let fs_history = file.as_ref().and_then(|file| {
File::open(file).map_or_display_none(|file| {
Some(BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>())
})
});
Self {
history: Vec::new(),
fs_history,
file,
}
}
pub fn write_to_file_fallible(&mut self) {
if self.history.is_empty() { return; }
if let (Some(history_file), Some(fs_history)) = (&self.file, &self.fs_history) {
OpenOptions::new()
.append(true)
.open(history_file.as_path())
.map_or_display(|mut file| {
let newline_maybe = if fs_history.is_empty() { "" } else { "\n" };
let formatted = format!("{newline_maybe}{}", self.history.join("\n"));
file.write_all(formatted.as_bytes()).unwrap_or_else(session::shell_error)
});
}
}
pub fn add(&mut self, command: &str) {
match self.history.last() {
Some(last_cmd) => if last_cmd != command { self.history.push(command.to_owned()); },
None => self.history.push(command.to_owned()),
};
}
}

View File

@ -2,28 +2,9 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub mod session;
pub mod commands;
pub mod ps;
pub mod history;
pub mod terminal;
pub mod rc;
pub mod vm;
#[inline]
pub fn shell_error<E: core::fmt::Display>(err: E) {
color_print::ceprintln!("<bold,r>[!]:</> {err}")
}
pub trait MapDisplay<T, E: core::fmt::Display> {
fn map_or_display<F: FnOnce(T)>(self, f: F);
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
}
impl<T, E: core::fmt::Display> MapDisplay<T, E> for Result<T, E> {
///Map but display the error to stdout
#[inline]
fn map_or_display<F: FnOnce(T)>(self, f: F) {
self.map_or_else(|e| shell_error(e), f)
}
///Map but display the error to stdout and return `None`
#[inline]
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|e| { shell_error(e); None }, f)
}
}
mod valid_pbuf;

View File

@ -1,28 +0,0 @@
pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"), " ");
#[derive(Debug)]
pub struct Ps(String);
impl Ps {
pub const fn set(prompt: String) -> Self {
Self(prompt)
}
//rustc: `std::string::String::as_str` is not yet stable as a const fn
pub fn get(&self) -> &str {
self.0.as_str()
}
pub fn modify(&mut self, prompt: String) {
self.0 = prompt
}
pub fn display(&self) {
print!("{}", self.0);
}
pub fn working_dir_name(&self) -> String {
std::env::current_dir().map_or("?".to_owned(), |path| path.file_name().map_or("?".to_owned(), |name| {
match name.to_os_string() == whoami::username_os() {
true => "~".to_owned(),
false => name.to_string_lossy().to_string(),
}
}))
}
}

View File

@ -1,7 +1,6 @@
use std::{path::PathBuf, fs::{self, File}, io::{self, Write}};
use thiserror::Error;
use std::path::PathBuf;
use crate::MapDisplay;
use crate::valid_pbuf::IsValid;
pub const DEFAULT_CONFIG_CONTENT: &str = r#"--!strict
@ -15,77 +14,11 @@ username = if username == "root" then red(username) else cyan(username)
SHELL.PROMPT = `{username}@{hostname} λ `"#;
#[derive(Debug, Error)]
#[allow(dead_code)]
enum IsValidDirErr {
#[error("Failed to see if a file exists: {0}")]
TryExists(#[from] io::Error),
#[error("Not a valid entry")]
NotAnEntry,
#[error("Directory missing")]
Missing
}
#[allow(dead_code)]
enum CreateErr {
TryExists(io::Error),
Passable
}
#[allow(dead_code)]
trait IsValid {
fn is_valid(&self, is_dir_or_file: bool) -> Result<PathBuf, IsValidDirErr>;
fn is_valid_option(&self, is_dir_or_file: bool) -> Option<PathBuf>;
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf>;
fn is_valid_dir_or_create(&self) -> Option<PathBuf>;
fn is_valid_or<F>(&self, is_content: bool, f: F) -> Option<PathBuf>
where
F: FnOnce() -> Option<PathBuf>;
}
impl IsValid for PathBuf {
fn is_valid(&self, is_content: bool) -> Result<PathBuf, IsValidDirErr> {
match self.try_exists() {
Ok(true) => if is_content { Ok(self.to_path_buf()) } else { Err(IsValidDirErr::NotAnEntry) },
Ok(false) => Err(IsValidDirErr::Missing),
Err(try_e) => Err(IsValidDirErr::TryExists(try_e))
}
}
fn is_valid_or<F>(&self, is_content: bool, f: F) -> Option<PathBuf>
where
F: FnOnce() -> Option<PathBuf>
{
self.is_valid(is_content).map_err(|e| match e {
IsValidDirErr::TryExists(try_e) => CreateErr::TryExists(try_e),
IsValidDirErr::NotAnEntry | IsValidDirErr::Missing => CreateErr::Passable
}).map_or_else(|e| match e {
CreateErr::TryExists(_) => None,
CreateErr::Passable => f()
}, Some)
}
fn is_valid_dir_or_create(&self) -> Option<PathBuf> {
self.is_valid_or(self.is_dir(), || fs::create_dir(self).map_or_display_none(|()| Some(self.to_path_buf())))
}
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf> {
self.is_valid_or(self.is_file(), || {
File::create(self).map_or_display_none(|mut file| {
file.write_all(default_file_bytes).map_or_display_none(|()| Some(self.to_path_buf()))
})
})
}
fn is_valid_option(&self, is_dir_or_file: bool) -> Option<PathBuf> {
self.is_valid(is_dir_or_file).ok()
}
}
pub fn config_dir() -> Option<PathBuf> {
let mut config = home::home_dir()?;
config.push(".config");
config.is_valid_dir_or_create()?;
config.push("lambdashell");
config.push("pse");
config.is_valid_dir_or_create()
}
@ -93,11 +26,4 @@ pub fn config_file() -> Option<PathBuf> {
let mut config_file = config_dir()?;
config_file.push("init.luau");
config_file.is_valid_file_or_create(DEFAULT_CONFIG_CONTENT.as_bytes())
}
// TODO: history.rs
pub fn history_file() -> Option<PathBuf> {
let mut config_file = config_dir()?;
config_file.push(".history");
config_file.is_valid_file_or_create(b"")
}

View File

@ -1,66 +1,77 @@
use std::{cell::RefCell, fs, io::{self}, rc::Rc};
use mlua::Lua as Luau;
use std::{cell::RefCell, fs, rc::Rc};
use core::fmt;
use crate::{
commands, ps::{self, Ps}, rc, shell_error, vm::{self, LuauVm}, MapDisplay
history::History, rc::{self}, terminal::TermProcessor, vm::LuauVm
};
pub trait MapDisplay<T, E: fmt::Display> {
fn map_or_display<F: FnOnce(T)>(self, f: F);
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
}
impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
///Map but display the error to stdout
#[inline]
fn map_or_display<F: FnOnce(T)>(self, f: F) {
self.map_or_else(|e| shell_error(e), f)
}
///Map but display the error to stdout and return `None`
#[inline]
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|e| { shell_error(e); None }, f)
}
}
pub fn shell_error<E: fmt::Display>(err: E) {
color_print::ceprintln!("<bold,r>[!]:</> {err}")
}
pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> {
shell_error(err);
None
}
#[derive(Debug, Clone)]
pub struct VmConfig {
pub sandbox: bool,
pub jit: bool,
}
#[derive(Debug, Clone)]
pub struct Config {
pub norc: bool
pub norc: bool,
pub vm: VmConfig,
}
pub struct Rt {
pub ps: Rc<RefCell<String>>,
pub input: String,
pub vm: Luau,
}
pub struct Pse {
pub config: Config,
pub history: History,
pub rt: Rt
}
impl Pse {
const DEFAULT_PS: &str = concat!("pse-", env!("CARGO_PKG_VERSION"), "$ ");
pub struct LambdaShell {
terminate: bool,
config: Config,
vm: LuauVm,
ps: Rc<RefCell<Ps>>,
}
impl LambdaShell {
pub fn create(config: Config) -> Self {
let ps = Rc::new(RefCell::new(Ps::set(ps::DEFAULT_PS.to_owned())));
Self {
ps: Rc::clone(&ps),
vm: vm::LuauVm::new(ps),
terminate: false,
rt: Rt {
ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())),
input: String::new(),
vm: Luau::new(),
},
history: History::init(),
config,
}
}
pub fn wait(&mut self) -> Result<(), io::Error> {
io::Write::flush(&mut io::stdout()).map(|()| {
let mut input = String::new();
io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() {
"exit" => self.terminate = true,
trim => commands::Command::new(trim.to_owned()).exec()
})
})
}
pub fn error<E: fmt::Display>(&mut self, err: E) {
shell_error(err);
self.terminate = true;
}
pub fn start(&mut self) {
if !self.config.norc {
if let Some(conf_file) = rc::config_file() {
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
}
}
self.ps.borrow().display();
loop {
if self.terminate { break } else {
match self.wait() {
Ok(()) => self.ps.borrow().display(),
Err(flush_err) => self.error(flush_err),
}
}
}
}
pub fn vm_exec(&self, source: String) {
self.vm.exec(source);
};
self.term_input_processor().map_or_display(|()| self.history.write_to_file_fallible())
}
}

119
src/terminal.rs Normal file
View File

@ -0,0 +1,119 @@
use crossterm::{event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, terminal};
use std::io::{self, Write};
use thiserror::Error;
use crate::{commands::Command, session::{self, Pse}};
#[derive(Debug, Error)]
pub enum InputHandleError {
#[error("UserExit")]
UserExit,
#[error("Sigterm")]
Sigterm,
#[error("Render failure: {0}")]
Write(io::Error),
#[error("Flush failure: {0}")]
Flush(io::Error),
#[error("Disabling the terminal's raw mode failed: {0}")]
EnableRaw(io::Error),
#[error("Enabling the terminal's raw mode failed: {0}")]
DisableRaw(io::Error),
#[error("key input failure: {0}")]
Key(KeyCode),
}
type InputResult<T> = Result<T, InputHandleError>;
trait SpecificKeybinds {
const TERM_ID_1: &str;
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>;
fn key_enter(&mut self) -> InputResult<()>;
fn key_backspace(&mut self) -> InputResult<()>;
}
impl SpecificKeybinds for Pse {
const TERM_ID_1: &str = "exit";
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()> {
if input_key.modifiers.contains(KeyModifiers::CONTROL) {
match keycode {
KeyCode::Char('c') => Err(InputHandleError::Sigterm),
_ => Ok(())
}
} else {
self.term_render(Some(keycode.to_string()))
}
}
fn key_enter(&mut self) -> InputResult<()> {
if self.rt.input == Self::TERM_ID_1 { return Err(InputHandleError::UserExit) };
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
Command::new(&self.rt.input).exec(&mut self.history);
self.rt.input.clear();
Ok(())
}
fn key_backspace(&mut self) -> InputResult<()> {
match self.rt.input.pop() {
Some(_) => self.term_render(None),
None => {
//the string is empty, do terminal beep
Ok(())
},
}
}
}
pub trait TermProcessor {
fn term_render(&mut self, def: Option<String>) -> InputResult<()>;
fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()>;
fn term_input_mainthread(&mut self) -> io::Result<()>;
fn term_input_processor(&mut self) -> io::Result<()>;
}
impl TermProcessor for Pse {
fn term_render(&mut self, def: Option<String>) -> InputResult<()> {
match def {
Some(def_string) => {
self.rt.input.push_str(&def_string);
write!(io::stdout(), "{def_string}").map_err(InputHandleError::Write)?;
},
None => {
write!(io::stdout(), "{}", self.rt.input).map_err(InputHandleError::Write)?
}
};
io::stdout().flush().map_err(InputHandleError::Flush)
}
fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()> {
let input_handle = match input_key.code {
KeyCode::Enter => self.key_enter(),
KeyCode::Backspace => self.key_backspace(),
KeyCode::Tab => todo!(),
KeyCode::Right => todo!(),
KeyCode::Left => todo!(),
KeyCode::Up => todo!(),
KeyCode::Down => todo!(),
keycode => self.key_ctrl(input_key, keycode)
};
input_handle.map_or_else(|inp_err| match inp_err {
InputHandleError::UserExit => None,
InputHandleError::Sigterm => self.term_render(Some("^C".to_owned())).ok(),
input_err => session::shell_error_none(input_err)
}, Some)
}
fn term_input_mainthread(&mut self) -> io::Result<()> {
crossterm::execute!(io::stdout(), event::EnableBracketedPaste)?;
loop {
terminal::enable_raw_mode()?;
if let Event::Key(event) = event::read()? {
if self.term_input_handler(event).is_none() { break Ok(()) }
}
}
}
fn term_input_processor(&mut self) -> io::Result<()> {
self.term_input_mainthread()?;
terminal::disable_raw_mode()?;
crossterm::execute!(io::stdout(), event::DisableBracketedPaste)
}
}

75
src/valid_pbuf.rs Normal file
View File

@ -0,0 +1,75 @@
use std::{fs::{self, File}, io::{self, Write}, path::PathBuf};
use thiserror::Error;
use crate::session::MapDisplay;
#[derive(Debug, Error)]
#[allow(dead_code)]
pub enum IsValidDirErr {
#[error("Failed to see if a file exists: {0}")]
TryExists(#[from] io::Error),
#[error("Not a valid entry")]
NotAnEntry,
#[error("Directory missing")]
Missing
}
#[allow(dead_code)]
enum CreateErr {
TryExists(io::Error),
Passable
}
#[allow(dead_code)]
pub trait IsValid {
fn is_valid(&self, is_dir_or_file: bool) -> Result<PathBuf, IsValidDirErr>;
fn is_valid_option(&self, is_dir_or_file: bool) -> Option<PathBuf>;
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf>;
fn is_valid_dir_or_create(&self) -> Option<PathBuf>;
fn is_valid_or<F>(&self, is_content: bool, f: F) -> Option<PathBuf>
where
F: FnOnce() -> Option<PathBuf>;
}
impl IsValid for PathBuf {
#[inline]
fn is_valid(&self, is_content: bool) -> Result<PathBuf, IsValidDirErr> {
match self.try_exists() {
Ok(true) => if is_content { Ok(self.to_path_buf()) } else { Err(IsValidDirErr::NotAnEntry) },
Ok(false) => Err(IsValidDirErr::Missing),
Err(try_e) => Err(IsValidDirErr::TryExists(try_e))
}
}
#[inline]
fn is_valid_or<F>(&self, is_content: bool, f: F) -> Option<PathBuf>
where
F: FnOnce() -> Option<PathBuf>
{
self.is_valid(is_content).map_err(|e| match e {
IsValidDirErr::TryExists(try_e) => CreateErr::TryExists(try_e),
IsValidDirErr::NotAnEntry | IsValidDirErr::Missing => CreateErr::Passable
}).map_or_else(|e| match e {
CreateErr::TryExists(_) => None,
CreateErr::Passable => f()
}, Some)
}
#[inline]
fn is_valid_dir_or_create(&self) -> Option<PathBuf> {
self.is_valid_or(self.is_dir(), || fs::create_dir(self).map_or_display_none(|()| Some(self.to_path_buf())))
}
#[inline]
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf> {
self.is_valid_or(self.is_file(), || {
File::create(self).map_or_display_none(|mut file| {
file.write_all(default_file_bytes).map_or_display_none(|()| Some(self.to_path_buf()))
})
})
}
#[inline]
fn is_valid_option(&self, is_dir_or_file: bool) -> Option<PathBuf> {
self.is_valid(is_dir_or_file).ok()
}
}

View File

@ -1,11 +1,10 @@
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
use color_print::{cformat, ceprintln};
use terminal::TerminalGlobal;
use std::{cell::RefCell, rc::Rc};
use core::fmt;
use mlua::{Function, MultiValue, Result as lResult, Table, Value};
use color_print::cformat;
use shell::ShellGlobal;
use terminal::TerminalGlobal;
use core::fmt;
use crate::{ps::Ps, MapDisplay};
use crate::session::{Pse, MapDisplay};
mod shell;
mod terminal;
@ -18,25 +17,27 @@ impl<T, E: fmt::Display> LuauRuntimeErr<T> for Result<T, E> {
#[inline]
fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|luau_rt_err| {
ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>");
color_print::ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>");
None
}, f)
}
}
trait Globals {
trait VmGlobals {
const LIB_VERSION: &str;
const CONV_ERROR: &str;
fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
fn global_version(&self, luau_globals: &Table) -> lResult<()>;
const LIB_NAME: &str;
fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()>;
fn vm_glob_version(&self, luau_globals: &Table) -> lResult<()>;
}
impl Globals for LuauVm {
impl VmGlobals for Pse {
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
const LIB_NAME: &str = env!("CARGO_PKG_NAME");
const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
fn global_warn(&self, luau_globals: &Table) -> lResult<()> {
fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()> {
let luau_print = luau_globals.get::<Function>("print")?;
luau_globals.raw_set("warn", self.vm.create_function(move |this, args: MultiValue| -> lResult<()> {
luau_globals.raw_set("warn", self.rt.vm.create_function(move |this, args: MultiValue| -> lResult<()> {
let luau_multi_values = args.into_iter()
.map(|value| cformat!("<bold,y>{}</>", value.to_string().unwrap_or(Self::CONV_ERROR.to_owned())))
.map(|arg_v| Value::String(this.create_string(arg_v).unwrap()))
@ -46,34 +47,31 @@ impl Globals for LuauVm {
})?)
}
fn global_version(&self, luau_globals: &Table) -> lResult<()> {
fn vm_glob_version(&self, luau_globals: &Table) -> lResult<()> {
let luau_info = luau_globals.get::<String>("_VERSION")?;
luau_globals.raw_set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
luau_globals.raw_set("_VERSION", format!("{luau_info}, {} {}", Self::LIB_NAME, Self::LIB_VERSION))
}
}
pub struct LuauVm {
vm: Luau,
ps: Rc<RefCell<Ps>>
pub trait LuauVm {
fn vm_setglobs(&self) -> lResult<()>;
fn vm_exec(&self, source: String);
}
impl LuauVm {
pub(crate) fn new(ps: Rc<RefCell<Ps>>) -> Self {
Self { vm: Luau::new(), ps }
}
impl LuauVm for Pse {
fn vm_setglobs(&self) -> lResult<()> {
let luau_globals = self.rt.vm.globals();
self.vm_glob_shell(&luau_globals)?;
self.vm_glob_terminal(&luau_globals)?;
self.vm_glob_warn(&luau_globals)?;
self.vm_glob_version(&luau_globals)?;
fn set_shell_globals(&self) -> lResult<()> {
let luau_globals = self.vm.globals();
self.global_shell(&luau_globals)?;
self.global_terminal(&luau_globals)?;
self.global_warn(&luau_globals)?;
self.global_version(&luau_globals)?;
luau_globals.raw_set("getfenv", mlua::Nil)?;
luau_globals.raw_set("setfenv", mlua::Nil)?;
self.vm.sandbox(true)?;
Ok(())
self.rt.vm.enable_jit(self.config.vm.jit);
self.rt.vm.sandbox(true)
}
pub fn exec(&self, source: String) {
self.set_shell_globals().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
fn vm_exec(&self, source: String) {
self.vm_setglobs().map_or_display_none(|()| self.rt.vm.load(source).exec().map_or_luau_rt_err(Some));
}
}

View File

@ -2,11 +2,11 @@ use mlua::{Lua as Luau, MetaMethod, Result as lResult, Table, UserData, UserData
use std::{cell::RefCell, rc::Rc};
use whoami::fallible;
use crate::{ps::Ps, vm::LuauVm};
const DEFAULT_HOSTNAME: &str = "hostname";
use crate::session::Pse;
fn luau_sys_details(luau: &Luau) -> lResult<Table> {
const DEFAULT_HOSTNAME: &str = "hostname";
let system = luau.create_table()?;
system.raw_set("DESKTOP_ENV", whoami::desktop_env().to_string())?;
system.raw_set("DEVICENAME", whoami::devicename().to_string())?;
@ -19,17 +19,18 @@ fn luau_sys_details(luau: &Luau) -> lResult<Table> {
Ok(system)
}
struct Shell(Rc<RefCell<Ps>>);
struct Shell(Rc<RefCell<String>>);
impl UserData for Shell {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("PROMPT", |_, this| Ok(this.0.borrow().get().to_owned()));
fields.add_field_method_get("PROMPT", |_, this| Ok(this.0.borrow().to_string()));
fields.add_field_method_get("SYSTEM", |luau, _| luau_sys_details(luau));
}
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (tindex, tvalue): (String, String)| -> lResult<()> {
if tindex == "PROMPT" {
this.0.borrow_mut().modify(tvalue);
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> {
if t_index == "PROMPT" {
let mut prompt = this.0.borrow_mut();
*prompt = t_value;
}
Ok(())
});
@ -37,11 +38,10 @@ impl UserData for Shell {
}
pub trait ShellGlobal {
fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()>;
}
impl ShellGlobal for LuauVm {
fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.set("SHELL", Shell(Rc::clone(&self.ps)))?;
Ok(())
impl ShellGlobal for Pse {
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.rt.ps)))
}
}

View File

@ -2,7 +2,7 @@ use mlua::{UserDataFields, Lua as Luau, Result as lResult, Table, UserData};
use const_format::str_split;
use crossterm::style::Stylize;
use crate::vm::LuauVm;
use crate::session::Pse;
macro_rules! foreground_styles_luau {
($luau:expr, $style_table:expr, $($color:ident)+) => {
@ -84,10 +84,10 @@ impl UserData for Terminal {
}
pub trait TerminalGlobal {
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()>;
}
impl TerminalGlobal for LuauVm {
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
impl TerminalGlobal for Pse {
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("TERMINAL", Terminal)
}
}