12 Commits

12 changed files with 489 additions and 380 deletions

143
Cargo.lock generated
View File

@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.6.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 = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be"
[[package]] [[package]]
name = "bstr" name = "bstr"
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.7" 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 = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7" 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"
@ -139,9 +180,9 @@ dependencies = [
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.76" version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7" checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"wasm-bindgen", "wasm-bindgen",
@ -175,6 +216,7 @@ dependencies = [
"color-print", "color-print",
"const_format", "const_format",
"crossterm", "crossterm",
"ctrlc",
"home", "home",
"mlua", "mlua",
"thiserror", "thiserror",
@ -194,9 +236,9 @@ dependencies = [
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.4.14" version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]] [[package]]
name = "lock_api" name = "lock_api"
@ -210,9 +252,9 @@ dependencies = [
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.22" version = "0.4.25"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" checksum = "04cbf5b083de1c7e0222a7a51dbfdba1cbe1c6ab0b15e29fff3f6c077fd9cd9f"
[[package]] [[package]]
name = "lua-src" name = "lua-src"
@ -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"
@ -351,9 +418,9 @@ checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.92" version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
@ -384,9 +451,9 @@ checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.38.42" version = "0.38.43"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"errno", "errno",
@ -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"
@ -465,9 +541,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.95" version = "2.0.96"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a" checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -476,18 +552,18 @@ dependencies = [
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "2.0.9" version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc" checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc"
dependencies = [ dependencies = [
"thiserror-impl", "thiserror-impl",
] ]
[[package]] [[package]]
name = "thiserror-impl" name = "thiserror-impl"
version = "2.0.9" version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -530,9 +606,9 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.99" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"once_cell", "once_cell",
@ -541,9 +617,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.99" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"log", "log",
@ -555,9 +631,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.99" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
dependencies = [ dependencies = [
"quote", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@ -565,9 +641,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.99" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -578,15 +654,18 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.99" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
dependencies = [
"unicode-ident",
]
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.76" version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc" checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",

View File

@ -7,14 +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"
[profile.release]
strip = true
opt-level = "z"
lto = true
codegen-units = 1

View File

@ -1,22 +1,16 @@
use std::{io, process, str::SplitWhitespace, path::{Path, PathBuf}};
use uzers::User; use uzers::User;
use std::{
io,
process,
str::SplitWhitespace,
path::{Path, PathBuf},
};
use crate::MapDisplay; use crate::{history::History, session::MapDisplay, valid_pbuf::IsValid};
enum ValidStatus {
NoRootFolder,
TryExists(io::Error)
}
trait PathBufIsValid { trait PathBufIsValid {
fn is_valid(&self) -> Result<PathBuf, ValidStatus>;
fn is_valid_or_home(&self) -> Option<PathBuf>; 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 {
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>; fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
@ -26,30 +20,6 @@ trait ChangeDirectory {
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 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 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()))
@ -119,24 +89,25 @@ impl ChangeDirectory for Command {
pub struct Command(String); pub struct Command(String);
impl Command { impl Command {
pub fn new(input: String) -> Self { pub const fn new(input: String) -> Self {
Self(input) Self(input)
} }
pub fn spawn(&self, command_process: io::Result<process::Child>) { pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
command_process.map_or_display_none(|mut child| Some(child.wait())); if let Ok(mut child) = command_process {
history.add(self.0.as_str());
child.wait().ok();
} else {
println!("lambdashell: Unknown command: {}", self.0)
}
} }
pub fn exec(&self) { pub fn exec(&mut self, history: &mut History) {
let mut args = self.0.split_whitespace(); let mut args = self.0.split_whitespace();
if let Some(command) = args.next() { if let Some(command) = args.next() {
match command { match command {
"cd" => { "cd" => if self.change_directory(args).is_some() { history.add(self.0.as_str()) },
self.change_directory(args); command => { self.spawn_sys_cmd(history, process::Command::new(command).args(args).spawn()); }
},
command => {
self.spawn(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

@ -1,22 +1,10 @@
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 ps; pub mod ps;
pub mod rc; pub mod rc;
pub mod vm; pub mod vm;
pub trait MapDisplay<T, E: std::fmt::Display> { mod valid_pbuf;
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: std::fmt::Display> MapDisplay<T, E> for Result<T, E> {
///Map and display an error
#[inline]
fn map_or_display<F: FnOnce(T)>(self, f: F) {
self.map_or_else(|e| color_print::ceprintln!("<bold,r>[!]:</> {e}"), f)
}
///Map and display an error but return `None`
#[inline]
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|e| { color_print::ceprintln!("<bold,r>[!]:</> {e}"); None }, f)
}
}

View File

@ -1,24 +1,28 @@
pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION")); pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"), " ");
#[derive(Debug)]
pub struct Ps(String); pub struct Ps(String);
impl Ps { impl Ps {
pub 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 working_dir_name(&self) -> String { pub fn get(&self) -> &str {
std::env::current_dir().map_or("?".to_owned(), |path| { self.0.as_str()
path.file_name().map_or("?".to_owned(), |name| { }
let name_os_string = name.to_os_string(); pub fn modify(&mut self, prompt: String) {
match name_os_string == whoami::username_os() && name_os_string != "root" { self.0 = prompt
true => "~".to_owned(),
false => name.to_string_lossy().to_string(),
}
})
})
} }
pub fn display(&self) { pub fn display(&self) {
print!("{}", self.0); 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,83 +1,19 @@
use std::{path::PathBuf, fs::{self, File}, io::{self, Write}}; use std::path::PathBuf;
use thiserror::Error;
use crate::MapDisplay; use crate::valid_pbuf::IsValid;
pub const DEFAULT_CONFIG_CONTENT: &str = r#"--!strict pub const DEFAULT_CONFIG_CONTENT: &str = r#"--!strict
local cyan = TERMINAL.OUT.FOREGROUND.CYAN local cyan = TERMINAL.OUT.FOREGROUND.CYAN
local red = TERMINAL.OUT.FOREGROUND.RED
local username = cyan(SHELL.SYSTEM.USERNAME)
local hostname = SHELL.SYSTEM.HOSTNAME local hostname = SHELL.SYSTEM.HOSTNAME
local username = SHELL.SYSTEM.USERNAME
username = if username == "root" then red(username) else cyan(username)
SHELL.PROMPT = `{username}@{hostname} λ `"#; 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> { pub fn config_dir() -> Option<PathBuf> {
let mut config = home::home_dir()?; let mut config = home::home_dir()?;
config.push(".config"); config.push(".config");
@ -90,11 +26,4 @@ pub fn config_file() -> Option<PathBuf> {
let mut config_file = config_dir()?; let mut config_file = config_dir()?;
config_file.push("init.luau"); config_file.push("init.luau");
config_file.is_valid_file_or_create(DEFAULT_CONFIG_CONTENT.as_bytes()) 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,70 +1,111 @@
use std::{fs, io::{self}}; use std::{fs, io::{self}, sync::{Arc, Mutex}, thread};
use core::fmt;
use color_print::ceprintln;
use crate::{ use crate::{commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm}};
vm::{LuauVm, self},
commands,
ps,
rc,
MapDisplay,
};
#[inline]
pub fn shell_error<E: fmt::Display>(err: E) {
ceprintln!("<bold,r>[!]:</> {err}")
}
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)
}
}
trait Errors {
fn error<E: fmt::Display>(&mut self, err: E);
}
impl Errors for LambdaShell {
fn error<E: fmt::Display>(&mut self, err: E) {
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)]
pub struct Config { pub struct Config {
pub norc: bool pub norc: bool
} }
pub struct LambdaShell { pub struct LambdaShell {
vm: LuauVm, terminate: bool,
ps1: String, history: History,
config: Config, config: Config,
terminating: bool, 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 {
vm: vm::LuauVm::new(), ps: Arc::clone(&ps),
ps1: ps::DEFAULT_PS.to_owned(), vm: vm::LuauVm::new(ps),
terminating: false, history: History::init(),
terminate: false,
config, config,
} }
} }
pub fn wait(&mut self) -> Result<(), io::Error> { fn wait(&mut self) -> Result<(), io::Error> {
io::Write::flush(&mut io::stdout()).map(|()| { io::Write::flush(&mut io::stdout()).map(|()| {
let mut input = String::new(); let mut input = String::new();
io::stdin().read_line(&mut input).map_or_display(|_size| { io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() {
match input.trim() { "exit" => {
//special casey self.terminate = true;
"exit" => self.terminating = true, self.history.add("exit");
trim => commands::Command::new(trim.to_owned()).exec() },
}; trim => commands::Command::new(trim.to_owned()).exec(&mut self.history)
}) })
}) })
} }
pub fn vm_exec(&self, source: String) { pub async fn start(&mut self) {
self.vm.exec(source);
}
pub fn start(&mut self) {
if !self.config.norc { if !self.config.norc {
if let Some(conf_file) = rc::config_file() { if let Some(conf_file) = rc::config_file() {
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf)); fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm.exec(luau_conf));
} }
} };
loop { self.ps.borrow().display();
match self.terminating { self.sigterm_event();
true => break, self.input();
false => {
match self.wait() {
Ok(()) => {},
Err(flush_error) => {
println!("{flush_error}");
break;
}
}
},
}
}
} }
} }

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,9 +1,11 @@
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 std::{cell::RefCell, rc::Rc};
use core::fmt; use core::fmt;
use shell::Shell; use shell::ShellGlobal;
use crate::{vm::terminal::Terminal, MapDisplay}; use crate::{ps::Ps, session::MapDisplay};
mod shell; mod shell;
mod terminal; mod terminal;
@ -24,51 +26,54 @@ 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;
fn global_warn(&self, luau_globals: &Table) -> lResult<()>; fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
fn global_version(&self, luau_globals: &Table) -> lResult<()>; fn global_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 CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
fn global_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.set("warn", self.0.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()
.map(|value| cformat!("<bold,y>{}</>", value.to_string().unwrap_or("<SHELL CONVERSION ERROR>".to_owned()))) .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())) .map(|arg_v| Value::String(this.create_string(arg_v).unwrap()))
.collect::<MultiValue>(); .collect::<MultiValue>();
luau_print.call::<()>(luau_multi_values).unwrap(); luau_print.call::<()>(luau_multi_values)?;
Ok(()) Ok(())
})?) })?)
} }
fn global_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.set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION)) luau_globals.raw_set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
} }
} }
pub struct LuauVm(pub Luau); pub struct LuauVm {
vm: Luau,
ps: Rc<RefCell<Ps>>
}
impl LuauVm { impl LuauVm {
pub(crate) fn new() -> Self { pub(crate) fn new(ps: Rc<RefCell<Ps>>) -> Self {
Self(Luau::new()) Self { vm: Luau::new(), ps }
} }
fn set_shell_globals(&self) -> lResult<()> { fn set_shell_globals(&self) -> lResult<()> {
let luau_globals = self.0.globals(); let luau_globals = self.vm.globals();
self.global_shell(&luau_globals)?;
self.global_terminal(&luau_globals)?;
self.global_warn(&luau_globals)?; self.global_warn(&luau_globals)?;
self.global_version(&luau_globals)?; self.global_version(&luau_globals)?;
self.global_terminal(&luau_globals)?; luau_globals.raw_set("getfenv", mlua::Nil)?;
self.global_shell(&luau_globals)?; luau_globals.raw_set("setfenv", mlua::Nil)?;
luau_globals.set("getfenv", mlua::Nil)?; self.vm.sandbox(true)?;
luau_globals.set("setfenv", mlua::Nil)?;
self.0.sandbox(true)?;
Ok(()) Ok(())
} }
pub fn exec(&self, source: String) { pub fn exec(&self, source: String) {
self.set_shell_globals().map_or_display_none(|()| { self.set_shell_globals().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
self.0.load(source).exec().map_or_luau_rt_err(Some)
});
} }
} }

View File

@ -1,57 +1,47 @@
use mlua::{Result as lResult, Table, Value}; use mlua::{Lua as Luau, MetaMethod, Result as lResult, Table, UserData, UserDataFields, UserDataMethods};
use std::{cell::RefCell, rc::Rc};
use whoami::fallible; use whoami::fallible;
use crate::vm::LuauVm; use crate::{ps::Ps, vm::LuauVm};
const DEFAULT_HOSTNAME: &str = "hostname"; const DEFAULT_HOSTNAME: &str = "hostname";
trait PsPrompt { fn luau_sys_details(luau: &Luau) -> lResult<Table> {
fn ps_prompt(&self) -> lResult<Table>; let system = luau.create_table()?;
system.raw_set("DESKTOP_ENV", whoami::desktop_env().to_string())?;
system.raw_set("DEVICENAME", whoami::devicename().to_string())?;
system.raw_set("USERNAME", whoami::username().to_string())?;
system.raw_set("REALNAME", whoami::realname().to_string())?;
system.raw_set("PLATFORM", whoami::platform().to_string())?;
system.raw_set("DISTRO", whoami::distro().to_string())?;
system.raw_set("ARCH", whoami::arch().to_string())?;
system.raw_set("HOSTNAME", fallible::hostname().unwrap_or(DEFAULT_HOSTNAME.to_owned()))?;
Ok(system)
} }
impl PsPrompt for LuauVm {
fn ps_prompt(&self) -> lResult<Table> { struct Shell(Rc<RefCell<Ps>>);
let prompt_table = self.0.create_table()?; impl UserData for Shell {
let prompt_metatable = self.0.create_table()?; fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
prompt_metatable.set("__index", self.0.create_function(|_, (table, index): (Table, Value)| -> lResult<String> { fields.add_field_method_get("PROMPT", |_, this| Ok(this.0.borrow().get().to_owned()));
table.raw_get::<String>(index) fields.add_field_method_get("SYSTEM", |luau, _| luau_sys_details(luau));
})?)?; }
prompt_metatable.set("__newindex", self.0.create_function(|_, _: String| -> lResult<String> {
Ok("placeholder".to_owned()) fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
})?)?; methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (tindex, tvalue): (String, String)| -> lResult<()> {
prompt_table.set("__metatable", mlua::Nil)?; if tindex == "PROMPT" {
prompt_table.set_metatable(Some(prompt_metatable)); this.0.borrow_mut().modify(tvalue);
prompt_table.set_readonly(false); }
Ok(prompt_table) Ok(())
});
} }
} }
trait System { pub trait ShellGlobal {
fn sys_details(&self) -> lResult<Table>;
}
impl System for LuauVm {
fn sys_details(&self) -> lResult<Table> {
let system = self.0.create_table()?;
system.set("DESKTOP_ENV", whoami::desktop_env().to_string())?;
system.set("DEVICENAME", whoami::devicename().to_string())?;
system.set("USERNAME", whoami::username().to_string())?;
system.set("REALNAME", whoami::realname().to_string())?;
system.set("PLATFORM", whoami::platform().to_string())?;
system.set("DISTRO", whoami::distro().to_string())?;
system.set("HOSTNAME", fallible::hostname().unwrap_or(DEFAULT_HOSTNAME.to_owned()))?;
Ok(system)
}
}
pub trait Shell {
fn global_shell(&self, luau_globals: &Table) -> lResult<()>; fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
} }
impl Shell for LuauVm { impl ShellGlobal for LuauVm {
fn global_shell(&self, luau_globals: &Table) -> lResult<()> { fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
let shell = self.0.create_table()?; luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.ps)))?;
let ps_prompt = self.ps_prompt()?;
shell.set("SYSTEM", self.sys_details()?)?;
shell.set("PROMPT", ps_prompt)?;
luau_globals.set("SHELL", shell)?;
Ok(()) Ok(())
} }
} }

View File

@ -1,112 +1,93 @@
use mlua::{Function, Result as lResult, Table}; use mlua::{UserDataFields, Lua as Luau, Result as lResult, Table, UserData};
use const_format::str_split; use const_format::str_split;
use crossterm::style::Stylize; use crossterm::style::Stylize;
use crate::vm::LuauVm; use crate::vm::LuauVm;
macro_rules! foreground_styles_luau { macro_rules! foreground_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => { ($luau:expr, $style_table:expr, $($color:ident)+) => {
$( $(
$style_table.set(stringify!($color).to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> { $style_table.raw_set(stringify!($color).to_ascii_uppercase(), $luau.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string()) Ok(text.$color().to_string())
})?)?; })?)?;
)+ )+
}; };
} }
macro_rules! background_styles_luau { macro_rules! background_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => { ($luau:expr, $style_table:expr, $($color:ident)+) => {
$( $(
$style_table.set( $style_table.raw_set(
str_split!(stringify!($color), "_")[1..].join("_").to_ascii_uppercase(), str_split!(stringify!($color), "_")[1..].join("_").to_ascii_uppercase(),
$self.0.create_function(|_, text: String| -> lResult<String> { $luau.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string()) Ok(text.$color().to_string())
})?)?; })?)?;
)+ )+
}; };
} }
trait Colors { fn text_styles_funcs(luau: &Luau) -> lResult<(Table, Table)> {
fn background(&self, term_out_table: &Table) -> lResult<()>; let foreground_table = luau.create_table()?;
fn foreground(&self, term_out_table: &Table) -> lResult<()>; let background_table = luau.create_table()?;
} foreground_styles_luau!(luau, foreground_table,
impl Colors for LuauVm { dark_grey dark_red dark_green dark_cyan
fn background(&self, term_out_table: &Table) -> lResult<()> { dark_yellow dark_magenta dark_blue
let foreground_table = self.0.create_table()?; red grey black green yellow
foreground_styles_luau!(self, foreground_table, blue magenta cyan white
dark_grey dark_red dark_green dark_cyan underlined
dark_yellow dark_magenta dark_blue underline_dark_grey underline_dark_red underline_dark_green underline_dark_cyan
red grey black green yellow underline_dark_yellow underline_dark_magenta underline_dark_blue underline_red
blue magenta cyan white underline_grey underline_black underline_green underline_yellow
underlined underline_blue underline_magenta underline_cyan underline_white
underline_dark_grey underline_dark_red underline_dark_green underline_dark_cyan bold
underline_dark_yellow underline_dark_magenta underline_dark_blue underline_red );
underline_grey underline_black underline_green underline_yellow background_styles_luau!(luau, background_table,
underline_blue underline_magenta underline_cyan underline_white on_dark_grey on_dark_red on_dark_green on_dark_cyan
bold on_dark_yellow on_dark_magenta on_dark_blue
); on_red on_grey on_black
term_out_table.set("FOREGROUND", foreground_table) on_green on_yellow
} on_blue on_magenta
on_cyan on_white
fn foreground(&self, term_out_table: &Table) -> lResult<()> { );
let background_table = self.0.create_table()?; Ok((foreground_table, background_table))
background_styles_luau!(self, background_table,
on_dark_grey on_dark_red on_dark_green on_dark_cyan
on_dark_yellow on_dark_magenta on_dark_blue
on_red on_grey on_black
on_green on_yellow
on_blue on_magenta
on_cyan on_white
);
term_out_table.set("BACKGROUND", background_table)
}
} }
trait Write { fn fields_write_funcs<F: UserDataFields<Terminal>>(fields: &mut F) {
fn write(&self) -> lResult<Function>; fields.add_field_method_get("WRITE", |luau, _| luau.create_function(|_, s: String| -> lResult<()> {
fn write_error(&self) -> lResult<Function>; print!("{s}");
fn write_error_ln(&self) -> lResult<Function>; Ok(())
} }));
impl Write for LuauVm { fields.add_field_method_get("WRITE_ERROR", |luau, _| luau.create_function(|_, s: String| -> lResult<()> {
fn write(&self) -> lResult<Function> { eprint!("{s}");
self.0.create_function(|_, s: String| -> lResult<()> { Ok(())
print!("{s}"); }));
Ok(()) fields.add_field_method_get("WRITE_ERROR_LN", |luau, _| luau.create_function(|_, s: String| -> lResult<()> {
}) eprintln!("{s}");
} Ok(())
}));
fn write_error(&self) -> lResult<Function> {
self.0.create_function(|_, s: String| -> lResult<()> {
eprint!("{s}");
Ok(())
})
}
fn write_error_ln(&self) -> lResult<Function> {
self.0.create_function(|_, s: String| -> lResult<()> {
eprintln!("{s}");
Ok(())
})
}
} }
pub trait Terminal { struct Terminal;
fn out(&self) -> lResult<Table>; impl UserData for Terminal {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
fields_write_funcs(fields);
fields.add_field_method_get("OUT", |luau, _| {
let (foreground, background) = text_styles_funcs(luau)?;
let out_table = luau.create_table()?;
out_table.raw_set("FOREGROUND", foreground)?;
out_table.raw_set("BACKGROUND", background)?;
Ok(out_table)
});
}
// fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
// }
}
pub trait TerminalGlobal {
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>; fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
} }
impl Terminal for LuauVm { impl TerminalGlobal for LuauVm {
fn out(&self) -> lResult<Table> {
let term_out_table = self.0.create_table()?;
self.background(&term_out_table)?;
self.foreground(&term_out_table)?;
Ok(term_out_table)
}
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> { fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
let term_table = self.0.create_table()?; luau_globals.raw_set("TERMINAL", Terminal)
term_table.set("OUT", self.out()?)?;
term_table.set("WRITE", self.write()?)?;
term_table.set("WRITE_ERROR", self.write_error()?)?;
term_table.set("WRITE_ERROR_LN", self.write_error_ln()?)?;
luau_globals.set("TERMINAL", term_table)
} }
} }