Compare commits

...

5 Commits

8 changed files with 195 additions and 162 deletions

24
Cargo.lock generated
View File

@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "bitflags"
version = "2.6.0"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be"
[[package]]
name = "bstr"
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]]
name = "cc"
version = "1.2.7"
version = "1.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7"
checksum = "ad0cf6e91fde44c773c6ee7ec6bba798504641a8bc2eb7e37a04ffbf4dfaa55a"
dependencies = [
"shlex",
]
@ -351,9 +351,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",
]
@ -465,9 +465,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 +476,18 @@ dependencies = [
[[package]]
name = "thiserror"
version = "2.0.10"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3ac7f54ca534db81081ef1c1e7f6ea8a3ef428d2fc069097c079443d24124d3"
checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.10"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9465d30713b56a37ede7185763c3492a91be2f5fa68d958c44e41ab9248beb"
checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2"
dependencies = [
"proc-macro2",
"quote",

View File

@ -1,22 +1,16 @@
use std::{io, process, str::SplitWhitespace, path::{Path, PathBuf}};
use uzers::User;
use std::{
io,
process,
str::SplitWhitespace,
path::{Path, PathBuf},
};
use crate::MapDisplay;
enum ValidStatus {
NoRootFolder,
TryExists(io::Error)
}
use crate::{history::History, session::MapDisplay, valid_pbuf::IsValid};
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>;
@ -26,30 +20,6 @@ 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()))
@ -119,24 +89,25 @@ impl ChangeDirectory for Command {
pub struct Command(String);
impl Command {
pub fn new(input: String) -> Self {
pub const 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 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 exec(&self) {
pub fn exec(&mut self, history: &mut History) {
let mut args = self.0.split_whitespace();
if let Some(command) = args.next() {
match command {
"cd" => {
self.change_directory(args);
},
command => {
self.spawn(process::Command::new(command).args(args).spawn());
}
"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()); }
}
}
}

52
src/history.rs Normal file
View 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 {
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()),
};
}
}

View File

@ -2,28 +2,9 @@ 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;
#[inline]
pub fn shell_error<E: core::fmt::Display>(err: E) {
color_print::ceprintln!("<bold,r>[!]:</> {err}")
}
pub trait MapDisplay<T, E: core::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: core::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)
}
}
mod valid_pbuf;

View File

@ -1,7 +1,6 @@
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
@ -15,72 +14,6 @@ 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");
@ -94,10 +27,3 @@ pub fn config_file() -> Option<PathBuf> {
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"")
}

View File

@ -1,17 +1,40 @@
use std::{cell::RefCell, fs, io::{self}, rc::Rc};
use core::fmt;
use color_print::ceprintln;
use crate::{
commands, ps::{self, Ps}, rc, shell_error, vm::{self, LuauVm}, MapDisplay
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>>,
@ -22,6 +45,7 @@ impl LambdaShell {
Self {
ps: Rc::clone(&ps),
vm: vm::LuauVm::new(ps),
history: History::init(),
terminate: false,
config,
}
@ -31,8 +55,11 @@ impl LambdaShell {
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,
trim => commands::Command::new(trim.to_owned()).exec()
"exit" => {
self.terminate = true;
self.history.add("exit");
},
trim => commands::Command::new(trim.to_owned()).exec(&mut self.history)
})
})
}
@ -48,8 +75,8 @@ impl LambdaShell {
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() {
@ -58,6 +85,7 @@ impl LambdaShell {
}
}
}
self.history.write_to_file_fallible();
}
pub fn vm_exec(&self, source: String) {

75
src/valid_pbuf.rs Normal file
View File

@ -0,0 +1,75 @@
use std::{fs::{self, File}, io::{self, Write}, path::PathBuf};
use thiserror::Error;
use crate::session::MapDisplay;
#[derive(Debug, Error)]
#[allow(dead_code)]
pub enum IsValidDirErr {
#[error("Failed to see if a file exists: {0}")]
TryExists(#[from] io::Error),
#[error("Not a valid entry")]
NotAnEntry,
#[error("Directory missing")]
Missing
}
#[allow(dead_code)]
enum CreateErr {
TryExists(io::Error),
Passable
}
#[allow(dead_code)]
pub trait IsValid {
fn is_valid(&self, is_dir_or_file: bool) -> Result<PathBuf, IsValidDirErr>;
fn is_valid_option(&self, is_dir_or_file: bool) -> Option<PathBuf>;
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf>;
fn is_valid_dir_or_create(&self) -> Option<PathBuf>;
fn is_valid_or<F>(&self, is_content: bool, f: F) -> Option<PathBuf>
where
F: FnOnce() -> Option<PathBuf>;
}
impl IsValid for PathBuf {
#[inline]
fn is_valid(&self, is_content: bool) -> Result<PathBuf, IsValidDirErr> {
match self.try_exists() {
Ok(true) => if is_content { Ok(self.to_path_buf()) } else { Err(IsValidDirErr::NotAnEntry) },
Ok(false) => Err(IsValidDirErr::Missing),
Err(try_e) => Err(IsValidDirErr::TryExists(try_e))
}
}
#[inline]
fn is_valid_or<F>(&self, is_content: bool, f: F) -> Option<PathBuf>
where
F: FnOnce() -> Option<PathBuf>
{
self.is_valid(is_content).map_err(|e| match e {
IsValidDirErr::TryExists(try_e) => CreateErr::TryExists(try_e),
IsValidDirErr::NotAnEntry | IsValidDirErr::Missing => CreateErr::Passable
}).map_or_else(|e| match e {
CreateErr::TryExists(_) => None,
CreateErr::Passable => f()
}, Some)
}
#[inline]
fn is_valid_dir_or_create(&self) -> Option<PathBuf> {
self.is_valid_or(self.is_dir(), || fs::create_dir(self).map_or_display_none(|()| Some(self.to_path_buf())))
}
#[inline]
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf> {
self.is_valid_or(self.is_file(), || {
File::create(self).map_or_display_none(|mut file| {
file.write_all(default_file_bytes).map_or_display_none(|()| Some(self.to_path_buf()))
})
})
}
#[inline]
fn is_valid_option(&self, is_dir_or_file: bool) -> Option<PathBuf> {
self.is_valid(is_dir_or_file).ok()
}
}

View File

@ -5,7 +5,7 @@ use std::{cell::RefCell, rc::Rc};
use core::fmt;
use shell::ShellGlobal;
use crate::{ps::Ps, MapDisplay};
use crate::{ps::Ps, session::MapDisplay};
mod shell;
mod terminal;