1 Commits

Author SHA1 Message Date
15a2dcb3d5 experimenting 2025-01-14 16:38:04 -05:00
11 changed files with 219 additions and 220 deletions

112
Cargo.lock generated
View File

@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.8.0" version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be"
[[package]] [[package]]
name = "bstr" name = "bstr"
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.10" version = "1.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229" checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b"
dependencies = [ dependencies = [
"shlex", "shlex",
] ]
@ -45,6 +45,12 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]] [[package]]
name = "color-print" name = "color-print"
version = "0.3.7" version = "0.3.7"
@ -112,6 +118,16 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "ctrlc"
version = "3.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90eeab0aa92f3f9b4e87f258c72b139c207d251f9cbc1080a0086b86a8870dd3"
dependencies = [
"nix",
"windows-sys 0.59.0",
]
[[package]] [[package]]
name = "either" name = "either"
version = "1.13.0" version = "1.13.0"
@ -128,6 +144,31 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "futures-core"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-task"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
[[package]]
name = "futures-util"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"pin-utils",
"slab",
]
[[package]] [[package]]
name = "home" name = "home"
version = "0.5.11" version = "0.5.11"
@ -168,6 +209,21 @@ version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "liblambdashell"
version = "0.1.0"
dependencies = [
"color-print",
"const_format",
"crossterm",
"ctrlc",
"home",
"mlua",
"thiserror",
"uzers",
"whoami",
]
[[package]] [[package]]
name = "libloading" name = "libloading"
version = "0.8.6" version = "0.8.6"
@ -178,20 +234,6 @@ dependencies = [
"windows-targets", "windows-targets",
] ]
[[package]]
name = "libpse"
version = "0.1.0"
dependencies = [
"color-print",
"const_format",
"crossterm",
"home",
"mlua",
"thiserror",
"uzers",
"whoami",
]
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.4.15" version = "0.4.15"
@ -274,6 +316,7 @@ checksum = "9ea43c3ffac2d0798bd7128815212dd78c98316b299b7a902dabef13dc7b6b8d"
dependencies = [ dependencies = [
"bstr", "bstr",
"either", "either",
"futures-util",
"libloading", "libloading",
"mlua-sys", "mlua-sys",
"num-traits", "num-traits",
@ -295,6 +338,18 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "nix"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]] [[package]]
name = "nom" name = "nom"
version = "7.1.3" version = "7.1.3"
@ -343,6 +398,18 @@ dependencies = [
"windows-targets", "windows-targets",
] ]
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]] [[package]]
name = "pkg-config" name = "pkg-config"
version = "0.3.31" version = "0.3.31"
@ -457,6 +524,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "slab"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "smallvec" name = "smallvec"
version = "1.13.2" version = "1.13.2"

View File

@ -1,5 +1,5 @@
[package] [package]
name = "libpse" name = "liblambdashell"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
@ -7,8 +7,9 @@ edition = "2021"
color-print = "0.3.7" color-print = "0.3.7"
const_format = { version = "0.2.34", features = ["rust_1_64"] } const_format = { version = "0.2.34", features = ["rust_1_64"] }
crossterm = "0.28.1" crossterm = "0.28.1"
ctrlc = "3.4.5"
home = "0.5.9" home = "0.5.9"
mlua = { version = "0.10.0", features = ["luau-jit", "vendored"] } mlua = { version = "0.10.0", features = ["luau-jit", "vendored", "async", "send"] }
thiserror = "2.0.9" thiserror = "2.0.9"
uzers = "0.12.1" uzers = "0.12.1"
whoami = "1.5.2" whoami = "1.5.2"

View File

@ -12,7 +12,7 @@ impl PathBufIsValid for PathBuf {
} }
} }
trait ChangeDirectory<'a> { trait ChangeDirectory {
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>; fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>; fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>;
fn specific_user_dir(&self, user: String) -> Option<PathBuf>; fn specific_user_dir(&self, user: String) -> Option<PathBuf>;
@ -20,7 +20,7 @@ trait ChangeDirectory<'a> {
fn previous_dir(&self) -> Option<PathBuf>; fn previous_dir(&self) -> Option<PathBuf>;
fn home_dir(&self) -> Option<PathBuf>; fn home_dir(&self) -> Option<PathBuf>;
} }
impl<'a> ChangeDirectory<'a> for Command<'a> { impl ChangeDirectory for Command {
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf> { 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())) std::env::set_current_dir(new_path).map_or_display_none(|()| Some(new_path.to_path_buf()))
} }
@ -87,19 +87,18 @@ impl<'a> ChangeDirectory<'a> for Command<'a> {
} }
} }
pub struct Command<'a>(&'a String); pub struct Command(String);
impl<'a> Command<'a> { impl Command {
pub const fn new(input: &'a String) -> Self { pub const fn new(input: String) -> Self {
Self(input) Self(input)
} }
pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) { pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
match command_process { if let Ok(mut child) = command_process {
Ok(mut child) => { history.add(self.0.as_str());
history.add(self.0.as_str()); child.wait().ok();
child.wait().ok(); } else {
}, println!("lambdashell: Unknown command: {}", self.0)
Err(_) => println!("pse: Unknown command: {}", self.0),
} }
} }

View File

@ -3,7 +3,6 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub mod session; pub mod session;
pub mod commands; pub mod commands;
pub mod history; pub mod history;
pub mod terminal;
pub mod ps; pub mod ps;
pub mod rc; pub mod rc;
pub mod vm; pub mod vm;

View File

@ -1,19 +1,4 @@
pub const DEFAULT_PS: &str = concat!("pse-", env!("CARGO_PKG_VERSION"), " "); pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"), " ");
pub trait PsMut {
fn get(&self) -> &str;
fn modify(&mut self, prompt: String);
}
impl PsMut for Ps {
#[inline]
fn get(&self) -> &str {
self.0.as_str()
}
#[inline]
fn modify(&mut self, prompt: String) {
self.0 = prompt
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct Ps(String); pub struct Ps(String);
@ -21,4 +6,23 @@ impl Ps {
pub const fn set(prompt: String) -> Self { pub const fn set(prompt: String) -> Self {
Self(prompt) 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

@ -18,7 +18,7 @@ pub fn config_dir() -> Option<PathBuf> {
let mut config = home::home_dir()?; let mut config = home::home_dir()?;
config.push(".config"); config.push(".config");
config.is_valid_dir_or_create()?; config.is_valid_dir_or_create()?;
config.push("pse"); config.push("lambdashell");
config.is_valid_dir_or_create() config.is_valid_dir_or_create()
} }

View File

@ -1,10 +1,13 @@
use std::{cell::RefCell, fs, rc::Rc}; use std::{fs, io::{self}, sync::{Arc, Mutex}, thread};
use core::fmt; use core::fmt;
use color_print::ceprintln; use color_print::ceprintln;
use crate::{ use crate::{commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm}};
history::History, ps::{self, Ps}, rc::{self}, terminal, vm::LuauVm
}; #[inline]
pub fn shell_error<E: fmt::Display>(err: E) {
ceprintln!("<bold,r>[!]:</> {err}")
}
pub trait MapDisplay<T, E: fmt::Display> { pub trait MapDisplay<T, E: fmt::Display> {
fn map_or_display<F: FnOnce(T)>(self, f: F); fn map_or_display<F: FnOnce(T)>(self, f: F);
@ -23,47 +26,86 @@ impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
} }
} }
pub fn shell_error<E: fmt::Display>(err: E) { trait Errors {
ceprintln!("<bold,r>[!]:</> {err}") fn error<E: fmt::Display>(&mut self, err: E);
} }
pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> { impl Errors for LambdaShell {
shell_error(err); fn error<E: fmt::Display>(&mut self, err: E) {
None shell_error(err);
self.terminate = true;
}
}
trait Signals {
fn sigterm_event(&mut self);
fn input(&mut self);
}
impl Signals for LambdaShell {
fn sigterm_event(&mut self) {
// task::spawn(async move {
// signal::ctrl_c().await.expect("Failed to listen for a sigterm signal.");
// // self.history.write_to_file_fallible();
// std::process::exit(0x0100);
// });
}
fn input(&mut self) {
thread::spawn(|| {
loop {
if self.terminate { break } else {
match self.wait() {
Ok(()) => self.ps.borrow().display(),
Err(flush_err) => self.error(flush_err),
}
}
}
});
}
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
pub norc: bool, pub norc: bool
pub nojit: bool,
pub nosandbox: bool
} }
pub struct LambdaShell { pub struct LambdaShell {
terminate: bool,
history: History, history: History,
config: Config, config: Config,
ps: Ps, vm: LuauVm,
ps: Arc<Mutex<Ps>>,
} }
impl LambdaShell { impl LambdaShell {
pub fn create(config: Config) -> Self { pub fn create(config: Config) -> Self {
let ps = Arc::new(Mutex::new(Ps::set(ps::DEFAULT_PS.to_owned())));
Self { Self {
ps: Ps::set(ps::DEFAULT_PS.to_owned()), ps: Arc::clone(&ps),
vm: vm::LuauVm::new(ps),
history: History::init(), history: History::init(),
terminate: false,
config, config,
} }
} }
pub fn start(&mut self) { fn wait(&mut self) -> Result<(), io::Error> {
if !self.config.norc { io::Write::flush(&mut io::stdout()).map(|()| {
if let Some(conf_file) = rc::config_file() { let mut input = String::new();
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf)); io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() {
} "exit" => {
} self.terminate = true;
terminal::Processor::init() self.history.add("exit");
.input_processor(&mut self.history) },
.map_or_display(|()| self.history.write_to_file_fallible()); trim => commands::Command::new(trim.to_owned()).exec(&mut self.history)
})
})
} }
pub fn vm_exec(&self, source: String) { pub async fn start(&mut self) {
let p = Rc::new(RefCell::new(&self.ps)); if !self.config.norc {
LuauVm::new(Rc::clone(p)).exec(source); 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();
self.sigterm_event();
self.input();
} }
} }

View File

@ -1,122 +0,0 @@
use crossterm::{event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, terminal};
use std::io::{self, Write};
use thiserror::Error;
use crate::{commands::Command, history::History, session};
#[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, history: &mut History) -> InputResult<()>;
fn key_backspace(&mut self) -> InputResult<()>;
}
impl SpecificKeybinds for Processor {
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.render(Some(keycode.to_string()))
}
}
fn key_enter(&mut self, history: &mut History) -> InputResult<()> {
if self.0 == Self::TERM_ID_1 { return Err(InputHandleError::UserExit) };
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
Command::new(&self.0).exec(history);
self.0.clear();
Ok(())
}
fn key_backspace(&mut self) -> InputResult<()> {
match self.0.pop() {
Some(_) => self.render(None),
None => {
//the string is empty, do terminal beep
Ok(())
},
}
}
}
pub struct Processor(String);
impl Processor {
pub const fn init() -> Self {
Self(String::new())
}
pub fn render(&mut self, def: Option<String>) -> InputResult<()> {
match def {
Some(def_string) => {
self.0.push_str(&def_string);
write!(io::stdout(), "{def_string}").map_err(InputHandleError::Write)?;
},
None => {
write!(io::stdout(), "{}", self.0).map_err(InputHandleError::Write)?
}
};
io::stdout().flush().map_err(InputHandleError::Flush)
}
pub fn input_handler(&mut self, input_key: KeyEvent, history: &mut History) -> Option<()> {
let input_handle = match input_key.code {
KeyCode::Enter => self.key_enter(history),
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.render(Some("^C".to_owned())).ok(),
InputHandleError::Write(e) => session::shell_error_none(e),
InputHandleError::Flush(e) => session::shell_error_none(e),
InputHandleError::Key(e) => session::shell_error_none(e),
InputHandleError::DisableRaw(e) => session::shell_error_none(e),
InputHandleError::EnableRaw(e) => session::shell_error_none(e)
}, Some)
}
fn input_mainthread(&mut self, history: &mut History) -> io::Result<()> {
crossterm::execute!(io::stdout(), event::EnableBracketedPaste)?;
loop {
terminal::enable_raw_mode()?;
if let Event::Key(event) = event::read()? {
if self.input_handler(event, history).is_none() { break Ok(()) }
}
}
}
pub fn input_processor(&mut self, history: &mut History) -> io::Result<()> {
self.input_mainthread(history)?;
terminal::disable_raw_mode()?;
crossterm::execute!(io::stdout(), event::DisableBracketedPaste)
}
}

View File

@ -1,8 +1,8 @@
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value}; use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
use color_print::{cformat, ceprintln}; use color_print::{cformat, ceprintln};
use terminal::TerminalGlobal; use terminal::TerminalGlobal;
use core::fmt;
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use core::fmt;
use shell::ShellGlobal; use shell::ShellGlobal;
use crate::{ps::Ps, session::MapDisplay}; use crate::{ps::Ps, session::MapDisplay};
@ -27,16 +27,14 @@ impl<T, E: fmt::Display> LuauRuntimeErr<T> for Result<T, E> {
trait Globals { trait Globals {
const LIB_VERSION: &str; const LIB_VERSION: &str;
const CONV_ERROR: &str; const CONV_ERROR: &str;
const LIB_NAME: &str; fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
fn glob_warn(&self, luau_globals: &Table) -> lResult<()>; fn global_version(&self, luau_globals: &Table) -> lResult<()>;
fn glob_version(&self, luau_globals: &Table) -> lResult<()>;
} }
impl Globals for LuauVm { impl Globals for LuauVm {
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION"); const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
const LIB_NAME: &str = env!("CARGO_PKG_NAME");
const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>"; const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
fn glob_warn(&self, luau_globals: &Table) -> lResult<()> { fn global_warn(&self, luau_globals: &Table) -> lResult<()> {
let luau_print = luau_globals.get::<Function>("print")?; 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.vm.create_function(move |this, args: MultiValue| -> lResult<()> {
let luau_multi_values = args.into_iter() let luau_multi_values = args.into_iter()
@ -48,9 +46,9 @@ impl Globals for LuauVm {
})?) })?)
} }
fn glob_version(&self, luau_globals: &Table) -> lResult<()> { fn global_version(&self, luau_globals: &Table) -> lResult<()> {
let luau_info = luau_globals.get::<String>("_VERSION")?; let luau_info = luau_globals.get::<String>("_VERSION")?;
luau_globals.raw_set("_VERSION", format!("{luau_info}, {} {}", Self::LIB_NAME, Self::LIB_VERSION)) luau_globals.raw_set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
} }
} }
@ -63,12 +61,12 @@ impl LuauVm {
Self { vm: Luau::new(), ps } Self { vm: Luau::new(), ps }
} }
fn setglobs(&self) -> lResult<()> { fn set_shell_globals(&self) -> lResult<()> {
let luau_globals = self.vm.globals(); let luau_globals = self.vm.globals();
self.glob_shell(&luau_globals)?; self.global_shell(&luau_globals)?;
self.glob_terminal(&luau_globals)?; self.global_terminal(&luau_globals)?;
self.glob_warn(&luau_globals)?; self.global_warn(&luau_globals)?;
self.glob_version(&luau_globals)?; self.global_version(&luau_globals)?;
luau_globals.raw_set("getfenv", mlua::Nil)?; luau_globals.raw_set("getfenv", mlua::Nil)?;
luau_globals.raw_set("setfenv", mlua::Nil)?; luau_globals.raw_set("setfenv", mlua::Nil)?;
self.vm.sandbox(true)?; self.vm.sandbox(true)?;
@ -76,6 +74,6 @@ impl LuauVm {
} }
pub fn exec(&self, source: String) { pub fn exec(&self, source: String) {
self.setglobs().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some)); self.set_shell_globals().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
} }
} }

View File

@ -2,7 +2,7 @@ use mlua::{Lua as Luau, MetaMethod, Result as lResult, Table, UserData, UserData
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use whoami::fallible; use whoami::fallible;
use crate::{ps::{Ps, PsMut}, vm::LuauVm}; use crate::{ps::Ps, vm::LuauVm};
const DEFAULT_HOSTNAME: &str = "hostname"; const DEFAULT_HOSTNAME: &str = "hostname";
@ -27,18 +27,20 @@ impl UserData for Shell {
} }
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> { methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (tindex, tvalue): (String, String)| -> lResult<()> {
if t_index == "PROMPT" { this.0.borrow_mut().modify(t_value); } if tindex == "PROMPT" {
this.0.borrow_mut().modify(tvalue);
}
Ok(()) Ok(())
}); });
} }
} }
pub trait ShellGlobal { pub trait ShellGlobal {
fn glob_shell(&self, luau_globals: &Table) -> lResult<()>; fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
} }
impl ShellGlobal for LuauVm { impl ShellGlobal for LuauVm {
fn glob_shell(&self, luau_globals: &Table) -> lResult<()> { fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.ps)))?; luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.ps)))?;
Ok(()) Ok(())
} }

View File

@ -84,10 +84,10 @@ impl UserData for Terminal {
} }
pub trait TerminalGlobal { pub trait TerminalGlobal {
fn glob_terminal(&self, luau_globals: &Table) -> lResult<()>; fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
} }
impl TerminalGlobal for LuauVm { impl TerminalGlobal for LuauVm {
fn glob_terminal(&self, luau_globals: &Table) -> lResult<()> { fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("TERMINAL", Terminal) luau_globals.raw_set("TERMINAL", Terminal)
} }
} }