Compare commits
No commits in common. "master" and "luau/system" have entirely different histories.
master
...
luau/syste
91
Cargo.lock
generated
91
Cargo.lock
generated
@ -10,15 +10,15 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.7.0"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be"
|
||||
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.11.3"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0"
|
||||
checksum = "786a307d683a5bf92e6fd5fd69a7eb613751668d1d8d67d802846dfe367c62c8"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"serde",
|
||||
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.8"
|
||||
version = "1.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad0cf6e91fde44c773c6ee7ec6bba798504641a8bc2eb7e37a04ffbf4dfaa55a"
|
||||
checksum = "8d6dbb628b8f8555f86d0323c2eb39e3ec81901f4b83e091db8a6a76d316a333"
|
||||
dependencies = [
|
||||
"shlex",
|
||||
]
|
||||
@ -73,7 +73,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "126f97965c8ad46d6d9163268ff28432e8f6a1196a55578867832e3049df63dd"
|
||||
dependencies = [
|
||||
"const_format_proc_macros",
|
||||
"konst",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -147,21 +146,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "konst"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330f0e13e6483b8c34885f7e6c9f19b1a7bd449c673fbb948a51c99d66ef74f4"
|
||||
dependencies = [
|
||||
"konst_macro_rules",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "konst_macro_rules"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.169"
|
||||
@ -194,9 +178,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
|
||||
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
@ -214,25 +198,6 @@ version = "0.4.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
|
||||
|
||||
[[package]]
|
||||
name = "lua-src"
|
||||
version = "547.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "luajit-src"
|
||||
version = "210.5.11+97813fb"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3015551c284515db7c30c559fc1080f9cb9ee990d1f6fca315451a107c7540bb"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "luau0-src"
|
||||
version = "0.11.2+luau653"
|
||||
@ -289,8 +254,6 @@ checksum = "63a11d485edf0f3f04a508615d36c7d50d299cf61a7ee6d3e2530651e0a31771"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"lua-src",
|
||||
"luajit-src",
|
||||
"luau0-src",
|
||||
"pkg-config",
|
||||
]
|
||||
@ -351,9 +314,9 @@ checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.93"
|
||||
version = "1.0.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
|
||||
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
@ -384,9 +347,9 @@ checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.43"
|
||||
version = "0.38.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6"
|
||||
checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
@ -465,9 +428,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.96"
|
||||
version = "2.0.94"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80"
|
||||
checksum = "987bc0be1cdea8b10216bd06e2ca407d40b9543468fafd3ddfb02f36e77f71f3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@ -476,18 +439,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.11"
|
||||
version = "2.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc"
|
||||
checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.11"
|
||||
version = "2.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2"
|
||||
checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@ -592,18 +555,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "which"
|
||||
version = "6.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"
|
||||
dependencies = [
|
||||
"either",
|
||||
"home",
|
||||
"rustix",
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "whoami"
|
||||
version = "1.5.2"
|
||||
@ -718,9 +669,3 @@ name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "winsafe"
|
||||
version = "0.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
|
||||
|
12
Cargo.toml
12
Cargo.toml
@ -5,10 +5,16 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
color-print = "0.3.7"
|
||||
const_format = { version = "0.2.34", features = ["rust_1_64"] }
|
||||
const_format = "0.2.33"
|
||||
crossterm = "0.28.1"
|
||||
home = "0.5.9"
|
||||
mlua = { version = "0.10.0", features = ["luau-jit", "vendored"] }
|
||||
mlua = { version = "0.10.0", features = ["luau-jit"] }
|
||||
thiserror = "2.0.9"
|
||||
uzers = "0.12.1"
|
||||
whoami = "1.5.2"
|
||||
whoami = "1.5.2"
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
|
21
LICENSE
21
LICENSE
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 rhpidfyre
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -1,16 +1,25 @@
|
||||
use std::{io, process, str::SplitWhitespace, path::{Path, PathBuf}};
|
||||
use uzers::User;
|
||||
use std::{
|
||||
io,
|
||||
process,
|
||||
str::SplitWhitespace,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use crate::{history::History, session::MapDisplay, valid_pbuf::IsValid};
|
||||
enum ValidStatus {
|
||||
NoRootFolder,
|
||||
TryExists(io::Error)
|
||||
}
|
||||
|
||||
fn display_none<T>(e: io::Error) -> Option<T> {
|
||||
println!("{e}");
|
||||
None
|
||||
}
|
||||
|
||||
trait PathBufIsValid {
|
||||
fn is_valid(&self) -> Result<PathBuf, ValidStatus>;
|
||||
fn is_valid_or_home(&self) -> Option<PathBuf>;
|
||||
}
|
||||
impl PathBufIsValid for PathBuf {
|
||||
fn is_valid_or_home(&self) -> Option<PathBuf> {
|
||||
self.is_valid_or(self.is_dir(), home::home_dir)
|
||||
}
|
||||
}
|
||||
|
||||
trait ChangeDirectory {
|
||||
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
|
||||
@ -20,9 +29,33 @@ trait ChangeDirectory {
|
||||
fn previous_dir(&self) -> Option<PathBuf>;
|
||||
fn home_dir(&self) -> Option<PathBuf>;
|
||||
}
|
||||
|
||||
impl PathBufIsValid for PathBuf {
|
||||
fn is_valid(&self) -> Result<PathBuf, ValidStatus> {
|
||||
match self.try_exists() {
|
||||
Ok(true) => Ok(self.to_path_buf()),
|
||||
Ok(false) => Err(ValidStatus::NoRootFolder),
|
||||
Err(trye_error) => Err(ValidStatus::TryExists(trye_error))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_valid_or_home(&self) -> Option<PathBuf> {
|
||||
match self.is_valid() {
|
||||
Ok(valid) => Some(valid),
|
||||
Err(valid_status) => {
|
||||
match valid_status {
|
||||
ValidStatus::NoRootFolder => println!("cd: /root: No such file or directory"),
|
||||
ValidStatus::TryExists(error) => println!("cd: {error}"),
|
||||
};
|
||||
None
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChangeDirectory for Command {
|
||||
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_else(display_none, |()| Some(new_path.to_path_buf()))
|
||||
}
|
||||
|
||||
fn home_dir(&self) -> Option<PathBuf> {
|
||||
@ -89,25 +122,24 @@ impl ChangeDirectory for Command {
|
||||
|
||||
pub struct Command(String);
|
||||
impl Command {
|
||||
pub const fn new(input: String) -> Self {
|
||||
pub fn new(input: String) -> Self {
|
||||
Self(input)
|
||||
}
|
||||
|
||||
pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
|
||||
if let Ok(mut child) = command_process {
|
||||
history.add(self.0.as_str());
|
||||
child.wait().ok();
|
||||
} else {
|
||||
println!("Unknown command: {}", self.0)
|
||||
}
|
||||
pub fn spawn(&self, command_process: io::Result<process::Child>) {
|
||||
command_process.map_or_else(display_none, |mut child| Some(child.wait()));
|
||||
}
|
||||
|
||||
pub fn exec(&mut self, history: &mut History) {
|
||||
pub fn exec(&self) {
|
||||
let mut args = self.0.split_whitespace();
|
||||
if let Some(command) = args.next() {
|
||||
match command {
|
||||
"cd" => if self.change_directory(args).is_some() { history.add(self.0.as_str()) },
|
||||
command => { self.spawn_sys_cmd(history, process::Command::new(command).args(args).spawn()); }
|
||||
"cd" => {
|
||||
self.change_directory(args);
|
||||
},
|
||||
command => {
|
||||
self.spawn(process::Command::new(command).args(args).spawn());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,52 +0,0 @@
|
||||
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" };
|
||||
if let Err(write_err) = file.write_all(format!("{newline_maybe}{}", self.history.join("\n")).as_bytes()) {
|
||||
session::shell_error(write_err);
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
};
|
||||
}
|
||||
}
|
19
src/lib.rs
19
src/lib.rs
@ -1,10 +1,15 @@
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub mod session;
|
||||
pub mod commands;
|
||||
pub mod history;
|
||||
pub mod ps;
|
||||
pub mod rc;
|
||||
pub mod vm;
|
||||
pub mod shell;
|
||||
mod commands;
|
||||
mod ps;
|
||||
mod rc;
|
||||
|
||||
mod valid_pbuf;
|
||||
#[path = "./luau/vm.rs"]
|
||||
mod vm;
|
||||
#[path = "./luau/alias.rs"]
|
||||
mod alias;
|
||||
#[path = "./luau/terminal.rs"]
|
||||
mod terminal;
|
||||
#[path = "./luau/system.rs"]
|
||||
mod sytem;
|
31
src/luau/system.rs
Normal file
31
src/luau/system.rs
Normal file
@ -0,0 +1,31 @@
|
||||
use mlua::{Result as lResult, Table};
|
||||
use whoami::fallible;
|
||||
use crate::vm::Vm;
|
||||
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
|
||||
pub trait System {
|
||||
fn details(&self, shell: &Table) -> lResult<()>;
|
||||
fn global_shell(&self) -> lResult<()>;
|
||||
}
|
||||
impl System for Vm {
|
||||
fn details(&self, shell: &Table) -> lResult<()> {
|
||||
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()))?;
|
||||
shell.set("SYSTEM", system)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn global_shell(&self) -> lResult<()> {
|
||||
let shell = self.0.create_table()?;
|
||||
self.details(&shell)?;
|
||||
self.0.globals().set("SHELL", shell)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
80
src/luau/terminal.rs
Normal file
80
src/luau/terminal.rs
Normal file
@ -0,0 +1,80 @@
|
||||
use mlua::{Result as lResult, Table};
|
||||
use crossterm::style::Stylize;
|
||||
use crate::vm::Vm;
|
||||
|
||||
macro_rules! foreground_styles_luau {
|
||||
($self:expr, $style_table:expr, $($color:ident)+) => {
|
||||
$(
|
||||
$style_table.set(stringify!($color).to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> {
|
||||
Ok(text.$color().to_string())
|
||||
})?)?;
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! background_styles_luau {
|
||||
($self:expr, $style_table:expr, $($color:ident)+) => {
|
||||
$(
|
||||
match stringify!($color).split_once("_") {
|
||||
Some((_, color_name)) => $style_table.set(color_name.to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> {
|
||||
Ok(text.$color().to_string())
|
||||
})?)?,
|
||||
None => panic!("Luau set error: {:?}. There was nothing to split from delimiter: \"_\"", stringify!($color)),
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
pub trait TerminalColors {
|
||||
fn background(&self, style_table: &Table) -> lResult<()>;
|
||||
fn foreground(&self, style_table: &Table) -> lResult<()>;
|
||||
fn styling(&self) -> lResult<Table>;
|
||||
fn terminal(&self) -> lResult<()>;
|
||||
}
|
||||
impl TerminalColors for Vm {
|
||||
fn background(&self, style_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
|
||||
);
|
||||
style_table.set("FOREGROUND", foreground_table)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn foreground(&self, style_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
|
||||
);
|
||||
style_table.set("BACKGROUND", background_table)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn styling(&self) -> lResult<Table> {
|
||||
let style_table = self.0.create_table()?;
|
||||
self.foreground(&style_table)?;
|
||||
self.background(&style_table)?;
|
||||
Ok(style_table)
|
||||
}
|
||||
|
||||
fn terminal(&self) -> lResult<()> {
|
||||
let term_table = self.0.create_table()?;
|
||||
term_table.set("OUT", self.styling()?)?;
|
||||
self.0.globals().set("TERMINAL", &term_table)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
52
src/luau/vm.rs
Normal file
52
src/luau/vm.rs
Normal file
@ -0,0 +1,52 @@
|
||||
use mlua::{
|
||||
Lua as Luau,
|
||||
Result as lResult
|
||||
};
|
||||
use crate::VERSION;
|
||||
use crate::terminal::TerminalColors;
|
||||
use crate::sytem::System;
|
||||
use core::fmt;
|
||||
use color_print::cprintln;
|
||||
|
||||
fn display_none<T, E: fmt::Display>(err: E) -> Option<T> {
|
||||
println!("{err}");
|
||||
None
|
||||
}
|
||||
|
||||
fn luau_error<T>(err: mlua::Error) -> Option<T> {
|
||||
cprintln!("<bold>====</>\n<r><bold>[!]</> {err}</>\n<bold>====</>");
|
||||
None
|
||||
}
|
||||
|
||||
trait Globals {
|
||||
fn version(&self) -> lResult<()>;
|
||||
}
|
||||
impl Globals for Vm {
|
||||
fn version(&self) -> lResult<()> {
|
||||
let luau_info = self.0.globals().get::<String>("_VERSION")?;
|
||||
self.0.globals().set("_VERSION", format!("{}, liblambdashell {}", luau_info, VERSION))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Vm(pub Luau);
|
||||
impl Vm {
|
||||
pub fn new() -> Self {
|
||||
Self(Luau::new())
|
||||
}
|
||||
|
||||
fn set_shell_globals(&self) -> mlua::Result<()> {
|
||||
self.version()?;
|
||||
self.terminal()?;
|
||||
self.global_shell()?;
|
||||
self.0.globals().set("getfenv", mlua::Nil)?;
|
||||
self.0.globals().set("setfenv", mlua::Nil)?;
|
||||
self.0.sandbox(true)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn exec(&self, source: String) {
|
||||
self.set_shell_globals().map_or_else(display_none, |()| {
|
||||
self.0.load(source).exec().map_or_else(luau_error, Some)
|
||||
});
|
||||
}
|
||||
}
|
39
src/ps.rs
39
src/ps.rs
@ -1,28 +1,21 @@
|
||||
pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"), " ");
|
||||
use const_format::formatcp;
|
||||
use color_print::{cformat, cprint};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Ps(String);
|
||||
impl Ps {
|
||||
pub const fn set(prompt: String) -> Self {
|
||||
Self(prompt)
|
||||
}
|
||||
//rustc: `std::string::String::as_str` is not yet stable as a const fn
|
||||
pub fn get(&self) -> &str {
|
||||
self.0.as_str()
|
||||
}
|
||||
pub fn modify(&mut self, prompt: String) {
|
||||
self.0 = prompt
|
||||
}
|
||||
pub fn display(&self) {
|
||||
print!("{}", self.0);
|
||||
}
|
||||
pub const DEFAULT_PS: &str = formatcp!("lambdashell-{}", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
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() {
|
||||
pub fn working_dir_name() -> 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(ps1: &String) {
|
||||
let working_dir_name = cformat!(" <bold>{}</> ", working_dir_name());
|
||||
cprint!("{}{}λ ", ps1, working_dir_name);
|
||||
}
|
||||
|
110
src/rc.rs
110
src/rc.rs
@ -1,29 +1,117 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::valid_pbuf::IsValid;
|
||||
use std::{fs::{self, File}, io::{self, Write}, path::PathBuf};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const DEFAULT_CONFIG_CONTENT: &str = r#"--!strict
|
||||
|
||||
local cyan = TERMINAL.OUT.FOREGROUND.CYAN
|
||||
local red = TERMINAL.OUT.FOREGROUND.RED
|
||||
|
||||
local hostname = SHELL.SYSTEM.HOSTNAME
|
||||
local username = SHELL.SYSTEM.USERNAME
|
||||
|
||||
username = if username == "root" then red(username) else cyan(username)
|
||||
local hostname = SHELL.SYSTEM.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
|
||||
}
|
||||
|
||||
fn display_none<T>(e: io::Error) -> Option<T> {
|
||||
println!("{e}");
|
||||
None
|
||||
}
|
||||
|
||||
#[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) => match is_content {
|
||||
true => Ok(self.to_path_buf()),
|
||||
false => 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>
|
||||
{
|
||||
let possible_content = self.is_valid(is_content).map_err(|e| match e {
|
||||
IsValidDirErr::TryExists(try_e) => CreateErr::TryExists(try_e),
|
||||
IsValidDirErr::NotAnEntry | IsValidDirErr::Missing => CreateErr::Passable
|
||||
});
|
||||
match possible_content {
|
||||
Ok(p) => Some(p),
|
||||
Err(e) => match e {
|
||||
CreateErr::TryExists(_) => None,
|
||||
CreateErr::Passable => f()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn is_valid_dir_or_create(&self) -> Option<PathBuf> {
|
||||
self.is_valid_or(self.is_dir(), || {
|
||||
match fs::create_dir(self) {
|
||||
Ok(()) => Some(self.to_path_buf()),
|
||||
Err(create_e) => display_none(create_e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf> {
|
||||
self.is_valid_or(self.is_file(), || {
|
||||
match File::create(self) {
|
||||
Ok(mut file) => match file.write_all(default_file_bytes) {
|
||||
Ok(()) => Some(self.to_path_buf()),
|
||||
Err(write_e) => display_none(write_e),
|
||||
},
|
||||
Err(create_e) => display_none(create_e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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.is_valid_option(config.is_dir())?;
|
||||
config.push("lambdashell");
|
||||
config.is_valid_dir_or_create()
|
||||
}
|
||||
|
||||
pub fn config_file() -> Option<PathBuf> {
|
||||
let mut config_file = config_dir()?;
|
||||
config_file.push("init.luau");
|
||||
config_file.push("config.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"")
|
||||
}
|
@ -1,94 +0,0 @@
|
||||
use std::{cell::RefCell, fs, io::{self}, rc::Rc};
|
||||
use core::fmt;
|
||||
use color_print::ceprintln;
|
||||
|
||||
use crate::{
|
||||
commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm}
|
||||
};
|
||||
|
||||
#[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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub norc: bool
|
||||
}
|
||||
pub struct LambdaShell {
|
||||
terminate: bool,
|
||||
history: History,
|
||||
config: Config,
|
||||
vm: LuauVm,
|
||||
ps: Rc<RefCell<Ps>>,
|
||||
}
|
||||
impl LambdaShell {
|
||||
pub fn create(config: Config) -> Self {
|
||||
let ps = Rc::new(RefCell::new(Ps::set(ps::DEFAULT_PS.to_owned())));
|
||||
Self {
|
||||
ps: Rc::clone(&ps),
|
||||
vm: vm::LuauVm::new(ps),
|
||||
history: History::init(),
|
||||
terminate: false,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wait(&mut self) -> Result<(), io::Error> {
|
||||
io::Write::flush(&mut io::stdout()).map(|()| {
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() {
|
||||
"exit" => {
|
||||
self.terminate = true;
|
||||
self.history.add("exit");
|
||||
},
|
||||
trim => commands::Command::new(trim.to_owned()).exec(&mut self.history)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn error<E: fmt::Display>(&mut self, err: E) {
|
||||
shell_error(err);
|
||||
self.terminate = true;
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
if !self.config.norc {
|
||||
if let Some(conf_file) = rc::config_file() {
|
||||
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
|
||||
}
|
||||
}
|
||||
self.ps.borrow().display();
|
||||
|
||||
loop {
|
||||
if self.terminate { break } else {
|
||||
match self.wait() {
|
||||
Ok(()) => self.ps.borrow().display(),
|
||||
Err(flush_err) => self.error(flush_err),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.history.write_to_file_fallible();
|
||||
}
|
||||
|
||||
pub fn vm_exec(&self, source: String) {
|
||||
self.vm.exec(source);
|
||||
}
|
||||
}
|
73
src/shell.rs
Normal file
73
src/shell.rs
Normal file
@ -0,0 +1,73 @@
|
||||
use crate::{ps, commands, rc, vm};
|
||||
use std::{fs, io::{self}};
|
||||
|
||||
pub struct Config {
|
||||
pub norc: bool
|
||||
}
|
||||
|
||||
trait ShellLuauVm {
|
||||
fn shell_vm_exec(&self, source: String);
|
||||
}
|
||||
impl ShellLuauVm for LambdaShell {
|
||||
fn shell_vm_exec(&self, source: String) {
|
||||
vm::Vm::new().exec(source);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LambdaShell {
|
||||
ps1: String,
|
||||
config: Config,
|
||||
terminating: bool,
|
||||
}
|
||||
impl LambdaShell {
|
||||
pub fn create(config: Config) -> Self {
|
||||
Self {
|
||||
ps1: ps::DEFAULT_PS.to_owned(),
|
||||
terminating: false,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wait(&mut self) -> Result<(), io::Error> {
|
||||
io::Write::flush(&mut io::stdout()).map(|()| {
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).map_or_else(|read_error| println!("{read_error}"), |_size| {
|
||||
match input.trim() {
|
||||
//special casey
|
||||
"exit" => self.terminating = true,
|
||||
trim => commands::Command::new(trim.to_owned()).exec()
|
||||
};
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn rc_parse(&self) {
|
||||
if !self.config.norc {
|
||||
if let Some(conf_file) = rc::config_file() {
|
||||
match fs::read_to_string(conf_file) {
|
||||
Ok(luau_conf) => self.shell_vm_exec(luau_conf),
|
||||
Err(read_err) => println!("{read_err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
self.rc_parse();
|
||||
|
||||
ps::display(&self.ps1);
|
||||
|
||||
loop {
|
||||
match self.terminating {
|
||||
true => break,
|
||||
false => match self.wait() {
|
||||
Ok(()) => ps::display(&self.ps1),
|
||||
Err(flush_error) => {
|
||||
println!("{flush_error}");
|
||||
break;
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,75 +0,0 @@
|
||||
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,79 +0,0 @@
|
||||
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
|
||||
use color_print::{cformat, ceprintln};
|
||||
use terminal::TerminalGlobal;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use core::fmt;
|
||||
use shell::ShellGlobal;
|
||||
|
||||
use crate::{ps::Ps, session::MapDisplay};
|
||||
|
||||
mod shell;
|
||||
mod terminal;
|
||||
mod alias;
|
||||
|
||||
trait LuauRuntimeErr<T> {
|
||||
fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
|
||||
}
|
||||
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>====</>");
|
||||
None
|
||||
}, f)
|
||||
}
|
||||
}
|
||||
|
||||
trait Globals {
|
||||
const LIB_VERSION: &str;
|
||||
const CONV_ERROR: &str;
|
||||
fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl Globals for LuauVm {
|
||||
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
|
||||
|
||||
fn global_warn(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let luau_print = luau_globals.get::<Function>("print")?;
|
||||
luau_globals.raw_set("warn", self.vm.create_function(move |this, args: MultiValue| -> lResult<()> {
|
||||
let luau_multi_values = args.into_iter()
|
||||
.map(|value| cformat!("<bold,y>{}</>", value.to_string().unwrap_or(Self::CONV_ERROR.to_owned())))
|
||||
.map(|arg_v| Value::String(this.create_string(arg_v).unwrap()))
|
||||
.collect::<MultiValue>();
|
||||
luau_print.call::<()>(luau_multi_values)?;
|
||||
Ok(())
|
||||
})?)
|
||||
}
|
||||
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let luau_info = luau_globals.get::<String>("_VERSION")?;
|
||||
luau_globals.raw_set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LuauVm {
|
||||
vm: Luau,
|
||||
ps: Rc<RefCell<Ps>>
|
||||
}
|
||||
impl LuauVm {
|
||||
pub(crate) fn new(ps: Rc<RefCell<Ps>>) -> Self {
|
||||
Self { vm: Luau::new(), ps }
|
||||
}
|
||||
|
||||
fn set_shell_globals(&self) -> lResult<()> {
|
||||
let luau_globals = self.vm.globals();
|
||||
self.global_shell(&luau_globals)?;
|
||||
self.global_terminal(&luau_globals)?;
|
||||
self.global_warn(&luau_globals)?;
|
||||
self.global_version(&luau_globals)?;
|
||||
luau_globals.raw_set("getfenv", mlua::Nil)?;
|
||||
luau_globals.raw_set("setfenv", mlua::Nil)?;
|
||||
self.vm.sandbox(true)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn exec(&self, source: String) {
|
||||
self.set_shell_globals().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
use mlua::{Lua as Luau, MetaMethod, Result as lResult, Table, UserData, UserDataFields, UserDataMethods};
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use whoami::fallible;
|
||||
|
||||
use crate::{ps::Ps, vm::LuauVm};
|
||||
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
|
||||
fn luau_sys_details(luau: &Luau) -> 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)
|
||||
}
|
||||
|
||||
struct Shell(Rc<RefCell<Ps>>);
|
||||
impl UserData for Shell {
|
||||
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
|
||||
fields.add_field_method_get("PROMPT", |_, this| Ok(this.0.borrow().get().to_owned()));
|
||||
fields.add_field_method_get("SYSTEM", |luau, _| luau_sys_details(luau));
|
||||
}
|
||||
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (tindex, tvalue): (String, String)| -> lResult<()> {
|
||||
if tindex == "PROMPT" {
|
||||
this.0.borrow_mut().modify(tvalue);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ShellGlobal {
|
||||
fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl ShellGlobal for LuauVm {
|
||||
fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
|
||||
luau_globals.set("SHELL", Shell(Rc::clone(&self.ps)))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
@ -1,93 +0,0 @@
|
||||
use mlua::{UserDataFields, Lua as Luau, Result as lResult, Table, UserData};
|
||||
use const_format::str_split;
|
||||
use crossterm::style::Stylize;
|
||||
|
||||
use crate::vm::LuauVm;
|
||||
|
||||
macro_rules! foreground_styles_luau {
|
||||
($luau:expr, $style_table:expr, $($color:ident)+) => {
|
||||
$(
|
||||
$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 {
|
||||
($luau:expr, $style_table:expr, $($color:ident)+) => {
|
||||
$(
|
||||
$style_table.raw_set(
|
||||
str_split!(stringify!($color), "_")[1..].join("_").to_ascii_uppercase(),
|
||||
$luau.create_function(|_, text: String| -> lResult<String> {
|
||||
Ok(text.$color().to_string())
|
||||
})?)?;
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
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))
|
||||
}
|
||||
|
||||
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(())
|
||||
}));
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
// }
|
||||
}
|
||||
|
||||
pub trait TerminalGlobal {
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl TerminalGlobal for LuauVm {
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
|
||||
luau_globals.raw_set("TERMINAL", Terminal)
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user