burn everything to the ground (#11)

🔥🔥🔥🔥🔥
This commit is contained in:
Chance 2024-12-19 20:54:46 -05:00 committed by GitHub
parent 3aba3aea1c
commit 470b934fb8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 528 additions and 1088 deletions

View file

@ -1,84 +1,253 @@
use std::{ffi::OsStr, process::Command};
use std::{fs, path::PathBuf, str::FromStr};
use lazy_static::lazy_static;
use parking_lot::Mutex;
use anyhow::anyhow;
use parking_lot::RwLock;
use regex::Regex;
use super::COMMAND_LIST;
use crate::core::repl::exec::evaluate_command;
// increasing this value WILL cause a stack overflow
// attempt at your own risk - Caz
const MAX_RECURSION_DEPTH: usize = 500;
use crate::core::repl::handler::COMMAND_MANAGER;
lazy_static! {
static ref RECURSION_DEPTH: Mutex<usize> = parking_lot::Mutex::new(0);
}
use super::{handler::Command, input::tokenize};
pub(crate) fn say_hello() -> anyhow::Result<()> {
println!("Hello, World!");
Ok(())
}
#[derive(Default)]
pub struct HelpCommand;
pub(crate) fn echo(args: Vec<String>) -> anyhow::Result<()> {
println!("{}", args.join(" "));
Ok(())
}
impl Command for HelpCommand {
fn execute(&self, _args: Option<Vec<String>>) -> Result<(), anyhow::Error> {
let manager = COMMAND_MANAGER.read();
println!("Available commands:\n");
pub(crate) fn exit() -> anyhow::Result<()> {
println!("Exiting...");
std::process::exit(0)
}
for (_, command) in manager.get_commands() {
println!(
"Command: {}\n\tDescription: {}\n\tParameters: {}\n\tHelp: {}\n",
command.get_name(),
command.get_description(),
command.get_params(),
command.get_help()
);
}
pub(crate) fn clear() -> anyhow::Result<()> {
println!("Clearing screen..., running command");
let _result = if cfg!(target_os = "windows") {
Command::new("cmd").args(["/c", "cls"]).spawn()
} else {
Command::new("clear").spawn()
};
Ok(())
}
pub(crate) fn help() -> anyhow::Result<()> {
println!("Commands:");
for cmd in COMMAND_LIST.commands.read().iter() {
println!("{:#}", cmd);
if !manager.aliases.is_empty() {
println!("Aliases:");
for (alias, command) in &manager.aliases {
println!("\t{} -> {}", alias, command);
}
}
Ok(())
}
Ok(())
}
pub(crate) fn exec(args: Vec<String>) -> anyhow::Result<()> {
*RECURSION_DEPTH.lock() += 1;
if *RECURSION_DEPTH.lock() > MAX_RECURSION_DEPTH {
eprintln!("Maximum recursion depth reached. Aborting.");
*RECURSION_DEPTH.lock() = 0;
return Ok(());
}
println!("Recursion depth: {}", *RECURSION_DEPTH.lock());
let file_path_str = &args[0];
let file_path = std::path::Path::new(file_path_str);
println!("File path: {:#?}", file_path);
if !file_path.is_file() {
eprintln!(
"Error: File does not exist or is not a valid file: {}",
file_path.display()
);
return Ok(());
fn undo(&self) {}
fn redo(&self) {}
fn get_description(&self) -> String {
String::from("help")
}
if file_path.extension() != Some(OsStr::new("zensh")) {
eprintln!(
"Error: File is not a zenshell script: {:#?}",
file_path.extension()
);
//TODO: dont panic on this error
return Ok(());
fn get_help(&self) -> String {
String::from("Displays a list of available commands and their descriptions.")
}
println!("Executing file: {:#?}", file_path);
let file_content = std::fs::read_to_string(file_path)?;
if file_content.is_empty() {
eprintln!("Error: file has no content. Is this a valid zenshell script?");
return Ok(());
fn get_params(&self) -> String {
String::from("No parameters required.")
}
fn get_name(&self) -> String {
String::from("Help")
}
println!("File contents:\n{file_content}");
evaluate_command(file_content.trim())?;
Ok(())
}
#[derive(Default)]
pub struct ClearCommand;
impl Command for ClearCommand {
fn execute(&self, _args: Option<Vec<String>>) -> Result<(), anyhow::Error> {
println!("Clearing screen..., running command");
let _result = if cfg!(target_os = "windows") {
std::process::Command::new("cmd").args(["/c", "cls"]).spawn()
} else {
std::process::Command::new("clear").spawn()
};
Ok(())
}
fn undo(&self) {}
fn redo(&self) {}
fn get_description(&self) -> String {
String::from("A simple command that clears the terminal")
}
fn get_name(&self) -> String {
String::from("clear")
}
fn get_help(&self) -> String {
String::from("Clears the terminal")
}
fn get_params(&self) -> String {
String::from("None")
}
}
#[derive(Default)]
pub struct ExitCommand;
impl Command for ExitCommand {
fn execute(&self, args: Option<Vec<String>>) -> Result<(), anyhow::Error> {
match args {
Some(args) => {
let exit_code = args[0].parse()?;
std::process::exit(exit_code);
// Ok(())
},
None => {
std::process::exit(0);
},
}
}
fn undo(&self) {
todo!()
}
fn redo(&self) {
todo!()
}
fn get_description(&self) -> String {
String::from("Gracefully exists the program")
}
fn get_name(&self) -> String {
String::from("exit")
}
fn get_help(&self) -> String {
String::from("Exits, probably")
}
fn get_params(&self) -> String {
String::from("None")
}
}
#[derive(Default)]
pub struct ExecFile;
impl Command for ExecFile {
fn execute(&self, args: Option<Vec<String>>) -> Result<(),anyhow::Error> {
match args {
Some(args) => {
let file_path = PathBuf::from_str(&args[0])?;
if file_path.extension().is_some() && file_path.extension().unwrap() != "zensh" {
return Err(anyhow!("Selected file was not a zensh file"));
} else {
let zscript = fs::read_to_string(file_path)?;
if let Ok(command) = eval(zscript) {
println!("{:#?}",command);
for (cmd_name,cmd_args) in command {
COMMAND_MANAGER.read().execute(&cmd_name, cmd_args)?
}
}
}
Ok(())
},
None => {
Err(anyhow!("Not enough argumentss"))
},
}
}
fn undo(&self) {}
fn redo(&self) {}
fn get_description(&self) -> String {
String::from("Executes a file path")
}
fn get_name(&self) -> String {
String::from("exec")
}
fn get_help(&self) -> String {
String::from("this will read the contents of a .zensh file, evaluate it, and run its input")
}
fn get_params(&self) -> String {
String::from("1: File path")
}
}
fn eval(input: String) -> Result<Vec<(String,Option<Vec<String>>)>, anyhow::Error> {
if input.trim().is_empty() {
return Err(anyhow!("Input was empty"));
}
let pattern = Regex::new(r"[;|\n]").unwrap();
let commands: Vec<&str> = pattern.split(&input).collect();
let mut evaluted = vec![];
for command in commands {
let command = command.trim();
if command.is_empty() {
println!("Empty command, skipping.");
continue;
}
let tokens = tokenize(command);
if tokens.is_empty() {
println!("Empty command, skipping.");
continue;
}
let cmd_name = &tokens[0];
let args: Option<Vec<String>> = if tokens.len() > 1 {
Some(tokens[1..].iter().map(|s| s.to_string()).collect())
} else {
None
};
evaluted.push((cmd_name.to_owned(),args));
}
Ok(evaluted)
}
#[derive(Default)]
pub struct CounterCommand {
counter: RwLock<u32>,
}
impl Command for CounterCommand {
fn execute(&self, _args: Option<Vec<String>>) -> Result<(), anyhow::Error> {
// Increment the counter
let mut count = self.counter.write();
*count += 1;
println!("CounterCommand executed. Current count: {}", *count);
Ok(())
}
fn undo(&self) {
println!("Undo CounterCommand.");
}
fn redo(&self) {
println!("Redo CounterCommand.");
}
fn get_description(&self) -> String {
String::from("counter")
}
fn get_help(&self) -> String {
String::from("Increments a counter every time it's executed.")
}
fn get_params(&self) -> String {
String::from("No parameters for CounterCommand.")
}
fn get_name(&self) -> String {
String::from("count")
}
}

View file

@ -0,0 +1,151 @@
use std::collections::HashMap;
use colored::Colorize;
use lazy_static::lazy_static;
use parking_lot::RwLock;
lazy_static! {
pub static ref COMMAND_MANAGER: RwLock<CommandManager> = RwLock::new(CommandManager::init());
}
#[macro_export]
macro_rules! commands {
[$($command:ty),*] => [
$(
{
let mut manager = $crate::core::repl::handler::COMMAND_MANAGER.write();
manager.add_command(Box::new(<$command>::default()));
}
)*
];
}
#[macro_export]
macro_rules! alias {
($($alias:expr => $command:expr),*) => {
$(
{
let mut manager = $crate::COMMAND_MANAGER.write();
manager.add_alias($alias, $command);
}
)*
};
}
fn hamming_distance(a: &str, b: &str) -> Option<usize> {
if a.len() != b.len() {
return None;
}
Some(
a.chars()
.zip(b.chars())
.filter(|(char_a, char_b)| char_a != char_b)
.count(),
)
}
fn edit_distance(a: &str, b: &str) -> usize {
let m = a.len();
let n = b.len();
let mut dp = vec![vec![0; n + 1]; m + 1];
for i in 0..=m {
for j in 0..=n {
if i == 0 {
dp[i][j] = j;
} else if j == 0 {
dp[i][j] = i;
} else if a.chars().nth(i - 1) == b.chars().nth(j - 1) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + dp[i - 1][j - 1].min(dp[i - 1][j]).min(dp[i][j - 1]);
}
}
}
dp[m][n]
}
fn check_similarity(target: &str) -> Option<String> {
let max_hamming_distance: usize = 2;
let max_edit_distance: usize = 2;
let mut best_match: Option<String> = None;
let mut best_distance = usize::MAX;
for (cmd_name,_) in COMMAND_MANAGER.read().get_commands() {
if let Some(hamming_dist) = hamming_distance(target, cmd_name) {
if hamming_dist <= max_hamming_distance && hamming_dist < best_distance {
best_distance = hamming_dist;
best_match = Some(String::from(cmd_name));
}
} else {
let edit_dist = edit_distance(target, cmd_name);
if edit_dist <= max_edit_distance && edit_dist < best_distance {
best_distance = edit_dist;
best_match = Some(String::from(cmd_name));
}
}
}
best_match
}
pub struct CommandManager {
pub commands: HashMap<String, Box<dyn Command>>,
pub aliases: HashMap<String, String>,
}
impl CommandManager {
pub fn init() -> CommandManager {
CommandManager {
commands: HashMap::new(),
aliases: HashMap::new(),
}
}
pub fn get_commands(&self) -> std::collections::hash_map::Iter<'_, String, Box<dyn Command>> {
self.commands.iter()
}
pub fn execute_command(&self,command: &str,args: Option<Vec<String>>) -> Result<(),anyhow::Error> {
if let Some(command) = self.commands.get(command) {
command.execute(args)?;
Ok(())
} else {
println!("Command '{}' not found.", command);
let corrected_cmd = check_similarity(command);
if corrected_cmd.is_some() {
println!("Command: {} was not found. Did you mean {}?",command.red().bold(),corrected_cmd
.expect("A command was editied during execution, something has gone seriously wrong").green().bold().italic());
return Ok(());
}
Ok(())
}
}
pub fn execute(&self, command: &str,args: Option<Vec<String>>) -> Result<(), anyhow::Error> {
match self.aliases.get(command) {
Some(command) => self.execute(command,args),
// check to see if we are using an alias or the command just doesnt exist
None => {
self.execute_command(command,args)?;
Ok(())
},
}
}
pub fn add_command(&mut self, command: Box<dyn Command>) {
self.commands.insert(command.get_name().to_lowercase(), command);
}
pub fn add_alias(&mut self, alias: &str, command: &str) {
self.aliases.insert(alias.to_string(), command.to_string());
}
}
pub trait Command: Send + Sync {
fn execute(&self, args: Option<Vec<String>>) -> Result<(),anyhow::Error>;
fn undo(&self);
fn redo(&self);
fn get_description(&self) -> String;
fn get_name(&self) -> String;
fn get_help(&self) -> String;
fn get_params(&self) -> String;
}

View file

@ -9,15 +9,13 @@ use log::debug;
use parking_lot::Mutex;
use regex::Regex;
use rustyline::{
completion::Completer, error::ReadlineError, highlight::Highlighter, hint::HistoryHinter,
history::DefaultHistory, Cmd, Completer, ConditionalEventHandler, Editor, Event, EventContext,
EventHandler, Helper, Hinter, KeyEvent, RepeatCount, Validator,
Cmd, Completer, ConditionalEventHandler, Editor, Event, EventContext, EventHandler, Helper,
Hinter, KeyEvent, RepeatCount, Validator, completion::Completer, error::ReadlineError,
highlight::Highlighter, hint::HistoryHinter, history::DefaultHistory,
};
use crate::{
core::repl::{commands, Callable, COMMAND_LIST},
utils::logger::LOGGER,
};
use super::handler::COMMAND_MANAGER;
use crate::core::logger::LOGGER;
struct CommandCompleter;
impl CommandCompleter {
@ -35,21 +33,21 @@ impl Completer for CommandCompleter {
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
let binding = COMMAND_LIST.commands.read();
let binding = COMMAND_MANAGER.read();
let binding = binding.get_commands();
let filtered_commands: Vec<_> = binding
.iter()
.filter(|command| command.name.starts_with(line))
.filter(|(command, _)| command.starts_with(line))
.collect();
let completions: Vec<String> = filtered_commands
.iter()
.filter(|command| command.name.starts_with(&line[..pos]))
.map(|command| command.name[pos..].to_string())
.filter(|(command, _)| command.starts_with(&line[..pos]))
.map(|(command, _)| command[pos..].to_string())
.collect();
println!("{:#?}", completions);
Ok((pos, completions))
}
}
#[derive(Completer, Helper, Hinter, Validator)]
struct MyHelper {
#[rustyline(Hinter)]
@ -106,53 +104,7 @@ impl ConditionalEventHandler for BacktickEventHandler {
}
}
fn register_commands() {
COMMAND_LIST.add_command(
"hello",
Some("Displays \"Hello World\"!"),
Callable::Simple(commands::say_hello),
None,
);
COMMAND_LIST.add_command(
"exit",
Some("Exits the application gracefully."),
Callable::Simple(commands::exit),
None,
);
COMMAND_LIST.add_command(
"clear",
Some("Clears the terminal screen."),
Callable::Simple(commands::clear),
None,
);
COMMAND_LIST.add_command(
"echo",
Some("Prints the provided arguments back to the terminal."),
Callable::WithArgs(commands::echo),
Some(1), // Requires at least one argument
);
COMMAND_LIST.add_command(
"help",
Some("Displays a list of all available commands."),
Callable::Simple(commands::help),
None,
);
COMMAND_LIST.add_command(
"exec",
Some("Executes a .nyx file."),
Callable::WithArgs(commands::exec),
Some(1),
);
// Example of adding aliases for commands
COMMAND_LIST.add_alias("clear".to_string(), "cls".to_string());
}
fn tokenize(command: &str) -> Vec<String> {
pub fn tokenize(command: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current_token = String::new();
let mut inside_string = false;
@ -180,12 +132,11 @@ fn tokenize(command: &str) -> Vec<String> {
pub fn parse_command(input: &str) -> anyhow::Result<Vec<String>> {
let pattern = Regex::new(r"[;|\n]").unwrap();
let commands: Vec<String> = pattern.split(input).map(|s| String::from(s)).collect();
let commands: Vec<String> = pattern.split(input).map(String::from).collect();
Ok(commands)
}
pub fn evaluate_command(input: &str) -> anyhow::Result<()> {
if input.trim().is_empty() {
println!("Empty command, skipping. type 'help' for a list of commands.");
return Ok(());
}
@ -205,12 +156,15 @@ pub fn evaluate_command(input: &str) -> anyhow::Result<()> {
continue;
}
let cmd_name = &tokens[0];
let args: Vec<String> = tokens[1..].iter().map(|s| s.to_string()).collect();
COMMAND_LIST.execute_command(
cmd_name.to_string(),
if args.is_empty() { None } else { Some(args) },
)?;
let args: Option<Vec<String>> = if tokens.len() > 1 {
Some(tokens[1..].iter().map(|s| s.to_string()).collect())
} else {
None
};
match COMMAND_MANAGER.read().execute(cmd_name, args) {
Ok(_) => continue,
Err(e) => return Err(e)
}
}
Ok(())
}
@ -233,8 +187,6 @@ pub async fn handle_repl() -> anyhow::Result<()> {
debug!("No previous history.");
}
register_commands();
loop {
let time = Local::now().format("%H:%M:%S.%3f").to_string();
let prompt = format!("[{}/{}] {}", time, "SHELL", ">>\t");
@ -243,7 +195,10 @@ pub async fn handle_repl() -> anyhow::Result<()> {
match sig {
Ok(line) => {
rl.add_history_entry(line.as_str())?;
evaluate_command(line.as_str())?;
match evaluate_command(line.as_str()) {
Ok(_) => continue,
Err(e) => println!("{e}"),
}
}
Err(ReadlineError::Interrupted) => {
println!("CTRL+C received, exiting...");

View file

@ -1,245 +1,12 @@
use commands::{ClearCommand, CounterCommand, ExecFile, ExitCommand, HelpCommand};
use crate::commands;
pub mod commands;
pub mod exec;
pub mod input;
pub mod handler;
use std::{borrow::Borrow, collections::HashMap, sync::Arc};
use anyhow::Context;
use colored::Colorize;
use lazy_static::lazy_static;
use log::{debug, info};
use parking_lot::RwLock;
lazy_static! {
pub static ref COMMAND_LIST: Arc<CommandList> = Arc::new(CommandList::new());
}
#[derive(Clone, Debug)]
enum Callable {
Simple(fn() -> anyhow::Result<()>),
WithArgs(fn(Vec<String>) -> anyhow::Result<()>),
}
#[derive(Debug)]
pub struct Command {
pub name: &'static str,
pub description: Option<&'static str>,
function: Callable,
pub arg_count: u8,
}
#[allow(private_interfaces)]
impl Command {
pub fn new(
name: &'static str,
description: Option<&'static str>,
function: Callable,
arg_count: Option<u8>,
) -> Self {
Command {
name,
description,
function,
arg_count: arg_count.unwrap_or(0),
}
}
pub fn execute(&self, args: Option<Vec<String>>) -> anyhow::Result<()> {
match &self.function {
Callable::Simple(f) => {
if let Some(args) = args {
eprintln!(
"Command expected 0 arguments but {} args were given. Ignoring..",
args.len()
);
}
f()?;
Ok(())
}
Callable::WithArgs(f) => match args {
Some(args) => f(args),
None => Ok(()),
},
}
}
}
impl std::fmt::Display for Command {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
" {:<10} {}, {}",
self.name,
self.description.unwrap_or("No description available"),
if self.arg_count > 0 {
format!("{} args", self.arg_count)
} else {
"No args".to_string()
}
)
}
}
pub struct CommandList {
pub commands: RwLock<Vec<Command>>,
pub aliases: RwLock<HashMap<String, String>>,
}
fn hamming_distance(a: &str, b: &str) -> Option<usize> {
if a.len() != b.len() {
return None;
}
Some(
a.chars()
.zip(b.chars())
.filter(|(char_a, char_b)| char_a != char_b)
.count(),
)
}
fn edit_distance(a: &str, b: &str) -> usize {
let m = a.len();
let n = b.len();
let mut dp = vec![vec![0; n + 1]; m + 1];
for i in 0..=m {
for j in 0..=n {
if i == 0 {
dp[i][j] = j;
} else if j == 0 {
dp[i][j] = i;
} else if a.chars().nth(i - 1) == b.chars().nth(j - 1) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + dp[i - 1][j - 1].min(dp[i - 1][j]).min(dp[i][j - 1]);
}
}
}
dp[m][n]
}
fn check_similarity(target: &str, strings: &[String]) -> Option<String> {
let max_hamming_distance: usize = 2;
let max_edit_distance: usize = 2;
let mut best_match: Option<String> = None;
let mut best_distance = usize::MAX;
for s in strings {
if let Some(hamming_dist) = hamming_distance(target, s) {
if hamming_dist <= max_hamming_distance && hamming_dist < best_distance {
best_distance = hamming_dist;
best_match = Some(s.clone());
}
} else {
let edit_dist = edit_distance(target, s);
if edit_dist <= max_edit_distance && edit_dist < best_distance {
best_distance = edit_dist;
best_match = Some(s.clone());
}
}
}
best_match
}
impl CommandList {
fn new() -> Self {
CommandList {
commands: RwLock::new(Vec::new()),
aliases: RwLock::new(HashMap::new()),
}
}
fn add_command(
&self,
name: &'static str,
description: Option<&'static str>,
func: Callable,
arg_count: Option<u8>,
) {
info!("Adding command: {}", name);
let mut commands = self.commands.write();
commands.push(Command {
name,
description,
function: func,
arg_count: arg_count.unwrap_or(0),
});
}
fn add_alias(&self, name: String, alias: String) {
if self.aliases.read().contains_key(&alias) {
eprintln!("Alias: '{}' already exists", alias);
return;
}
let mut commands = self.commands.write();
if let Some(command) = commands.iter_mut().find(|cmd| cmd.name == name) {
debug!("Adding alias: {} for cmd: {}", alias, command.name);
self.aliases
.write()
.insert(alias.to_string(), name.to_string());
} else {
eprintln!("Command: '{}' was not found", name);
}
}
fn execute_command(&self, mut name: String, args: Option<Vec<String>>) -> anyhow::Result<()> {
let commands = self.commands.borrow();
if self.aliases.read().contains_key(&name) {
name = self
.aliases
.read()
.get_key_value(&name)
.context("Failed to get alias")?
.1
.to_string();
debug!("changed to {}", &name);
}
if let Some(command) = commands.read().iter().find(|cmd| cmd.name == name) {
match (command.arg_count, args.as_ref()) {
(expected, Some(args_vec)) if args_vec.len() != expected as usize => {
eprintln!(
"Command: '{}' expected {} arguments but received {}",
name,
expected,
args_vec.len()
);
Ok(())
}
(expected, None) => {
eprintln!(
"Command: '{}' expected {} arguments but received none",
name, expected
);
Ok(())
}
(_, _) => command.execute(args),
}
} else {
eprintln!("Command: '{}' was not found", name.red().italic());
let most_similar = check_similarity(
&name,
&self
.commands
.read()
.iter()
.map(|cmd| cmd.name.to_string())
.collect::<Vec<String>>(),
);
match most_similar {
Some(similar) => {
eprintln!("Did you mean: '{}'?", similar.green().italic().bold());
Ok(())
}
None => {
println!("Type 'help' for a list of commands");
Ok(())
}
}
}
}
pub fn setup() {
commands!(HelpCommand,ClearCommand,ExitCommand,ExecFile,CounterCommand);
}