Compare commits
21 Commits
rc
...
terminal-e
Author | SHA1 | Date | |
---|---|---|---|
8552449510 | |||
cde80eccad | |||
c91b486214 | |||
ee0ed28f85 | |||
e985236188 | |||
d4ccf3b061 | |||
c080a25603 | |||
0282b26265 | |||
4cda728b2e | |||
375cc7a88f | |||
09a6ad3ae2 | |||
41c611c0ca | |||
f8d97ded00 | |||
d40f4bece3 | |||
ca639db826 | |||
ab349f7894 | |||
fb2d79c35c | |||
e578f408c5 | |||
d95366bebe | |||
97b08d24e3 | |||
41899480c0 |
125
Cargo.lock
generated
125
Cargo.lock
generated
@ -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"
|
||||
@ -26,15 +26,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.16.0"
|
||||
version = "3.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
|
||||
checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf"
|
||||
|
||||
[[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",
|
||||
]
|
||||
@ -118,6 +118,12 @@ version = "1.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
|
||||
|
||||
[[package]]
|
||||
name = "env_home"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.10"
|
||||
@ -139,9 +145,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 +175,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,21 +198,11 @@ 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.14"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
|
||||
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
@ -210,9 +216,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"
|
||||
@ -225,9 +231,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luajit-src"
|
||||
version = "210.5.11+97813fb"
|
||||
version = "210.5.12+a4f56a4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3015551c284515db7c30c559fc1080f9cb9ee990d1f6fca315451a107c7540bb"
|
||||
checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"which",
|
||||
@ -235,9 +241,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "luau0-src"
|
||||
version = "0.11.2+luau653"
|
||||
version = "0.12.0+luau657"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02313a53daf1fae25e82f7e7ca56180b72d1f08c514426672877cd957298201c"
|
||||
checksum = "3a4b4c16b82ddf60e0fa93ca5a6afc504a6db22310cc82ecec629cd2e405b2ca"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
@ -268,9 +274,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mlua"
|
||||
version = "0.10.2"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ea43c3ffac2d0798bd7128815212dd78c98316b299b7a902dabef13dc7b6b8d"
|
||||
checksum = "d3f763c1041eff92ffb5d7169968a327e1ed2ebfe425dac0ee5a35f29082534b"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"either",
|
||||
@ -283,9 +289,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mlua-sys"
|
||||
version = "0.6.6"
|
||||
version = "0.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63a11d485edf0f3f04a508615d36c7d50d299cf61a7ee6d3e2530651e0a31771"
|
||||
checksum = "1901c1a635a22fe9250ffcc4fcc937c16b47c2e9e71adba8784af8bca1f69594"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
@ -351,9 +357,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",
|
||||
]
|
||||
@ -384,9 +390,9 @@ checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.42"
|
||||
version = "0.38.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
|
||||
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
@ -465,9 +471,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 +482,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.9"
|
||||
version = "2.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc"
|
||||
checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.9"
|
||||
version = "2.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4"
|
||||
checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@ -496,9 +502,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.14"
|
||||
version = "1.0.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
|
||||
checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
@ -530,9 +536,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 +547,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 +561,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 +571,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 +584,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",
|
||||
@ -594,12 +603,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "which"
|
||||
version = "6.0.3"
|
||||
version = "7.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"
|
||||
checksum = "fb4a9e33648339dc1642b0e36e21b3385e6148e289226f657c809dee59df5028"
|
||||
dependencies = [
|
||||
"either",
|
||||
"home",
|
||||
"env_home",
|
||||
"rustix",
|
||||
"winsafe",
|
||||
]
|
||||
|
10
Cargo.toml
10
Cargo.toml
@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "liblambdashell"
|
||||
name = "libpse"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
@ -11,10 +11,4 @@ home = "0.5.9"
|
||||
mlua = { version = "0.10.0", features = ["luau-jit", "vendored"] }
|
||||
thiserror = "2.0.9"
|
||||
uzers = "0.12.1"
|
||||
whoami = "1.5.2"
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
whoami = "1.5.2"
|
111
src/commands.rs
111
src/commands.rs
@ -1,75 +1,45 @@
|
||||
use std::{env, path::{Path, PathBuf}, process, str::SplitWhitespace};
|
||||
use uzers::User;
|
||||
use std::{
|
||||
io,
|
||||
process,
|
||||
str::SplitWhitespace,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use crate::MapDisplay;
|
||||
|
||||
enum ValidStatus {
|
||||
NoRootFolder,
|
||||
TryExists(io::Error)
|
||||
}
|
||||
use crate::{session::{MapDisplay, Pse}, valid_pbuf::IsValid};
|
||||
|
||||
trait PathBufIsValid {
|
||||
fn is_valid(&self) -> Result<PathBuf, ValidStatus>;
|
||||
fn is_valid_or_home(&self) -> Option<PathBuf>;
|
||||
}
|
||||
|
||||
trait ChangeDirectory {
|
||||
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>;
|
||||
fn cd_args(&self, vec_args: Vec<String>) -> Option<PathBuf>;
|
||||
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
|
||||
},
|
||||
}
|
||||
self.is_valid_or(self.is_dir(), home::home_dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChangeDirectory for Command {
|
||||
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()))
|
||||
struct ChangeDirectory(Option<PathBuf>);
|
||||
impl ChangeDirectory {
|
||||
fn set_dir(&mut self, new_path: &Path) -> Option<PathBuf> {
|
||||
let past_dir = env::current_dir().ok();
|
||||
env::set_current_dir(new_path).map_or_display_none(|()| {
|
||||
self.0 = past_dir;
|
||||
Some(new_path.to_path_buf())
|
||||
})
|
||||
}
|
||||
|
||||
fn home_dir(&self) -> Option<PathBuf> {
|
||||
home::home_dir().map_or(self.set_current_dir(Path::new("/")), |home_pathbuf| self.set_current_dir(&home_pathbuf))
|
||||
fn home_dir(&mut self) -> Option<PathBuf> {
|
||||
home::home_dir().map_or(self.set_dir(Path::new("/")), |home_pathbuf| self.set_dir(&home_pathbuf))
|
||||
}
|
||||
|
||||
fn previous_dir(&self) -> Option<PathBuf> {
|
||||
unimplemented!()
|
||||
fn previous_dir(&mut self) -> Option<PathBuf> {
|
||||
match self.0.as_ref() {
|
||||
Some(p_buf) => self.set_dir(&p_buf.to_path_buf()),
|
||||
None => None
|
||||
}
|
||||
}
|
||||
|
||||
fn specific_user_dir(&self, requested_user: String) -> Option<PathBuf> {
|
||||
match requested_user.as_str() {
|
||||
"root" => PathBuf::from("/root").is_valid_or_home(),
|
||||
_ => {
|
||||
u => {
|
||||
for user in unsafe { uzers::all_users().collect::<Vec<User>>() } {
|
||||
let user_name = user.name();
|
||||
if *requested_user == *user_name {
|
||||
if *u == *user_name {
|
||||
let mut user_dir = PathBuf::from("/home");
|
||||
user_dir.push(user_name);
|
||||
return user_dir.is_valid_or_home();
|
||||
@ -80,11 +50,11 @@ impl ChangeDirectory for Command {
|
||||
}
|
||||
}
|
||||
|
||||
fn cd_args(&self, vec_args: Vec<String>) -> Option<PathBuf> {
|
||||
fn cd_args(&mut self, vec_args: Vec<String>) -> Option<PathBuf> {
|
||||
let string_path = vec_args.concat();
|
||||
let new_path = Path::new(string_path.as_str());
|
||||
match new_path.is_dir() {
|
||||
true => self.set_current_dir(new_path),
|
||||
true => self.set_dir(new_path),
|
||||
false => {
|
||||
match new_path.file_name() {
|
||||
Some(file_name) => println!("cd: {:?} is not a directory.", file_name),
|
||||
@ -95,15 +65,15 @@ impl ChangeDirectory for Command {
|
||||
}
|
||||
}
|
||||
|
||||
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf> {
|
||||
fn change_directory(&mut self, args: SplitWhitespace) -> Option<PathBuf> {
|
||||
let vec_args: Vec<String> = args.map(|arg| arg.to_owned()).collect();
|
||||
match vec_args.first() {
|
||||
None => self.home_dir(),
|
||||
Some(arg) => match arg.as_str() {
|
||||
"/" => self.set_current_dir(Path::new("/")),
|
||||
"/" => self.set_dir(Path::new("/")),
|
||||
"-" => self.previous_dir(),
|
||||
_ => {
|
||||
let mut arg_chars = arg.chars();
|
||||
arg_str => {
|
||||
let mut arg_chars = arg_str.chars();
|
||||
match arg_chars.next() {
|
||||
Some(char) => match char == '~' {
|
||||
true => self.specific_user_dir(arg_chars.collect::<String>()),
|
||||
@ -117,25 +87,22 @@ impl ChangeDirectory for Command {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Command(String);
|
||||
impl Command {
|
||||
pub fn new(input: 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 exec(&self) {
|
||||
let mut args = self.0.split_whitespace();
|
||||
pub trait Command {
|
||||
fn spawn_sys_cmd(&mut self);
|
||||
}
|
||||
impl Command for Pse {
|
||||
fn spawn_sys_cmd(&mut self) {
|
||||
let mut args = self.rt.input.literal.split_whitespace();
|
||||
if let Some(command) = args.next() {
|
||||
match command {
|
||||
"cd" => {
|
||||
self.change_directory(args);
|
||||
"cd" => if ChangeDirectory(None).change_directory(args).is_some() {
|
||||
self.rt.history.add(self.rt.input.literal.as_str())
|
||||
},
|
||||
command => {
|
||||
self.spawn(process::Command::new(command).args(args).spawn());
|
||||
command => if let Ok(mut child) = process::Command::new(command).args(args).spawn() {
|
||||
self.rt.history.add(self.rt.input.literal.as_str());
|
||||
child.wait().ok();
|
||||
} else {
|
||||
println!("pse: Unknown command: {}", self.rt.input.literal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
52
src/history.rs
Normal file
52
src/history.rs
Normal file
@ -0,0 +1,52 @@
|
||||
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 {
|
||||
pub history: Vec<String>,
|
||||
pub index: isize,
|
||||
file: Option<PathBuf>,
|
||||
}
|
||||
impl History {
|
||||
pub fn init() -> Self {
|
||||
let mut history = Vec::new();
|
||||
let file = rc::config_dir().map(|mut config_dir| {
|
||||
config_dir.push(".history");
|
||||
config_dir.is_valid_file_or_create(b"");
|
||||
config_dir
|
||||
});
|
||||
file.as_ref().and_then(|file| {
|
||||
File::open(file).map_or_display_none(|file| {
|
||||
let mut fs_history_vec = BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>();
|
||||
fs_history_vec.dedup();
|
||||
fs_history_vec.reverse();
|
||||
Some(fs_history_vec)
|
||||
})
|
||||
}).inspect(|fs_history_vec| history = fs_history_vec.clone());
|
||||
|
||||
Self { history, file, index: -1 }
|
||||
}
|
||||
|
||||
pub fn write_to_file_fallible(&mut self) {
|
||||
if self.history.is_empty() { return; }
|
||||
|
||||
if let Some(history_file) = &self.file {
|
||||
OpenOptions::new()
|
||||
.append(true)
|
||||
.open(history_file.as_path())
|
||||
.map_or_display(|mut file| {
|
||||
let newline_maybe = if self.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()),
|
||||
};
|
||||
}
|
||||
}
|
22
src/lib.rs
22
src/lib.rs
@ -1,22 +1,10 @@
|
||||
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;
|
||||
|
||||
pub trait MapDisplay<T, E: std::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: 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)
|
||||
}
|
||||
}
|
||||
mod valid_pbuf;
|
24
src/ps.rs
24
src/ps.rs
@ -1,24 +0,0 @@
|
||||
pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
pub struct Ps(String);
|
||||
impl Ps {
|
||||
pub fn set(prompt: String) -> Self {
|
||||
Self(prompt)
|
||||
}
|
||||
|
||||
pub fn working_dir_name(&self) -> String {
|
||||
std::env::current_dir().map_or("?".to_owned(), |path| {
|
||||
path.file_name().map_or("?".to_owned(), |name| {
|
||||
let name_os_string = name.to_os_string();
|
||||
match name_os_string == whoami::username_os() && name_os_string != "root" {
|
||||
true => "~".to_owned(),
|
||||
false => name.to_string_lossy().to_string(),
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn display(&self) {
|
||||
print!("{}", self.0);
|
||||
}
|
||||
}
|
85
src/rc.rs
85
src/rc.rs
@ -1,88 +1,24 @@
|
||||
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
|
||||
|
||||
local cyan = TERMINAL.OUT.FOREGROUND.CYAN
|
||||
local red = TERMINAL.OUT.FOREGROUND.RED
|
||||
|
||||
local username = cyan(SHELL.SYSTEM.USERNAME)
|
||||
local hostname = SHELL.SYSTEM.HOSTNAME
|
||||
local username = SHELL.SYSTEM.USERNAME
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
@ -90,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"")
|
||||
}
|
118
src/session.rs
118
src/session.rs
@ -1,48 +1,76 @@
|
||||
use std::{fs, io::{self}};
|
||||
use mlua::Lua as Luau;
|
||||
use std::{cell::RefCell, fs, rc::Rc};
|
||||
use core::fmt;
|
||||
|
||||
use crate::{
|
||||
vm::{LuauVm, self},
|
||||
commands,
|
||||
ps,
|
||||
rc,
|
||||
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,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Input {
|
||||
pub literal: String,
|
||||
pub cursor: u16,
|
||||
}
|
||||
pub struct Rt {
|
||||
pub input: Input,
|
||||
pub ps: Rc<RefCell<String>>,
|
||||
pub vm: Luau,
|
||||
pub history: History,
|
||||
}
|
||||
pub struct Pse {
|
||||
pub config: Config,
|
||||
pub rt: Rt
|
||||
}
|
||||
impl Pse {
|
||||
const DEFAULT_PS: &str = concat!("pse-", env!("CARGO_PKG_VERSION"), "$ ");
|
||||
|
||||
pub struct LambdaShell {
|
||||
vm: LuauVm,
|
||||
ps1: String,
|
||||
config: Config,
|
||||
terminating: bool,
|
||||
}
|
||||
impl LambdaShell {
|
||||
pub fn create(config: Config) -> Self {
|
||||
Self {
|
||||
vm: vm::LuauVm::new(),
|
||||
ps1: ps::DEFAULT_PS.to_owned(),
|
||||
terminating: false,
|
||||
config,
|
||||
}
|
||||
}
|
||||
let rt = Rt {
|
||||
ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())),
|
||||
vm: Luau::new(),
|
||||
history: History::init(),
|
||||
input: Input {
|
||||
literal: String::new(),
|
||||
cursor: u16::MIN,
|
||||
},
|
||||
};
|
||||
|
||||
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() {
|
||||
//special casey
|
||||
"exit" => self.terminating = true,
|
||||
trim => commands::Command::new(trim.to_owned()).exec()
|
||||
};
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn vm_exec(&self, source: String) {
|
||||
self.vm.exec(source);
|
||||
Self { rt, config }
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
@ -50,21 +78,7 @@ impl LambdaShell {
|
||||
if let Some(conf_file) = rc::config_file() {
|
||||
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
|
||||
}
|
||||
}
|
||||
loop {
|
||||
match self.terminating {
|
||||
true => break,
|
||||
false => {
|
||||
|
||||
match self.wait() {
|
||||
Ok(()) => {},
|
||||
Err(flush_error) => {
|
||||
println!("{flush_error}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
self.term_input_processor().map_or_display(|()| self.rt.history.write_to_file_fallible())
|
||||
}
|
||||
}
|
||||
|
218
src/terminal.rs
Normal file
218
src/terminal.rs
Normal file
@ -0,0 +1,218 @@
|
||||
use crossterm::{cursor, event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, execute, terminal};
|
||||
use core::fmt;
|
||||
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("Sigint")]
|
||||
Sigint,
|
||||
#[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>;
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn debug<S: fmt::Display>(s: S) {
|
||||
terminal::disable_raw_mode().unwrap();
|
||||
println!("{s}");
|
||||
terminal::enable_raw_mode().unwrap()
|
||||
}
|
||||
|
||||
trait SpecificKeybinds {
|
||||
const EXIT_ID_1: &str;
|
||||
const KEY_SPACE: char;
|
||||
fn key_literal(&mut self, keycode: KeyCode) -> InputResult<()>;
|
||||
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>;
|
||||
fn key_enter(&mut self) -> InputResult<()>;
|
||||
fn key_backspace(&mut self) -> InputResult<()>;
|
||||
fn key_arrow_right(&mut self) -> InputResult<()>;
|
||||
fn key_arrow_left(&mut self) -> InputResult<()>;
|
||||
fn key_arrow_up(&mut self) -> InputResult<()>;
|
||||
fn key_arrow_down(&mut self) -> InputResult<()>;
|
||||
}
|
||||
impl SpecificKeybinds for Pse {
|
||||
const EXIT_ID_1: &str = "exit";
|
||||
const KEY_SPACE: char = ' ';
|
||||
|
||||
fn key_literal(&mut self, keycode: KeyCode) -> InputResult<()> {
|
||||
match keycode {
|
||||
KeyCode::Char(Self::KEY_SPACE) => self.term_render(Self::KEY_SPACE.to_string()),
|
||||
keycode => self.term_render(keycode.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()> {
|
||||
match input_key.modifiers.contains(KeyModifiers::CONTROL) {
|
||||
true => match keycode {
|
||||
KeyCode::Char('c') => Err(InputHandleError::Sigint),
|
||||
KeyCode::Char('r') => unimplemented!(),
|
||||
_ => Ok(())
|
||||
},
|
||||
false => self.key_literal(keycode)
|
||||
}
|
||||
}
|
||||
|
||||
fn key_enter(&mut self) -> InputResult<()> {
|
||||
if self.rt.input.literal == Self::EXIT_ID_1 { return Err(InputHandleError::UserExit) };
|
||||
|
||||
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
|
||||
println!();
|
||||
self.spawn_sys_cmd();
|
||||
self.rt.input.literal.clear();
|
||||
self.rt.input.cursor = u16::MIN;
|
||||
self.term_render_ps()
|
||||
}
|
||||
|
||||
fn key_backspace(&mut self) -> InputResult<()> {
|
||||
if self.rt.input.literal.pop().is_some() {
|
||||
execute!(
|
||||
io::stdout(),
|
||||
cursor::MoveLeft(1),
|
||||
terminal::Clear(terminal::ClearType::UntilNewLine)
|
||||
).map_err(InputHandleError::Flush)?;
|
||||
self.rt.input.cursor-=1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key_arrow_right(&mut self) -> InputResult<()> {
|
||||
match self.term_input_cursor_move_right() {
|
||||
Some(()) => execute!(io::stdout(), cursor::MoveRight(1)).map_err(InputHandleError::Flush),
|
||||
None => Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn key_arrow_left(&mut self) -> InputResult<()> {
|
||||
match self.term_input_cursor_move_left() {
|
||||
Some(()) => execute!(io::stdout(), cursor::MoveLeft(1)).map_err(InputHandleError::Flush),
|
||||
None => Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn key_arrow_up(&mut self) -> InputResult<()> {
|
||||
self.rt.history.index += 1;
|
||||
if self.rt.history.index != self.rt.history.history.len() as isize {
|
||||
self.term_render_reset()?;
|
||||
self.term_render(self.rt.history.history[self.rt.history.index as usize].clone())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key_arrow_down(&mut self) -> InputResult<()> {
|
||||
self.rt.history.index -= 1;
|
||||
if self.rt.history.index != -1 {
|
||||
self.term_render_reset()?;
|
||||
self.term_render(self.rt.history.history[self.rt.history.index as usize].clone())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub trait TermInputCursor {
|
||||
fn term_input_cursor_move_left(&mut self) -> Option<()>;
|
||||
fn term_input_cursor_move_right(&mut self) -> Option<()>;
|
||||
}
|
||||
impl TermInputCursor for Pse {
|
||||
fn term_input_cursor_move_left(&mut self) -> Option<()> {
|
||||
if self.rt.input.cursor == u16::MIN { None } else {
|
||||
match self.rt.input.cursor>u16::MIN {
|
||||
true => { self.rt.input.cursor-=1; Some(()) }
|
||||
false => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn term_input_cursor_move_right(&mut self) -> Option<()> {
|
||||
if self.rt.input.cursor == u16::MAX { None } else {
|
||||
match self.rt.input.cursor<self.rt.input.literal.chars().count() as u16 {
|
||||
true => { self.rt.input.cursor+=1; Some(()) },
|
||||
false => None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait TermProcessor {
|
||||
fn term_render(&mut self, def_string: String) -> InputResult<()>;
|
||||
fn term_render_ps(&self) -> InputResult<()>;
|
||||
fn term_render_reset(&mut self) -> 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, text: String) -> InputResult<()> {
|
||||
self.rt.input.literal.insert_str(self.rt.input.cursor.into(), &text);
|
||||
let input_literal_size = self.rt.input.literal.chars().count() as u16;
|
||||
self.rt.input.cursor = input_literal_size;
|
||||
if self.rt.input.cursor != input_literal_size {
|
||||
execute!(io::stdout(), terminal::Clear(terminal::ClearType::UntilNewLine)).map_err(InputHandleError::Flush)?;
|
||||
let slice = &self.rt.input.literal[(self.rt.input.cursor as usize)..];
|
||||
write!(io::stdout(), "{text}{slice}").map_err(InputHandleError::Write)?;
|
||||
} else {
|
||||
write!(io::stdout(), "{text}").map_err(InputHandleError::Write)?;
|
||||
}
|
||||
io::stdout().flush().map_err(InputHandleError::Flush)
|
||||
}
|
||||
|
||||
fn term_render_ps(&self) -> InputResult<()> {
|
||||
print!("{}", self.rt.ps.borrow());
|
||||
io::stdout().flush().map_err(InputHandleError::Flush)
|
||||
}
|
||||
|
||||
fn term_render_reset(&mut self) -> InputResult<()> {
|
||||
execute!(io::stdout(), cursor::MoveLeft(self.rt.input.cursor)).map_err(InputHandleError::Flush)?;
|
||||
self.rt.input.cursor = u16::MIN;
|
||||
self.rt.input.literal.clear();
|
||||
execute!(io::stdout(), terminal::Clear(terminal::ClearType::UntilNewLine)).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 => self.key_arrow_right(),
|
||||
KeyCode::Left => self.key_arrow_left(),
|
||||
KeyCode::Up => self.key_arrow_up(),
|
||||
KeyCode::Down => self.key_arrow_down(),
|
||||
keycode => self.key_ctrl(input_key, keycode)
|
||||
};
|
||||
input_handle.map_or_else(|inp_err| match inp_err {
|
||||
InputHandleError::UserExit => None,
|
||||
InputHandleError::Sigint => self.term_render("^C".to_owned()).ok(),
|
||||
input_err => session::shell_error_none(input_err)
|
||||
}, Some)
|
||||
}
|
||||
|
||||
fn term_input_mainthread(&mut self) -> io::Result<()> {
|
||||
execute!(io::stdout(), event::EnableBracketedPaste)?;
|
||||
self.term_render_ps().map_or_else(|_| Ok(()), |()| {
|
||||
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()?;
|
||||
execute!(io::stdout(), event::DisableBracketedPaste)
|
||||
}
|
||||
}
|
75
src/valid_pbuf.rs
Normal file
75
src/valid_pbuf.rs
Normal 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()
|
||||
}
|
||||
}
|
@ -1,9 +1,10 @@
|
||||
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
|
||||
use color_print::{cformat, ceprintln};
|
||||
use mlua::{Function, MultiValue, Result as lResult, Table, Value};
|
||||
use color_print::cformat;
|
||||
use shell::ShellGlobal;
|
||||
use terminal::TerminalGlobal;
|
||||
use core::fmt;
|
||||
use shell::Shell;
|
||||
|
||||
use crate::{vm::terminal::Terminal, MapDisplay};
|
||||
use crate::session::{Pse, MapDisplay};
|
||||
|
||||
mod shell;
|
||||
mod terminal;
|
||||
@ -16,59 +17,61 @@ 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;
|
||||
fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()>;
|
||||
const CONV_ERROR: &str;
|
||||
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.set("warn", self.0.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("<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()))
|
||||
.collect::<MultiValue>();
|
||||
luau_print.call::<()>(luau_multi_values).unwrap();
|
||||
luau_print.call::<()>(luau_multi_values)?;
|
||||
Ok(())
|
||||
})?)
|
||||
}
|
||||
|
||||
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.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(pub Luau);
|
||||
impl LuauVm {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(Luau::new())
|
||||
pub trait LuauVm {
|
||||
fn vm_setglobs(&self) -> lResult<()>;
|
||||
fn vm_exec(&self, source: String);
|
||||
}
|
||||
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)?;
|
||||
|
||||
luau_globals.raw_set("getfenv", mlua::Nil)?;
|
||||
luau_globals.raw_set("setfenv", mlua::Nil)?;
|
||||
self.rt.vm.enable_jit(self.config.vm.jit);
|
||||
self.rt.vm.sandbox(true)
|
||||
}
|
||||
|
||||
fn set_shell_globals(&self) -> lResult<()> {
|
||||
let luau_globals = self.0.globals();
|
||||
self.global_warn(&luau_globals)?;
|
||||
self.global_version(&luau_globals)?;
|
||||
self.global_terminal(&luau_globals)?;
|
||||
self.global_shell(&luau_globals)?;
|
||||
luau_globals.set("getfenv", mlua::Nil)?;
|
||||
luau_globals.set("setfenv", mlua::Nil)?;
|
||||
self.0.sandbox(true)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn exec(&self, source: String) {
|
||||
self.set_shell_globals().map_or_display_none(|()| {
|
||||
self.0.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));
|
||||
}
|
||||
}
|
@ -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 crate::vm::LuauVm;
|
||||
use crate::session::Pse;
|
||||
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
fn luau_sys_details(luau: &Luau) -> lResult<Table> {
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
|
||||
trait PsPrompt {
|
||||
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> {
|
||||
let prompt_table = self.0.create_table()?;
|
||||
let prompt_metatable = self.0.create_table()?;
|
||||
prompt_metatable.set("__index", self.0.create_function(|_, (table, index): (Table, Value)| -> lResult<String> {
|
||||
table.raw_get::<String>(index)
|
||||
})?)?;
|
||||
prompt_metatable.set("__newindex", self.0.create_function(|_, _: String| -> lResult<String> {
|
||||
Ok("placeholder".to_owned())
|
||||
})?)?;
|
||||
prompt_table.set("__metatable", mlua::Nil)?;
|
||||
prompt_table.set_metatable(Some(prompt_metatable));
|
||||
prompt_table.set_readonly(false);
|
||||
Ok(prompt_table)
|
||||
|
||||
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().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, (t_index, t_value): (String, String)| -> lResult<()> {
|
||||
if t_index == "PROMPT" {
|
||||
let mut prompt = this.0.borrow_mut();
|
||||
*prompt = t_value;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
trait System {
|
||||
fn sys_details(&self) -> lResult<Table>;
|
||||
pub trait ShellGlobal {
|
||||
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
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<()>;
|
||||
}
|
||||
impl Shell for LuauVm {
|
||||
fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let shell = self.0.create_table()?;
|
||||
let ps_prompt = self.ps_prompt()?;
|
||||
shell.set("SYSTEM", self.sys_details()?)?;
|
||||
shell.set("PROMPT", ps_prompt)?;
|
||||
luau_globals.set("SHELL", shell)?;
|
||||
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)))
|
||||
}
|
||||
}
|
@ -1,112 +1,94 @@
|
||||
use mlua::{Function, Result as lResult, Table};
|
||||
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 {
|
||||
($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())
|
||||
})?)?;
|
||||
)+
|
||||
};
|
||||
}
|
||||
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(),
|
||||
$self.0.create_function(|_, text: String| -> lResult<String> {
|
||||
$luau.create_function(|_, text: String| -> lResult<String> {
|
||||
Ok(text.$color().to_string())
|
||||
})?)?;
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
trait Colors {
|
||||
fn background(&self, term_out_table: &Table) -> lResult<()>;
|
||||
fn foreground(&self, term_out_table: &Table) -> lResult<()>;
|
||||
}
|
||||
impl Colors for LuauVm {
|
||||
fn background(&self, term_out_table: &Table) -> lResult<()> {
|
||||
let foreground_table = self.0.create_table()?;
|
||||
foreground_styles_luau!(self, foreground_table,
|
||||
dark_grey dark_red dark_green dark_cyan
|
||||
dark_yellow dark_magenta dark_blue
|
||||
red grey black green yellow
|
||||
blue magenta cyan white
|
||||
underlined
|
||||
underline_dark_grey underline_dark_red underline_dark_green underline_dark_cyan
|
||||
underline_dark_yellow underline_dark_magenta underline_dark_blue underline_red
|
||||
underline_grey underline_black underline_green underline_yellow
|
||||
underline_blue underline_magenta underline_cyan underline_white
|
||||
bold
|
||||
);
|
||||
term_out_table.set("FOREGROUND", foreground_table)
|
||||
}
|
||||
|
||||
fn foreground(&self, term_out_table: &Table) -> lResult<()> {
|
||||
let background_table = self.0.create_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)
|
||||
}
|
||||
fn text_styles_funcs(luau: &Luau) -> lResult<(Table, Table)> {
|
||||
let foreground_table = luau.create_table()?;
|
||||
let background_table = luau.create_table()?;
|
||||
foreground_styles_luau!(luau, foreground_table,
|
||||
dark_grey dark_red dark_green dark_cyan
|
||||
dark_yellow dark_magenta dark_blue
|
||||
red grey black green yellow
|
||||
blue magenta cyan white
|
||||
underlined
|
||||
underline_dark_grey underline_dark_red underline_dark_green underline_dark_cyan
|
||||
underline_dark_yellow underline_dark_magenta underline_dark_blue underline_red
|
||||
underline_grey underline_black underline_green underline_yellow
|
||||
underline_blue underline_magenta underline_cyan underline_white
|
||||
bold
|
||||
crossed_out
|
||||
);
|
||||
background_styles_luau!(luau, 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
|
||||
);
|
||||
Ok((foreground_table, background_table))
|
||||
}
|
||||
|
||||
trait Write {
|
||||
fn write(&self) -> lResult<Function>;
|
||||
fn write_error(&self) -> lResult<Function>;
|
||||
fn write_error_ln(&self) -> lResult<Function>;
|
||||
}
|
||||
impl Write for LuauVm {
|
||||
fn write(&self) -> lResult<Function> {
|
||||
self.0.create_function(|_, s: String| -> lResult<()> {
|
||||
print!("{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(())
|
||||
})
|
||||
}
|
||||
fn fields_write_funcs<F: UserDataFields<Terminal>>(fields: &mut F) {
|
||||
fields.add_field_method_get("WRITE", |luau, _| luau.create_function(|_, s: String| -> lResult<()> {
|
||||
print!("{s}");
|
||||
Ok(())
|
||||
}));
|
||||
fields.add_field_method_get("WRITE_ERROR", |luau, _| luau.create_function(|_, s: String| -> lResult<()> {
|
||||
eprint!("{s}");
|
||||
Ok(())
|
||||
}));
|
||||
fields.add_field_method_get("WRITE_ERROR_LN", |luau, _| luau.create_function(|_, s: String| -> lResult<()> {
|
||||
eprintln!("{s}");
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
pub trait Terminal {
|
||||
fn out(&self) -> lResult<Table>;
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl Terminal 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)
|
||||
struct Terminal;
|
||||
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) {
|
||||
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let term_table = self.0.create_table()?;
|
||||
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)
|
||||
// }
|
||||
}
|
||||
|
||||
pub trait TerminalGlobal {
|
||||
fn vm_glob_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)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user