exec .zenshell files + shell extensions

Co-authored-by: Tristan Poland (Trident_For_U) <tristanpoland@users.noreply.github.com>
This commit is contained in:
Chance 2024-12-06 15:54:31 -05:00 committed by BitSyndicate
parent acf22483a8
commit 7adf770d54
16 changed files with 494 additions and 37 deletions

View file

@ -11,6 +11,7 @@ lazy_static = "1.5.0"
log = "0.4.22"
once_cell = "1.20.2"
parking_lot = "0.12.3"
rand = "0.8.5"
regex = "1.11.1"
rustyline = { version = "15.0.0", features = ["derive", "rustyline-derive"] }
thiserror = "2.0.3"
@ -18,3 +19,5 @@ tokio = { version = "1.41.1", features = ["macros", "rt", "rt-multi-thread"] }
wgpu = "23.0.1"
winit = "0.30.5"
zephyr.workspace = true
plugin_api = { path = "../plugin_api" }
horizon-plugin-api = "0.1.13"

View file

@ -1,32 +1,66 @@
use std::process::Command;
use std::{ffi::OsStr, process::Command};
use crate::core::repl::repl::evaluate_command;
use super::COMMAND_LIST;
pub(crate) fn say_hello() {
pub(crate) fn say_hello() -> anyhow::Result<()> {
println!("Hello, World!");
Ok(())
}
pub(crate) fn echo(args: Vec<String>) {
println!("{}", args.join(" "))
pub(crate) fn echo(args: Vec<String>) -> anyhow::Result<()> {
println!("{}", args.join(" "));
Ok(())
}
pub(crate) fn exit() {
pub(crate) fn exit() -> anyhow::Result<()> {
println!("Exiting...");
std::process::exit(0)
}
pub(crate) fn clear() {
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() {
pub(crate) fn help() -> anyhow::Result<()> {
println!("Commands:");
for cmd in COMMAND_LIST.commands.read().iter() {
println!("{:#}", cmd);
}
Ok(())
}
pub(crate) fn exec(args: Vec<String>) -> anyhow::Result<()> {
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(());
}
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(());
}
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(());
}
println!("File contents:\n{file_content}");
evaluate_command(file_content.trim())?;
Ok(())
}

View file

@ -3,6 +3,7 @@ pub mod repl;
use std::{borrow::Borrow, collections::HashMap, sync::Arc};
use anyhow::Ok;
use colored::Colorize;
use lazy_static::lazy_static;
use log::{debug, info};
@ -14,8 +15,8 @@ lazy_static! {
#[derive(Clone, Debug)]
enum Callable {
Simple(fn()),
WithArgs(fn(Vec<String>)),
Simple(fn() -> anyhow::Result<()>),
WithArgs(fn(Vec<String>) -> anyhow::Result<()>),
}
#[derive(Debug)]
@ -27,7 +28,7 @@ pub struct Command {
}
impl Command {
pub fn execute(&self, args: Option<Vec<String>>) {
pub fn execute(&self, args: Option<Vec<String>>) -> anyhow::Result<()> {
match &self.function {
Callable::Simple(f) => {
if let Some(args) = args {
@ -36,11 +37,16 @@ impl Command {
args.len()
);
}
f()
f()?;
Ok(())
}
Callable::WithArgs(f) => match args {
Some(args) => f(args),
None => eprintln!("Command expected arguments but received 0"),
None => {
Ok(())
},
},
}
}
@ -50,9 +56,14 @@ impl std::fmt::Display for Command {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
" {:<10} {}",
" {:<10} {}, {}",
self.name,
self.description.unwrap_or("No description available")
self.description.unwrap_or("No description available"),
if self.arg_count > 0 {
format!("{} args", self.arg_count)
} else {
"No args".to_string()
}
)
}
}
@ -64,9 +75,8 @@ pub struct CommandList {
fn check_similarity(target: &str, strings: &[String]) -> Option<String> {
strings
.iter().filter(|s| {
target.chars().zip(s.chars()).any(|(c1, c2)| c1 == c2)
})
.iter()
.filter(|s| target.chars().zip(s.chars()).any(|(c1, c2)| c1 == c2))
.min_by_key(|s| {
let mut diff_count = 0;
for (c1, c2) in target.chars().zip(s.chars()) {
@ -111,6 +121,7 @@ impl CommandList {
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);
@ -122,7 +133,7 @@ impl CommandList {
}
}
fn execute_command(&self, mut name: String, args: Option<Vec<String>>) {
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
@ -144,6 +155,7 @@ impl CommandList {
expected,
args_vec.len()
);
Ok(())
}
(_, _) => command.execute(args),
}
@ -161,12 +173,12 @@ impl CommandList {
);
match most_similar {
Some(similar) => {
eprintln!(
"Did you mean: '{}'?",
similar.green().italic().bold()
);
eprintln!("Did you mean: '{}'?", similar.green().italic().bold());
Ok(())
}
None => {
Ok(())
}
None => {}
}
}
}

View file

@ -3,7 +3,8 @@ use std::{
sync::Arc,
};
use anyhow::Result;
use chrono::Local;
use colored::Colorize;
use log::debug;
@ -106,6 +107,12 @@ fn register_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());
@ -137,10 +144,10 @@ fn tokenize(command: &str) -> Vec<String> {
tokens
}
fn evaluate_command(input: &str) {
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;
return Ok(());
}
let pattern = Regex::new(r"[;|\n]").unwrap();
@ -164,11 +171,12 @@ fn evaluate_command(input: &str) {
COMMAND_LIST.execute_command(
cmd_name.to_string(),
if args.is_empty() { None } else { Some(args) },
);
}
)?;
};
Ok(())
}
pub async fn handle_repl() -> Result<()> {
pub async fn handle_repl() -> anyhow::Result<()> {
let mut rl = Editor::<MyHelper, DefaultHistory>::new()?;
rl.set_helper(Some(MyHelper(HistoryHinter::new())));
@ -193,7 +201,7 @@ pub async fn handle_repl() -> Result<()> {
match sig {
Ok(line) => {
rl.add_history_entry(line.as_str())?;
evaluate_command(line.as_str());
evaluate_command(line.as_str())?;
}
Err(ReadlineError::Interrupted) => {
println!("CTRL+C received, exiting...");

View file

@ -2,6 +2,8 @@
use anyhow::Result;
use log::LevelFilter;
use plugin_api::plugin_imports::*;
use plugin_api::{get_plugin, PluginManager};
pub mod core;
pub mod utils;
@ -10,20 +12,26 @@ use utils::{logger::LOGGER, splash::print_splash};
#[tokio::main]
async fn main() -> Result<()> {
let t = zephyr::add(0, 2);
println!("{}", t);
// Load all plugins
log::set_logger(&*LOGGER).ok();
log::set_max_level(LevelFilter::Debug);
log::set_max_level(LevelFilter::Off);
print_splash();
let mut plugin_manager = PluginManager::new();
let plugins = plugin_manager.load_all();
println!("Plugins loaded: {:?}", plugins);
// Get the player plugin
let player_lib = get_plugin!(player_lib, plugins);
player_lib.test();
LOGGER.write_to_stdout();
let shell_thread = tokio::task::spawn(async { core::repl::repl::handle_repl().await });
core::init_renderer()?;
let _ = shell_thread.await?;
let _ = shell_thread.await??;
Ok(())
}

View file

@ -0,0 +1 @@

View file

@ -1,2 +1,3 @@
pub mod logger;
pub mod mathi;
pub mod splash;

View file

@ -1,8 +1,7 @@
use colored::Colorize;
use log::info;
pub fn print_splash() {
info!(
println!(
"{}",
format!(
r#"