Skip to content

Commit

Permalink
exec .zenshell files + shell extensions
Browse files Browse the repository at this point in the history
Co-authored-by: Tristan Poland (Trident_For_U) <[email protected]>
  • Loading branch information
Caznix and tristanpoland committed Dec 6, 2024
1 parent b289e3d commit 48bdd14
Show file tree
Hide file tree
Showing 16 changed files with 494 additions and 37 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["engine", "subcrates/zephyr"]
members = ["engine", "subcrates/zephyr", "plugin_api"]

[profile.dev]
rpath = false
Expand Down
3 changes: 3 additions & 0 deletions engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ 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"
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"
48 changes: 41 additions & 7 deletions engine/src/core/repl/commands.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
44 changes: 28 additions & 16 deletions engine/src/core/repl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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)]
Expand All @@ -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 {
Expand All @@ -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(())


},
},
}
}
Expand All @@ -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()
}
)
}
}
Expand All @@ -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()) {
Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand All @@ -144,6 +155,7 @@ impl CommandList {
expected,
args_vec.len()
);
Ok(())
}
(_, _) => command.execute(args),
}
Expand All @@ -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 => {}
}
}
}
Expand Down
22 changes: 15 additions & 7 deletions engine/src/core/repl/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use std::{
sync::Arc,
};

use anyhow::Result;


use chrono::Local;
use colored::Colorize;
use log::debug;
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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();
Expand All @@ -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())));

Expand All @@ -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...");
Expand Down
16 changes: 12 additions & 4 deletions engine/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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(())
}
1 change: 1 addition & 0 deletions engine/src/utils/mathi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions engine/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod logger;
pub mod mathi;
pub mod splash;
3 changes: 1 addition & 2 deletions engine/src/utils/splash.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use colored::Colorize;
use log::info;

pub fn print_splash() {
info!(
println!(
"{}",
format!(
r#"
Expand Down
25 changes: 25 additions & 0 deletions plugin_api/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]
name = "plugin_api"
version = "0.3.0"
authors = ["Tristan Poland <[email protected]>"]
description = "Horizon Plugins API"
license = "MIT"
edition = "2021"

[build-dependencies]
toml_edit = "0.22.22"
pathdiff = "0.2.3"

[dependencies]
async-trait = "0.1.83"
tokio = { version = "1.42.0", features = ["rt", "net", "rt-multi-thread"] }
uuid = "1.11.0"
socketioxide = "0.15.0"
horizon-plugin-api = "0.1.11"
#
#
#
#
###### BEGIN AUTO-GENERATED PLUGIN DEPENDENCIES - DO NOT EDIT THIS SECTION ######
player_lib = { path = "../plugins/player_lib", version = "0.1.0" }
###### END AUTO-GENERATED PLUGIN DEPENDENCIES ######
Loading

0 comments on commit 48bdd14

Please sign in to comment.