Compare commits

..

No commits in common. "41c611c0ca8c043c6736a692e8f861c29339d7ca" and "d40f4bece3c11b00e78770b9b322935198eb4008" have entirely different histories.

7 changed files with 134 additions and 106 deletions

24
Cargo.lock generated
View File

@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.7.0" version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
[[package]] [[package]]
name = "bstr" name = "bstr"
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.8" version = "1.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad0cf6e91fde44c773c6ee7ec6bba798504641a8bc2eb7e37a04ffbf4dfaa55a" checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7"
dependencies = [ dependencies = [
"shlex", "shlex",
] ]
@ -351,9 +351,9 @@ checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.93" version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
@ -465,9 +465,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.96" version = "2.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -476,18 +476,18 @@ dependencies = [
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "2.0.11" version = "2.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" checksum = "a3ac7f54ca534db81081ef1c1e7f6ea8a3ef428d2fc069097c079443d24124d3"
dependencies = [ dependencies = [
"thiserror-impl", "thiserror-impl",
] ]
[[package]] [[package]]
name = "thiserror-impl" name = "thiserror-impl"
version = "2.0.11" version = "2.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" checksum = "9e9465d30713b56a37ede7185763c3492a91be2f5fa68d958c44e41ab9248beb"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",

View File

@ -1,14 +1,41 @@
use std::{io, process, str::SplitWhitespace, path::{Path, PathBuf}};
use uzers::User; use uzers::User;
use std::{
io,
process,
str::SplitWhitespace,
path::{Path, PathBuf},
};
use crate::{history::History, session::MapDisplay, valid_pbuf::IsValid}; use crate::{history::History, MapDisplay};
enum ValidStatus {
NoRootFolder,
TryExists(io::Error)
}
trait PathBufIsValid { trait PathBufIsValid {
fn is_valid(&self) -> Result<PathBuf, ValidStatus>;
fn is_valid_or_home(&self) -> Option<PathBuf>; fn is_valid_or_home(&self) -> Option<PathBuf>;
} }
impl PathBufIsValid for PathBuf { 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> { fn is_valid_or_home(&self) -> Option<PathBuf> {
self.is_valid_or(self.is_dir(), home::home_dir) 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
},
}
} }
} }
@ -87,27 +114,39 @@ impl ChangeDirectory for Command {
} }
} }
pub struct Command(String); pub struct Command {
input: String,
history: Option<History>
}
impl Command { impl Command {
pub const fn new(input: String) -> Self { pub fn new(input: String) -> Self {
Self(input) Self {
} history: History::init(),
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 exec(&mut self, history: &mut History) { pub fn write_history(&mut self) {
let mut args = self.0.split_whitespace(); if let Some(history_file) = self.history.as_mut() {
history_file.write(&self.input);
};
}
pub fn spawn_handle(&mut self, command_process: io::Result<process::Child>) {
if let Ok(mut child) = command_process {
self.write_history();
child.wait().ok();
} else {
println!("Unknown command: {}", self.input)
}
}
pub fn exec(&mut self) {
let mut args = self.input.split_whitespace();
if let Some(command) = args.next() { if let Some(command) = args.next() {
match command { match command {
"cd" => if self.change_directory(args).is_some() { history.add(self.0.as_str()) }, "cd" => { self.change_directory(args); },
command => { self.spawn_sys_cmd(history, process::Command::new(command).args(args).spawn()); } command => { self.spawn_handle(process::Command::new(command).args(args).spawn()); }
} }
} }
} }

View File

@ -1,52 +1,48 @@
use std::{fs::{File, OpenOptions}, io::{BufRead, BufReader, Write}, path::PathBuf}; use std::{fs::{File, OpenOptions}, io::{BufRead, BufReader, Write}, path::PathBuf};
use crate::{rc::{self}, session::{self, MapDisplay}, valid_pbuf::IsValid}; use crate::{rc::{self}, shell_error, valid_pbuf::IsValid, MapDisplay};
#[derive(Debug, Clone)]
pub struct History { pub struct History {
fs_history: Option<Vec<String>>, history_file: PathBuf,
history: Vec<String>, checked_empty: bool
file: Option<PathBuf>,
} }
impl History { impl History {
pub fn init() -> Self { pub fn init() -> Option<Self> {
let file = rc::config_dir().map(|mut config_dir| { rc::config_dir().map(|mut config| {
config_dir.push(".history"); config.push(".history");
config_dir.is_valid_file_or_create(b""); config.is_valid_file_or_create(b"");
config_dir Self {
}); history_file: config,
let fs_history = file.as_ref().and_then(|file| { checked_empty: false
File::open(file).map_or_display_none(|file| { }
Some(BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>()) })
}
pub fn is_empty(&mut self) -> bool {
match self.checked_empty {
true => true,
false => self.read().map_or(false, |history_l| {
self.checked_empty = true;
history_l.is_empty()
}) })
}
}
pub fn write<S: AsRef<str>>(&mut self, content: S) {
OpenOptions::new().append(true).open(self.history_file.as_path()).map_or_display(|mut file| {
let write_data = match self.is_empty() {
true => content.as_ref().to_owned(),
false => format!("\n{}", content.as_ref()),
};
if let Err(write_err) = file.write_all(write_data.as_bytes()) {
shell_error(write_err);
};
}); });
Self {
history: Vec::new(),
fs_history,
file,
}
} }
pub fn write_to_file_fallible(&mut self) { pub fn read(&self) -> Option<Vec<String>> {
if self.history.is_empty() { return; } File::open(&self.history_file).map_or_display_none(|file| {
Some(BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>())
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

@ -8,3 +8,25 @@ pub mod rc;
pub mod vm; pub mod vm;
mod valid_pbuf; mod valid_pbuf;
#[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)
}
}

View File

@ -1,40 +1,17 @@
use std::{cell::RefCell, fs, io::{self}, rc::Rc}; use std::{cell::RefCell, fs, io::{self}, rc::Rc};
use core::fmt; use core::fmt;
use color_print::ceprintln;
use crate::{ use crate::{
commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm} commands, ps::{self, Ps}, rc::{self}, shell_error, vm::{self, LuauVm}, MapDisplay
}; };
#[inline]
pub fn shell_error<E: fmt::Display>(err: E) {
ceprintln!("<bold,r>[!]:</> {err}")
}
pub trait MapDisplay<T, E: fmt::Display> {
fn map_or_display<F: FnOnce(T)>(self, f: F);
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
}
impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
///Map but display the error to stdout
#[inline]
fn map_or_display<F: FnOnce(T)>(self, f: F) {
self.map_or_else(|e| shell_error(e), f)
}
///Map but display the error to stdout and return `None`
#[inline]
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|e| { shell_error(e); None }, f)
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
pub norc: bool pub norc: bool
} }
pub struct LambdaShell { pub struct LambdaShell {
terminate: bool, terminate: bool,
history: History,
config: Config, config: Config,
vm: LuauVm, vm: LuauVm,
ps: Rc<RefCell<Ps>>, ps: Rc<RefCell<Ps>>,
@ -45,7 +22,6 @@ impl LambdaShell {
Self { Self {
ps: Rc::clone(&ps), ps: Rc::clone(&ps),
vm: vm::LuauVm::new(ps), vm: vm::LuauVm::new(ps),
history: History::init(),
terminate: false, terminate: false,
config, config,
} }
@ -55,11 +31,8 @@ impl LambdaShell {
io::Write::flush(&mut io::stdout()).map(|()| { io::Write::flush(&mut io::stdout()).map(|()| {
let mut input = String::new(); let mut input = String::new();
io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() { io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() {
"exit" => { "exit" => self.terminate = true,
self.terminate = true; trim => commands::Command::new(trim.to_owned()).exec()
self.history.add("exit");
},
trim => commands::Command::new(trim.to_owned()).exec(&mut self.history)
}) })
}) })
} }
@ -76,7 +49,6 @@ impl LambdaShell {
} }
} }
self.ps.borrow().display(); self.ps.borrow().display();
loop { loop {
if self.terminate { break } else { if self.terminate { break } else {
match self.wait() { match self.wait() {
@ -85,7 +57,6 @@ impl LambdaShell {
} }
} }
} }
self.history.write_to_file_fallible();
} }
pub fn vm_exec(&self, source: String) { pub fn vm_exec(&self, source: String) {

View File

@ -1,7 +1,7 @@
use std::{fs::{self, File}, io::{self, Write}, path::PathBuf}; use std::{fs::{self, File}, io::{self, Write}, path::PathBuf};
use thiserror::Error; use thiserror::Error;
use crate::session::MapDisplay; use crate::MapDisplay;
#[derive(Debug, Error)] #[derive(Debug, Error)]
#[allow(dead_code)] #[allow(dead_code)]

View File

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