refactoring
This commit is contained in:
parent
edced4ddf1
commit
9f0a376d5e
@ -6,16 +6,13 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use crate::MapDisplay;
|
||||
|
||||
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>;
|
||||
@ -55,7 +52,7 @@ impl PathBufIsValid for PathBuf {
|
||||
|
||||
impl ChangeDirectory for Command {
|
||||
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf> {
|
||||
std::env::set_current_dir(new_path).map_or_else(display_none, |()| Some(new_path.to_path_buf()))
|
||||
std::env::set_current_dir(new_path).map_or_display_none(|()| Some(new_path.to_path_buf()))
|
||||
}
|
||||
|
||||
fn home_dir(&self) -> Option<PathBuf> {
|
||||
@ -127,7 +124,7 @@ impl Command {
|
||||
}
|
||||
|
||||
pub fn spawn(&self, command_process: io::Result<process::Child>) {
|
||||
command_process.map_or_else(display_none, |mut child| Some(child.wait()));
|
||||
command_process.map_or_display_none(|mut child| Some(child.wait()));
|
||||
}
|
||||
|
||||
pub fn exec(&self) {
|
||||
|
20
src/lib.rs
20
src/lib.rs
@ -1,8 +1,22 @@
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub mod session;
|
||||
pub mod commands;
|
||||
pub mod ps;
|
||||
pub mod rc;
|
||||
pub mod vm;
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
12
src/ps.rs
12
src/ps.rs
@ -1,14 +1,12 @@
|
||||
use const_format::formatcp;
|
||||
pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
pub const DEFAULT_PS: &str = formatcp!("lambdashell-{}", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
struct Ps(String);
|
||||
pub struct Ps(String);
|
||||
impl Ps {
|
||||
fn set(prompt: String) -> Self {
|
||||
pub fn set(prompt: String) -> Self {
|
||||
Self(prompt)
|
||||
}
|
||||
|
||||
fn working_dir_name(&self) -> String {
|
||||
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();
|
||||
@ -20,7 +18,7 @@ impl Ps {
|
||||
})
|
||||
}
|
||||
|
||||
fn display(&self) {
|
||||
pub fn display(&self) {
|
||||
print!("{}", self.0);
|
||||
}
|
||||
}
|
46
src/rc.rs
46
src/rc.rs
@ -1,9 +1,13 @@
|
||||
use std::{fs::{self, File}, io::{self, Write}, path::PathBuf};
|
||||
use std::{path::PathBuf, fs::{self, File}, io::{self, Write}};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::MapDisplay;
|
||||
|
||||
pub const DEFAULT_CONFIG_CONTENT: &str = r#"--!strict
|
||||
|
||||
local username = SHELL.SYSTEM.USERNAME
|
||||
local cyan = TERMINAL.OUT.FOREGROUND.CYAN
|
||||
|
||||
local username = cyan(SHELL.SYSTEM.USERNAME)
|
||||
local hostname = SHELL.SYSTEM.HOSTNAME
|
||||
|
||||
SHELL.PROMPT = `{username}@{hostname} λ `"#;
|
||||
@ -25,11 +29,6 @@ enum CreateErr {
|
||||
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>;
|
||||
@ -56,37 +55,24 @@ impl IsValid for PathBuf {
|
||||
where
|
||||
F: FnOnce() -> Option<PathBuf>
|
||||
{
|
||||
let possible_content = self.is_valid(is_content).map_err(|e| match e {
|
||||
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()
|
||||
},
|
||||
}
|
||||
}).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(), || {
|
||||
match fs::create_dir(self) {
|
||||
Ok(()) => Some(self.to_path_buf()),
|
||||
Err(create_e) => display_none(create_e),
|
||||
}
|
||||
})
|
||||
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(), || {
|
||||
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)
|
||||
}
|
||||
File::create(self).map_or_display_none(|mut file| {
|
||||
file.write_all(default_file_bytes).map_or_display_none(|()| Some(self.to_path_buf()))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@ -98,7 +84,7 @@ impl IsValid for PathBuf {
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
let mut config = home::home_dir()?;
|
||||
config.push(".config");
|
||||
config.is_valid_option(config.is_dir())?;
|
||||
config.is_valid_dir_or_create()?;
|
||||
config.push("lambdashell");
|
||||
config.is_valid_dir_or_create()
|
||||
}
|
||||
|
@ -1,6 +1,13 @@
|
||||
use crate::{commands, ps, rc, vm::{LuauVm, self}};
|
||||
use std::{fs, io::{self}};
|
||||
|
||||
use crate::{
|
||||
vm::{LuauVm, self},
|
||||
commands,
|
||||
ps,
|
||||
rc,
|
||||
MapDisplay,
|
||||
};
|
||||
|
||||
pub struct Config {
|
||||
pub norc: bool
|
||||
}
|
||||
@ -24,7 +31,7 @@ impl LambdaShell {
|
||||
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| {
|
||||
io::stdin().read_line(&mut input).map_or_display(|_size| {
|
||||
match input.trim() {
|
||||
//special casey
|
||||
"exit" => self.terminating = true,
|
||||
@ -41,7 +48,7 @@ impl LambdaShell {
|
||||
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_else(|e| println!("{e}"), |luau_conf| self.vm_exec(luau_conf));
|
||||
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
|
||||
}
|
||||
}
|
||||
loop {
|
||||
|
@ -1,41 +1,40 @@
|
||||
use mlua::{
|
||||
Function, Lua as Luau, MultiValue, Result as lResult, Table, Value
|
||||
};
|
||||
use crate::vm::{shell::System, terminal::Terminal};
|
||||
use crate::VERSION;
|
||||
use color_print::{cformat, cprintln};
|
||||
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
|
||||
use color_print::{cformat, ceprintln};
|
||||
use core::fmt;
|
||||
use shell::Shell;
|
||||
|
||||
use crate::{vm::terminal::Terminal, MapDisplay};
|
||||
|
||||
mod shell;
|
||||
mod terminal;
|
||||
mod alias;
|
||||
|
||||
trait Helpers {
|
||||
fn option_display_none<T, E: fmt::Display>(&self, err: E) -> Option<T>;
|
||||
fn luau_error<T>(&self, err: mlua::Error) -> Option<T>;
|
||||
trait LuauRuntimeErr<T> {
|
||||
fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
|
||||
}
|
||||
impl Helpers for LuauVm {
|
||||
fn option_display_none<T, E: fmt::Display>(&self, err: E) -> Option<T> {
|
||||
println!("{err}");
|
||||
None
|
||||
}
|
||||
|
||||
fn luau_error<T>(&self, err: mlua::Error) -> Option<T> {
|
||||
cprintln!("<bold>====</>\n<r><bold>[!]:</> {err}</>\n<bold>====</>");
|
||||
None
|
||||
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;
|
||||
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");
|
||||
|
||||
fn global_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<()> {
|
||||
let luau_multi_values = args.into_iter()
|
||||
.map(|value| cformat!("<y>{}</>", value.to_string().unwrap_or("<SHELL CONVERSION ERROR>".to_owned())))
|
||||
.map(|value| cformat!("<bold,y>{}</>", value.to_string().unwrap_or("<SHELL CONVERSION ERROR>".to_owned())))
|
||||
.map(|arg_v| Value::String(this.create_string(arg_v).unwrap()))
|
||||
.collect::<MultiValue>();
|
||||
luau_print.call::<()>(luau_multi_values).unwrap();
|
||||
@ -45,7 +44,7 @@ impl Globals for LuauVm {
|
||||
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let luau_info = luau_globals.get::<String>("_VERSION")?;
|
||||
luau_globals.set("_VERSION", format!("{}, liblambdashell {}", luau_info, VERSION))
|
||||
luau_globals.set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
|
||||
}
|
||||
}
|
||||
|
||||
@ -60,7 +59,7 @@ impl LuauVm {
|
||||
self.global_warn(&luau_globals)?;
|
||||
self.global_version(&luau_globals)?;
|
||||
self.global_terminal(&luau_globals)?;
|
||||
self.shell_globals(&luau_globals)?;
|
||||
self.global_shell(&luau_globals)?;
|
||||
luau_globals.set("getfenv", mlua::Nil)?;
|
||||
luau_globals.set("setfenv", mlua::Nil)?;
|
||||
self.0.sandbox(true)?;
|
||||
@ -68,9 +67,8 @@ impl LuauVm {
|
||||
}
|
||||
|
||||
pub fn exec(&self, source: String) {
|
||||
match self.set_shell_globals() {
|
||||
Ok(()) => self.0.load(source).exec().map_or_else(|exec_err| self.luau_error(exec_err), Some),
|
||||
Err(globals_err) => self.option_display_none(globals_err),
|
||||
};
|
||||
self.set_shell_globals().map_or_display_none(|()| {
|
||||
self.0.load(source).exec().map_or_luau_rt_err(Some)
|
||||
});
|
||||
}
|
||||
}
|
@ -1,10 +1,11 @@
|
||||
use mlua::{Result as lResult, Table, Value};
|
||||
use whoami::fallible;
|
||||
|
||||
use crate::vm::LuauVm;
|
||||
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
|
||||
pub trait PsPrompt {
|
||||
trait PsPrompt {
|
||||
fn ps_prompt(&self) -> lResult<Table>;
|
||||
}
|
||||
impl PsPrompt for LuauVm {
|
||||
@ -19,16 +20,16 @@ impl PsPrompt for LuauVm {
|
||||
})?)?;
|
||||
prompt_table.set("__metatable", mlua::Nil)?;
|
||||
prompt_table.set_metatable(Some(prompt_metatable));
|
||||
prompt_table.set_readonly(false);
|
||||
Ok(prompt_table)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait System {
|
||||
fn sys_details(&self, shell: &Table) -> lResult<()>;
|
||||
fn shell_globals(&self, luau_globals: &Table) -> lResult<()>;
|
||||
trait System {
|
||||
fn sys_details(&self) -> lResult<Table>;
|
||||
}
|
||||
impl System for LuauVm {
|
||||
fn sys_details(&self, shell: &Table) -> lResult<()> {
|
||||
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())?;
|
||||
@ -37,14 +38,18 @@ impl System for LuauVm {
|
||||
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(())
|
||||
Ok(system)
|
||||
}
|
||||
}
|
||||
|
||||
fn shell_globals(&self, luau_globals: &Table) -> lResult<()> {
|
||||
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()?;
|
||||
self.sys_details(&shell)?;
|
||||
shell.set("SYSTEM", self.sys_details()?)?;
|
||||
shell.set("PROMPT", ps_prompt)?;
|
||||
luau_globals.set("SHELL", shell)?;
|
||||
Ok(())
|
||||
|
@ -1,6 +1,7 @@
|
||||
use const_format::str_split;
|
||||
use mlua::{Function, Result as lResult, Table};
|
||||
use const_format::str_split;
|
||||
use crossterm::style::Stylize;
|
||||
|
||||
use crate::vm::LuauVm;
|
||||
|
||||
macro_rules! foreground_styles_luau {
|
||||
@ -15,21 +16,21 @@ macro_rules! foreground_styles_luau {
|
||||
macro_rules! background_styles_luau {
|
||||
($self:expr, $style_table:expr, $($color:ident)+) => {
|
||||
$(
|
||||
$style_table.set(str_split!(stringify!($color), "_")[1..].join("_").to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> {
|
||||
$style_table.set(
|
||||
str_split!(stringify!($color), "_")[1..].join("_").to_ascii_uppercase(),
|
||||
$self.0.create_function(|_, text: String| -> lResult<String> {
|
||||
Ok(text.$color().to_string())
|
||||
})?)?;
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
trait Colors {
|
||||
fn background(&self, style_table: &Table) -> lResult<()>;
|
||||
fn foreground(&self, style_table: &Table) -> lResult<()>;
|
||||
fn styling(&self, term_out_table: &Table) -> lResult<()>;
|
||||
fn background(&self, term_out_table: &Table) -> lResult<()>;
|
||||
fn foreground(&self, term_out_table: &Table) -> lResult<()>;
|
||||
}
|
||||
impl Colors for LuauVm {
|
||||
fn background(&self, style_table: &Table) -> lResult<()> {
|
||||
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
|
||||
@ -43,10 +44,10 @@ impl Colors for LuauVm {
|
||||
underline_blue underline_magenta underline_cyan underline_white
|
||||
bold
|
||||
);
|
||||
style_table.set("FOREGROUND", foreground_table)
|
||||
term_out_table.set("FOREGROUND", foreground_table)
|
||||
}
|
||||
|
||||
fn foreground(&self, style_table: &Table) -> lResult<()> {
|
||||
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
|
||||
@ -56,38 +57,56 @@ impl Colors for LuauVm {
|
||||
on_blue on_magenta
|
||||
on_cyan on_white
|
||||
);
|
||||
style_table.set("BACKGROUND", background_table)
|
||||
}
|
||||
|
||||
fn styling(&self, term_out_table: &Table) -> lResult<()> {
|
||||
let style_table = self.0.create_table()?;
|
||||
self.foreground(&style_table)?;
|
||||
self.background(&style_table)?;
|
||||
term_out_table.set("STYLE", style_table)
|
||||
term_out_table.set("BACKGROUND", background_table)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
trait Write {
|
||||
fn write(&self, term_out_table: &Table) -> lResult<()>;
|
||||
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, term_out_table: &Table) -> lResult<()> {
|
||||
term_out_table.set("WRITE", self.0.create_function(|_, s: String| -> lResult<()> {
|
||||
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(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let term_table = self.0.create_table()?;
|
||||
let term_out_table = self.0.create_table()?;
|
||||
term_table.set("OUT", term_out_table)?;
|
||||
luau_globals.set("TERMINAL", &term_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)
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user