This commit is contained in:
2024-12-07 17:33:39 -05:00
commit b87bb4d85f
7 changed files with 842 additions and 0 deletions

162
src/commands.rs Normal file
View File

@ -0,0 +1,162 @@
use uzers::User;
use std::{
io,
process,
str::SplitWhitespace,
path::{Path, PathBuf},
};
enum ValidStatus {
NoRootFolder,
TryExists(io::Error)
}
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(root_folder_exist) => match root_folder_exist {
true => Ok(self.to_path_buf()),
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> {
match std::env::set_current_dir(new_path) {
Ok(()) => Some(new_path.to_path_buf()),
Err(set_cd_err) => {
println!("{set_cd_err}");
None
},
}
}
fn home_dir(&self) -> Option<PathBuf> {
match home::home_dir() {
Some(home_path_buf) => self.set_current_dir(&home_path_buf),
None => self.set_current_dir(Path::new("/")),
}
}
fn previous_dir(&self) -> Option<PathBuf> {
unimplemented!()
}
fn specific_user_dir(&self, requested_user: String) -> Option<PathBuf> {
match requested_user.as_str() {
"root" => PathBuf::from("/root").is_valid_or_home(),
_ => {
for user in unsafe { uzers::all_users().collect::<Vec<User>>() } {
let user_name = user.name();
if *requested_user == *user_name {
let mut user_dir = PathBuf::from("/home");
user_dir.push(user_name);
return user_dir.is_valid_or_home();
}
}
None
}
}
}
fn cd_args(&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),
false => {
match new_path.file_name() {
Some(file_name) => println!("cd: {:?} is not a directory.", file_name),
None => println!("cd: Failed to resolve the file name of a file that is not a directory."),
}
None
}
}
}
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf> {
let vec_args: Vec<String> = args.map(|arg| arg.to_string()).collect();
match vec_args.first() {
Some(arg) => match arg.as_str() {
"/" => self.set_current_dir(Path::new("/")),
"-" => self.previous_dir(),
_ => {
let mut arg_chars = arg.chars();
match arg_chars.next() {
Some(char) => match char == '~' {
true => self.specific_user_dir(arg_chars.collect::<String>()),
false => self.cd_args(vec_args),
},
None => self.home_dir(),
}
}
},
None => self.home_dir(),
}
}
}
pub type ProcessExitStatus = Option<process::ExitStatus>;
pub struct Command(String);
impl Command {
pub fn new(input: String) -> Self {
Self(input)
}
pub fn spawn(&self, command_process: io::Result<process::Child>) -> ProcessExitStatus {
match command_process {
Ok(mut child) => Some(match child.wait() {
Ok(exit_status) => exit_status,
Err(exit_status_err) => {
println!("{exit_status_err}");
return None;
}
}),
Err(e) => {
println!("{e}");
return None;
}
}
}
pub fn exec(&self) -> ProcessExitStatus {
let mut args = self.0.split_whitespace();
args.next().and_then(|command| match command {
"cd" => {
Self::change_directory(self, args);
None
}
command => self.spawn(process::Command::new(command).args(args).spawn()),
})
}
}

6
src/lib.rs Normal file
View File

@ -0,0 +1,6 @@
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub mod shell;
mod commands;
mod ps;
mod rc;

26
src/ps.rs Normal file
View File

@ -0,0 +1,26 @@
use const_format::formatcp;
use color_print::{cformat, cprint};
pub const DEFAULT_PS: &str = formatcp!("lambdashell-{}", env!("CARGO_PKG_VERSION"));
pub fn working_dir_name() -> String {
match std::env::current_dir() {
Ok(pathbuf) => match pathbuf.file_name() {
Some(name) => {
let name_os_string = name.to_os_string();
match name_os_string == whoami::username_os() && name_os_string != "root" {
true => "~".to_string(),
false => name.to_string_lossy().to_string(),
}
}
None => "?".to_string(),
},
Err(_) => "?".to_string(),
}
}
pub fn display(ps1: &String) {
// let exit_status = shell_storage.command_exit_status.map(|s| format!(" [{s}] ")).unwrap_or(" ".to_string());
let working_dir_name = cformat!(" <bold>{}</> ", working_dir_name());
cprint!("{}{}λ ", ps1, working_dir_name);
}

44
src/rc.rs Normal file
View File

@ -0,0 +1,44 @@
use std::{io, path::PathBuf};
pub enum RcError {
FolderMissing,
FolderTryExists(io::Error)
}
trait is_valid {
fn is_valid(&self) -> Option<PathBuf>;
}
impl is_valid for PathBuf {
fn is_valid(&self) -> Option<PathBuf> {
let try_exists = match self.try_exists() {
Ok(config_exist) => match config_exist {
true => Ok(self.to_path_buf()),
false => Err(RcError::FolderMissing),
},
Err(trye_error) => Err(RcError::FolderTryExists(trye_error)),
};
match try_exists {
Ok(file) => Some(file.to_path_buf()),
Err(rc_error) => match rc_error {
RcError::FolderMissing => todo!(),
RcError::FolderTryExists(error) => {
println!("{error}");
None
},
},
}
}
}
fn dot_config_folder() -> Option<PathBuf> {
let mut config = home::home_dir()?;
config.push(".config");
config.is_valid()
}
fn rc_folder() -> Option<PathBuf> {
let mut dot_config = dot_config_folder()?;
dot_config.push("lambdashell");
dot_config.is_valid()
}

75
src/shell.rs Normal file
View File

@ -0,0 +1,75 @@
use crate::{ps, commands};
use std::io;
pub struct Config {
pub norc: bool
}
pub struct LambdaShell {
terminating: bool,
storage: Storage,
config: Config,
}
struct Storage {
pub command_exit_status: commands::ProcessExitStatus,
pub ps1: String,
}
impl LambdaShell {
pub fn create(config: Config) -> Self {
Self {
storage: Storage {
command_exit_status: None,
ps1: ps::DEFAULT_PS.to_string(),
},
terminating: false,
config,
}
}
fn input(&mut self) {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_size) => {
let trimmed_input = input.trim();
match trimmed_input {
//special casey
"exit" => self.terminating = true,
_ => self.storage.command_exit_status = commands::Command::new(trimmed_input.to_string()).exec()
};
}
Err(read_error) => println!("{read_error}"),
};
}
pub fn wait(&mut self) -> Result<(), io::Error> {
match io::Write::flush(&mut io::stdout()) {
Ok(()) => {
self.input();
Ok(())
}
Err(flush_error) => {
println!("{flush_error}");
Err(flush_error)
}
}
}
pub fn start(&mut self) {
ps::display(&self.storage.ps1);
loop {
match self.terminating {
true => break,
false => match self.wait() {
Ok(()) => ps::display(&self.storage.ps1),
Err(flush_error) => {
println!("{flush_error}");
break;
}
},
}
}
}
}