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

@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["engine", "subcrates/zephyr"]
members = ["engine", "subcrates/zephyr", "plugin_api"]
[profile.dev]
rpath = false

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#"

25
plugin_api/Cargo.toml Normal file
View file

@ -0,0 +1,25 @@
[package]
name = "plugin_api"
version = "0.3.0"
authors = ["Tristan Poland <redstonecrafter126@gmail.com>"]
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 ######

224
plugin_api/build.rs Normal file
View file

@ -0,0 +1,224 @@
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::Path;
fn main() {
// Get the path to the plugins directory
let plugins_dir = Path::new("..").join("plugins");
println!("cargo:warning=Looking for plugins in: {:?}", plugins_dir);
// Ensure the plugins directory exists
if !plugins_dir.exists() {
println!(
"cargo:warning=Plugins directory not found at {:?}",
plugins_dir
);
return;
}
// Find all valid plugin directories
let plugin_paths = discover_plugins(&plugins_dir);
println!("cargo:warning=Found {} plugins", plugin_paths.len());
// Update Cargo.toml with plugin dependencies
if let Err(e) = update_cargo_toml(&plugin_paths) {
println!("cargo:warning=Failed to update Cargo.toml: {}", e);
std::process::exit(1);
}
// Generate the plugin macro and imports files
if let Err(e) = generate_plugin_files(&plugin_paths) {
println!("cargo:warning=Failed to generate plugin files: {}", e);
std::process::exit(1);
}
// Tell Cargo to rerun this script if the plugins directory or Cargo.toml
// changes
println!("cargo:rerun-if-changed=../plugins");
println!("cargo:rerun-if-changed=Cargo.toml");
}
fn discover_plugins(plugins_dir: &Path) -> Vec<(String, String, String)> {
let mut valid_plugins = Vec::new();
if let Ok(entries) = fs::read_dir(plugins_dir) {
for entry in entries.flatten() {
let path = entry.path();
// Check if this is a directory
if !path.is_dir() {
continue;
}
let plugin_name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("")
.to_string();
// Skip if empty plugin name
if plugin_name.is_empty() {
continue;
}
// Check for required files/directories
let cargo_toml = path.join("Cargo.toml");
let src_dir = path.join("src");
let lib_rs = path.join("src").join("lib.rs");
if cargo_toml.exists() && src_dir.exists() && lib_rs.exists() {
// Read the Cargo.toml to get the package name and version
if let Ok(mut file) = File::open(&cargo_toml) {
let mut contents = String::new();
if file.read_to_string(&mut contents).is_ok() {
// Simple parsing for package name and version
let mut name = None;
let mut version = None;
for line in contents.lines() {
let line = line.trim();
if line.starts_with("name") {
name = line
.split('=')
.nth(1)
.map(|s| s.trim().trim_matches('"').to_string());
} else if line.starts_with("version") {
version = line
.split('=')
.nth(1)
.map(|s| s.trim().trim_matches('"').to_string());
}
}
if let (Some(name), Some(version)) = (name, version) {
println!(
"cargo:warning=Found plugin: {} v{} in {}",
name, version, plugin_name
);
valid_plugins.push((name, version, plugin_name));
}
}
}
}
}
}
valid_plugins
}
const AUTO_GENERATED_START: &str =
"###### BEGIN AUTO-GENERATED PLUGIN DEPENDENCIES - DO NOT EDIT THIS SECTION ######";
const AUTO_GENERATED_END: &str = "###### END AUTO-GENERATED PLUGIN DEPENDENCIES ######";
fn update_cargo_toml(plugin_paths: &[(String, String, String)]) -> std::io::Result<()> {
let cargo_path = "Cargo.toml";
let mut contents = String::new();
File::open(cargo_path)?.read_to_string(&mut contents)?;
// Normalize line endings to \n for consistent processing
contents = contents.replace("\r\n", "\n");
// Find the boundaries of the auto-generated section
let start_idx = contents.find(AUTO_GENERATED_START);
let end_idx = contents.find(AUTO_GENERATED_END);
let base_contents = match (start_idx, end_idx) {
(Some(start), Some(end)) => {
// If an existing section is found, take everything before it
contents[..start].trim_end().to_string()
}
_ => {
// If no section exists, use all current contents
contents.trim_end().to_string()
}
};
// Generate the new dependencies section
let mut new_section = String::new();
new_section.push('\n'); // Add a newline before the section
new_section.push_str(AUTO_GENERATED_START);
new_section.push('\n'); // Add newline after start marker
// Sort plugins by name for consistent output
let mut sorted_plugins = plugin_paths.to_vec();
sorted_plugins.sort_by(|a, b| a.0.cmp(&b.0));
for (name, version, plugin_dir) in sorted_plugins {
new_section.push_str(&format!(
"{} = {{ path = \"../plugins/{}\", version = \"{}\" }}\n",
name, plugin_dir, version
));
}
new_section.push_str(AUTO_GENERATED_END);
// Combine the base contents with the new section
let mut final_contents = base_contents;
final_contents.push_str(&new_section);
// Ensure file ends with a single newline
if !final_contents.ends_with('\n') {
final_contents.push('\n');
}
// Write the updated Cargo.toml
fs::write(cargo_path, final_contents)?;
Ok(())
}
fn generate_plugin_files(plugin_paths: &[(String, String, String)]) -> std::io::Result<()> {
// Create the output directory if it doesn't exist
let out_dir = Path::new("src");
fs::create_dir_all(out_dir)?;
// Then generate the imports file that uses the macro
generate_imports_file(plugin_paths, out_dir)?;
Ok(())
}
fn generate_imports_file(
plugin_paths: &[(String, String, String)],
out_dir: &Path,
) -> std::io::Result<()> {
let mut file = fs::File::create(out_dir.join("plugin_imports.rs"))?;
// Write the header
writeln!(file, "// This file is automatically generated by build.rs")?;
writeln!(file, "// Do not edit this file manually!\n")?;
writeln!(
file,
"use horizon_plugin_api::{{Pluginstate, LoadedPlugin, Plugin}};"
)?;
writeln!(file, "use std::collections::HashMap;\n")?;
for (i, (name, _, _)) in plugin_paths.iter().enumerate() {
write!(file, "pub use {};\n", name)?;
write!(file, "pub use {}::*;\n", name)?;
write!(file, "pub use {}::Plugin as {}_plugin;\n", name, name)?;
}
writeln!(file, "\n");
// Use the macro with discovered plugins
writeln!(file, "// Invoke the macro with all discovered plugins")?;
writeln!(
file,
"pub fn load_plugins() -> HashMap<String, (Pluginstate, Plugin)> {{"
)?;
write!(file, " let plugins = crate::load_plugins!(")?;
// Add each plugin to the macro invocation
for (i, (name, _, _)) in plugin_paths.iter().enumerate() {
if i > 0 {
write!(file, ",")?;
}
write!(file, "\n {}", name)?;
}
writeln!(file, "\n );")?;
writeln!(file, " plugins")?;
writeln!(file, "}}")?;
Ok(())
}

77
plugin_api/src/lib.rs Normal file
View file

@ -0,0 +1,77 @@
use std::collections::HashMap;
pub use horizon_plugin_api::{get_plugin, LoadedPlugin, Plugin, Pluginstate, Version};
pub mod plugin_imports;
// Define the current plugin version
const PLUGIN_API_VERSION: Version = Version {
major: 0,
minor: 1,
hotfix: 0,
};
#[derive(Clone)]
pub struct PluginManager {
plugins: HashMap<String, (Pluginstate, Plugin)>,
}
#[macro_export]
macro_rules! load_plugins {
($($plugin:ident),* $(,)?) => {
{
let mut plugins = HashMap::new();
$(
plugins.insert(
stringify!($plugin).to_string(),
(Pluginstate::ACTIVE, <$plugin::Plugin as $plugin::PluginConstruct>::new(plugins.clone())),
);
)*
plugins
}
};
}
impl PluginManager {
/// Allow instantiation of the ``PluginManager`` struct
pub fn new() -> PluginManager {
let new_manager = PluginManager {
plugins: HashMap::new(),
};
new_manager
}
pub fn load_plugin(mut self, name: String, plugin: Plugin) {
self.plugins.insert(name, (Pluginstate::ACTIVE, plugin));
}
pub fn unload_plugin(mut self, name: String) {
self.plugins.remove(&name);
}
pub fn get_plugins(self) -> HashMap<String, (Pluginstate, Plugin)> {
self.plugins
}
pub fn load_all(&mut self) -> HashMap<String, LoadedPlugin> {
self.plugins = plugin_imports::load_plugins();
//let my_test_plugin = get_plugin!(test_plugin, plugins);
//let result = my_test_plugin.thing();
let mut loaded_plugins = HashMap::new();
for (name, (state, plugin)) in &self.plugins {
if *state == Pluginstate::ACTIVE {
loaded_plugins.insert(
name.clone(),
LoadedPlugin {
instance: plugin.clone(),
},
);
}
}
loaded_plugins
}
}

View file

@ -0,0 +1,18 @@
// This file is automatically generated by build.rs
// Do not edit this file manually!
use horizon_plugin_api::{Pluginstate, LoadedPlugin, Plugin};
use std::collections::HashMap;
pub use player_lib;
pub use player_lib::*;
pub use player_lib::Plugin as player_lib_plugin;
// Invoke the macro with all discovered plugins
pub fn load_plugins() -> HashMap<String, (Pluginstate, Plugin)> {
let plugins = crate::load_plugins!(
player_lib
);
plugins
}

View file

@ -0,0 +1,11 @@
[package]
name = "player_lib"
version = "0.1.0"
edition = "2021"
[dependencies]
PebbleVault = "0.6.1"
horizon-plugin-api = "0.1.13"
horizon_data_types = "0.4.0"
socketioxide = "0.15.1"
parking_lot = "0.12.3"

View file

@ -0,0 +1,36 @@
use std::collections::HashMap;
pub use horizon_plugin_api::{LoadedPlugin, Plugin, Pluginstate};
// Define the trait properly
pub trait PluginAPI {
fn test(&self);
}
pub trait PluginConstruct {
fn get_structs(&self) -> Vec<&str>;
// If you want default implementations, mark them with 'default'
fn new(plugins: HashMap<String, (Pluginstate, Plugin)>) -> Plugin;
}
// Implement constructor separately
impl PluginConstruct for Plugin {
fn new(plugins: HashMap<String, (Pluginstate, Plugin)>) -> Plugin {
Plugin {}
}
fn get_structs(&self) -> Vec<&str> {
vec!["MyPlayer"]
}
}
// Implement the trait for Plugin
impl PluginAPI for Plugin {
fn test(&self) {
println!("test");
}
}
//-----------------------------------------------------------------------------
// Plugin Implementation
//-----------------------------------------------------------------------------

0
test.zensh Normal file
View file