more builtin refactoring

main
Jordan Orelli 11 months ago
parent 9c7d64e512
commit 678b5f7932

@ -1,5 +1,6 @@
mod echo;
mod printenv;
mod which;
use crate::{
error::ExecError,
@ -11,6 +12,7 @@ use std::collections::HashMap;
pub enum Builtin {
Echo,
Printenv,
Which,
}
impl Builtin {
@ -19,6 +21,7 @@ impl Builtin {
match self {
Echo => &echo::Echo,
Printenv => &printenv::Printenv,
Which => &which::Which,
}
}
}
@ -31,5 +34,5 @@ impl Call for Builtin {
pub fn all() -> HashMap<&'static str, Builtin> {
use Builtin::*;
HashMap::from([("echo", Echo), ("printenv", Printenv)])
HashMap::from([("echo", Echo), ("printenv", Printenv), ("which", Which)])
}

@ -0,0 +1,26 @@
use crate::{
error::ExecError,
run::{Call, Context, Value},
};
use std::{env, io::Write};
pub struct Which;
impl Call for Which {
fn call(&self, ctx: &mut Context, args: &[Value]) -> Result<Value, ExecError> {
let path = env::var("path").unwrap_or_default();
let dirs: Vec<&str> = path.split(";").collect();
for arg in args {
let name = arg.try_as_str()?;
for d in dirs.iter() {
let dir = std::path::Path::new(d);
let fname = dir.join(name).with_extension("exe");
if fname.exists() && fname.is_file() {
_ = writeln!(ctx.stdout, "{}", fname.to_str().unwrap());
}
}
}
Ok(Value::None)
}
}

@ -1,10 +1,8 @@
mod command;
mod tail;
mod which;
pub use command::Command;
pub use tail::Tail;
pub use which::Which;
/*
Posix Shell builtins:

@ -1,34 +0,0 @@
use crate::ext::Command;
use anyhow::Result;
pub struct Which {}
impl Command for Which {
fn name() -> String {
String::from("which")
}
fn create() -> Self {
Self {}
}
fn exec(&mut self, args: Vec<&str>) -> Result<bool> {
if args.len() > 0 {
let path = std::env::var("path").unwrap();
let dirs: Vec<&str> = path.split(";").collect();
for d in dirs {
let dir = std::path::Path::new(d);
let fname = dir.join(args[0]).with_extension("exe");
if fname.exists() && fname.is_file() {
println!("{}", fname.to_str().unwrap());
return Ok(true);
}
}
println!("not found: {}", args[0]);
Ok(false)
} else {
println!("what do you want to look for?");
Ok(false)
}
}
}

@ -50,6 +50,7 @@ impl Eval for Value {
pub struct State {
#[allow(unused)]
variables: HashMap<&'static str, Value>,
pub(crate) builtins: HashMap<&'static str, builtin::Builtin>,
}

Loading…
Cancel
Save