From c7d962f25002527997aa10f3f7bc266ec3d319dc Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 24 Jul 2022 17:55:28 +0800 Subject: [PATCH 01/48] fix: ignore `.DS_Store` --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6b39d31a9..f01f6dacf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ /target -.idea/ \ No newline at end of file +.idea/ + +.DS_Store \ No newline at end of file From 09311ff1327369eb5d7f60120dce810e50d84d0b Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 24 Jul 2022 19:00:43 +0800 Subject: [PATCH 02/48] feat: add `plugin` mod --- Cargo.lock | 50 +++++++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 2 ++ src/lib.rs | 1 + src/plugin/mod.rs | 0 4 files changed, 53 insertions(+) create mode 100644 src/plugin/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 4a1840d06..4f7ee9f05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -234,6 +234,15 @@ dependencies = [ "byte-tools", ] +[[package]] +name = "bstr" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +dependencies = [ + "memchr", +] + [[package]] name = "bumpalo" version = "3.10.0" @@ -639,6 +648,7 @@ dependencies = [ "hyper", "indicatif", "log", + "mlua", "notify", "proc-macro2", "regex", @@ -1522,6 +1532,24 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "lua-src" +version = "544.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708ba3c844d5e9d38def4a09dd871c17c370f519b3c4b7261fbabe4a613a814c" +dependencies = [ + "cc", +] + +[[package]] +name = "luajit-src" +version = "210.4.0+resty124ff8d" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f76fb2e2c0c7192e18719d321c9a148f7625c4dcbe3df5f4c19e685e4c286f6c" +dependencies = [ + "cc", +] + [[package]] name = "maplit" version = "1.0.2" @@ -1589,6 +1617,22 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "mlua" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a82d0b12c7c8d3bdda5933d2aa322c76e4833d822796495f299990ca652bd1bf" +dependencies = [ + "bstr", + "cc", + "lua-src", + "luajit-src", + "num-traits", + "once_cell", + "pkg-config", + "rustc-hash", +] + [[package]] name = "native-tls" version = "0.2.10" @@ -2115,6 +2159,12 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + [[package]] name = "rustls" version = "0.20.6" diff --git a/Cargo.toml b/Cargo.toml index d0c0cb44c..31ac60386 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,6 +59,8 @@ dioxus-rsx-interpreter = { git = "https://github.com/dioxuslabs/dioxus/" } proc-macro2 = { version = "1.0", features = ["span-locations"] } +# plugin packages +mlua = { version = "0.8.1", features = ["lua54", "vendored"] } [[bin]] path = "src/main.rs" diff --git a/src/lib.rs b/src/lib.rs index 1b651acee..e01786047 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,3 +22,4 @@ pub mod logging; pub use logging::*; pub mod hot_reload; +pub mod plugin; \ No newline at end of file diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs new file mode 100644 index 000000000..e69de29bb From ca8855b168ffe0d4768c64960ef72eac6f2a5512 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 24 Jul 2022 19:04:13 +0800 Subject: [PATCH 03/48] feat: move `hot_reload` code --- src/{hot_reload/mod.rs => hot_reload.rs} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/{hot_reload/mod.rs => hot_reload.rs} (99%) diff --git a/src/hot_reload/mod.rs b/src/hot_reload.rs similarity index 99% rename from src/hot_reload/mod.rs rename to src/hot_reload.rs index 3aced9567..84bb415ed 100644 --- a/src/hot_reload/mod.rs +++ b/src/hot_reload.rs @@ -610,4 +610,4 @@ fn find_rsx_expr( (syn::Expr::Verbatim(_), syn::Expr::Verbatim(_)) => false, _ => true, } -} +} \ No newline at end of file From bd2853a1945f561441820f61e5d656ba65ebddcc Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Mon, 25 Jul 2022 08:10:06 +0800 Subject: [PATCH 04/48] feat: commit lua code --- .vscode/settings.json | 6 +++- examples/plugin/init.lua | 14 +++++++++ examples/plugin/interface.lua | 25 +++++++++++++++++ src/assets/dioxus.toml | 23 ++------------- src/config.rs | 23 +++++---------- src/plugin/log.rs | 28 ++++++++++++++++++ src/plugin/mod.rs | 53 +++++++++++++++++++++++++++++++++++ 7 files changed, 135 insertions(+), 37 deletions(-) create mode 100644 examples/plugin/init.lua create mode 100644 examples/plugin/interface.lua create mode 100644 src/plugin/log.rs diff --git a/.vscode/settings.json b/.vscode/settings.json index 0967ef424..e56c13485 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1 +1,5 @@ -{} +{ + "Lua.diagnostics.globals": [ + "plugin_logger" + ] +} diff --git a/examples/plugin/init.lua b/examples/plugin/init.lua new file mode 100644 index 000000000..d7afea665 --- /dev/null +++ b/examples/plugin/init.lua @@ -0,0 +1,14 @@ +local api = require("interface") +local log = api.log; + +Manager = {} + +Manager.info = { + name = "Dioxus-CLI Plugin Demo", + repository = "http://github.com/DioxusLabs/cli", + author = "YuKun Liu ", +} + +Manager.onbuild = function () + print("") +end \ No newline at end of file diff --git a/examples/plugin/interface.lua b/examples/plugin/interface.lua new file mode 100644 index 000000000..bc6c91cb1 --- /dev/null +++ b/examples/plugin/interface.lua @@ -0,0 +1,25 @@ +local interface = {} + +if plugin_logger ~= nil then + interface.log = plugin_logger +else + interface.log = { + trace = function (info) + print("trace: " .. info) + end, + debug = function (info) + print("debug: " .. info) + end, + info = function (info) + print("info: " .. info) + end, + warn = function (info) + print("warn: " .. info) + end, + error = function (info) + print("error: " .. info) + end, + } +end + +return interface \ No newline at end of file diff --git a/src/assets/dioxus.toml b/src/assets/dioxus.toml index 649aa2c3c..42a1bd3f1 100644 --- a/src/assets/dioxus.toml +++ b/src/assets/dioxus.toml @@ -40,25 +40,8 @@ script = [] # serve: [dev-server] only script = [] -[application.tools] +[application.plugins] -# use binaryen.wasm-opt for output Wasm file -# binaryen just will trigger in `web` platform -binaryen = { wasm_opt = true } +available = true -# use sass auto will auto check sass file and build it. - - -# [application.tools.sass] - -# auto will check the assets dirs, and auto to transform all scss file to css file. -# input = "*" - -# or you can specify some scss file -> css file -# input = [ -# # some sass file path -# # this file will translate to `/css/test.css` -# "/css/test.scss" -# ] - -# source_map = true \ No newline at end of file +required = [] \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 3952f973e..3d6fe65a4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,4 @@ -use crate::error::Result; +use crate::{error::Result, plugin::PluginConfig}; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, fs::File, io::Read, path::PathBuf}; @@ -34,7 +34,10 @@ impl Default for DioxusConfig { default_platform: "web".to_string(), out_dir: Some(PathBuf::from("dist")), asset_dir: Some(PathBuf::from("public")), + tools: None, + plugins: None, + sub_package: None, }, web: WebConfig { @@ -66,7 +69,10 @@ pub struct ApplicationConfig { pub default_platform: String, pub out_dir: Option, pub asset_dir: Option, + pub tools: Option>, + pub plugins: Option, + pub sub_package: Option, } @@ -218,19 +224,4 @@ impl CrateConfig { self } - // pub fn with_build_options(&mut self, options: &BuildOptions) { - // if let Some(name) = &options.example { - // self.as_example(name.clone()); - // } - // self.release = options.release; - // self.out_dir = options.outdir.clone().into(); - // } - - // pub fn with_develop_options(&mut self, options: &DevelopOptions) { - // if let Some(name) = &options.example { - // self.as_example(name.clone()); - // } - // self.release = options.release; - // self.out_dir = tempfile::Builder::new().tempdir().expect("").into_path(); - // } } diff --git a/src/plugin/log.rs b/src/plugin/log.rs new file mode 100644 index 000000000..d67ae0316 --- /dev/null +++ b/src/plugin/log.rs @@ -0,0 +1,28 @@ +use log; +use mlua::UserData; + +pub struct PluginLogger; +impl UserData for PluginLogger { + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_function("trace", |_, info: String| { + log::trace!("{}", info); + Ok(()) + }); + methods.add_function("info", |_, info: String| { + log::info!("{}", info); + Ok(()) + }); + methods.add_function("debug", |_, info: String| { + log::debug!("{}", info); + Ok(()) + }); + methods.add_function("warn", |_, info: String| { + log::warn!("{}", info); + Ok(()) + }); + methods.add_function("error", |_, info: String| { + log::error!("{}", info); + Ok(()) + }); + } +} \ No newline at end of file diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index e69de29bb..44a08cd74 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -0,0 +1,53 @@ +use std::{fs::create_dir_all, path::PathBuf}; + +use anyhow::Ok; +use mlua::Lua; +use serde::{Deserialize, Serialize}; +use walkdir::WalkDir; + +use crate::tools::app_path; + +pub mod log; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginConfig { + available: bool, + required: Vec, +} + +pub struct PluginManager { + lua: Lua, +} + +impl PluginManager { + pub fn init(config: &PluginConfig) -> Option { + if config.available { + return None; + } + + let lua = Lua::new(); + + let manager = lua.create_table().ok()?; + + let plugin_dir = Self::init_plugin_dir(); + for entry in WalkDir::new(plugin_dir).into_iter().filter_map(|e| e.ok()) { + let plugin_dir = entry.path().to_path_buf(); + if plugin_dir.is_dir() { + + } + } + + lua.globals().set("manager", manager).ok()?; + + Some(Self { lua }) + } + + fn init_plugin_dir() -> PathBuf { + let app_path = app_path(); + let plugin_path = app_path.join("plugins"); + if !plugin_path.is_dir() { + create_dir_all(&plugin_path).unwrap(); + } + plugin_path + } +} From d5afbefddbcb13a47aed5393939807769a714a0a Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Mon, 25 Jul 2022 13:53:45 +0800 Subject: [PATCH 05/48] feat: commit code --- examples/README.md | 0 examples/plugin/init.lua | 20 +++++++++------ src/plugin/interface.rs | 54 ++++++++++++++++++++++++++++++++++++++++ src/plugin/mod.rs | 20 ++++++++++++--- 4 files changed, 83 insertions(+), 11 deletions(-) create mode 100644 examples/README.md create mode 100644 src/plugin/interface.rs diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/examples/plugin/init.lua b/examples/plugin/init.lua index d7afea665..564a8ba94 100644 --- a/examples/plugin/init.lua +++ b/examples/plugin/init.lua @@ -1,14 +1,18 @@ -local api = require("interface") -local log = api.log; +local Api = require("interface") +local log = Api.log; -Manager = {} - -Manager.info = { +local manager = { name = "Dioxus-CLI Plugin Demo", repository = "http://github.com/DioxusLabs/cli", author = "YuKun Liu ", } -Manager.onbuild = function () - print("") -end \ No newline at end of file +manager.onLoad = function () + log.info("plugin loaded.") +end + +manager.onStartBuild = function () + log.warn("system start to build") +end + +return manager \ No newline at end of file diff --git a/src/plugin/interface.rs b/src/plugin/interface.rs new file mode 100644 index 000000000..ac2005319 --- /dev/null +++ b/src/plugin/interface.rs @@ -0,0 +1,54 @@ +use mlua::{FromLua, Function}; + +pub struct PluginInfo<'lua> { + name: String, + repository: String, + author: String, + + on_init: Option>, + on_load: Option>, + on_build_start: Option>, + on_build_end: Option>, +} + +impl<'lua> FromLua<'lua> for PluginInfo<'lua> { + fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { + let mut res = Self { + name: String::default(), + repository: String::default(), + author: String::default(), + + on_init: None, + on_load: None, + on_build_start: None, + on_build_end: None, + }; + if let mlua::Value::Table(tab) = lua_value { + if let Ok(v) = tab.get::<_, String>("name") { + res.name = v; + } + if let Ok(v) = tab.get::<_, String>("repository") { + res.repository = v; + } + if let Ok(v) = tab.get::<_, String>("author") { + res.author = v; + } + + if let Ok(v) = tab.get::<_, Function>("onInit") { + res.on_init = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("onLoad") { + res.on_load = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("onBuildStart") { + res.on_build_start = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("onBuildEnd") { + res.on_build_end = Some(v); + } + + } + + Ok(res) + } +} diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 44a08cd74..da312aa00 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -1,14 +1,17 @@ -use std::{fs::create_dir_all, path::PathBuf}; +use std::{fs::create_dir_all, path::PathBuf, io::Read}; -use anyhow::Ok; use mlua::Lua; use serde::{Deserialize, Serialize}; use walkdir::WalkDir; use crate::tools::app_path; +use self::{log::PluginLogger, interface::PluginInfo}; + pub mod log; +mod interface; + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PluginConfig { available: bool, @@ -29,11 +32,22 @@ impl PluginManager { let manager = lua.create_table().ok()?; + lua.globals().set("plugin_logger", PluginLogger).unwrap(); + let plugin_dir = Self::init_plugin_dir(); + let mut index = 0; for entry in WalkDir::new(plugin_dir).into_iter().filter_map(|e| e.ok()) { let plugin_dir = entry.path().to_path_buf(); if plugin_dir.is_dir() { - + let init_file = plugin_dir.join("init.lua"); + if init_file.is_file() { + let mut file = std::fs::File::open(init_file).unwrap(); + let mut buffer = String::new(); + file.read_to_string(&mut buffer).unwrap(); + let info = lua.load(&buffer).eval::().unwrap(); + let _ = manager.set(index, info); + } + index += 1; } } From ded8f862792b82bc60e117ae817075cacb9c73e8 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 26 Jul 2022 14:25:59 +0800 Subject: [PATCH 06/48] feat: commit code --- examples/plugin/init.lua | 2 +- src/main.rs | 9 +++++++- src/plugin/interface.rs | 2 +- src/plugin/{log.rs => logger.rs} | 0 src/plugin/mod.rs | 39 +++++++++++++++++++++++--------- src/tools.rs | 38 +++++++++++++++++-------------- 6 files changed, 59 insertions(+), 31 deletions(-) rename src/plugin/{log.rs => logger.rs} (100%) diff --git a/examples/plugin/init.lua b/examples/plugin/init.lua index 564a8ba94..7d6b710ef 100644 --- a/examples/plugin/init.lua +++ b/examples/plugin/init.lua @@ -1,4 +1,4 @@ -local Api = require("interface") +local Api = require("./interface") local log = Api.log; local manager = { diff --git a/src/main.rs b/src/main.rs index 39b360f7d..bc36e1071 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,18 @@ use clap::Parser; -use dioxus_cli::*; +use dioxus_cli::{*, plugin::{PluginManager, PluginConfig}}; #[tokio::main] async fn main() -> Result<()> { let args = Cli::parse(); set_up_logging(); + let plugin_manager = PluginManager::init(&PluginConfig { + available: true, + required: vec![], + }).unwrap(); + + plugin_manager.load_all_plugins().unwrap(); + match args.action { Commands::Translate(opts) => { if let Err(e) = opts.translate() { diff --git a/src/plugin/interface.rs b/src/plugin/interface.rs index ac2005319..399b6919f 100644 --- a/src/plugin/interface.rs +++ b/src/plugin/interface.rs @@ -1,7 +1,7 @@ use mlua::{FromLua, Function}; pub struct PluginInfo<'lua> { - name: String, + pub name: String, repository: String, author: String, diff --git a/src/plugin/log.rs b/src/plugin/logger.rs similarity index 100% rename from src/plugin/log.rs rename to src/plugin/logger.rs diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index da312aa00..c69fb620b 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -1,21 +1,21 @@ -use std::{fs::create_dir_all, path::PathBuf, io::Read}; +use std::{fs::create_dir_all, io::Read, path::PathBuf}; -use mlua::Lua; +use mlua::{Lua, Table}; use serde::{Deserialize, Serialize}; use walkdir::WalkDir; -use crate::tools::app_path; +use crate::tools::{app_path, clone_repo}; -use self::{log::PluginLogger, interface::PluginInfo}; +use self::{interface::PluginInfo, logger::PluginLogger}; -pub mod log; +pub mod logger; mod interface; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PluginConfig { - available: bool, - required: Vec, + pub available: bool, + pub required: Vec, } pub struct PluginManager { @@ -24,18 +24,19 @@ pub struct PluginManager { impl PluginManager { pub fn init(config: &PluginConfig) -> Option { - if config.available { + if !config.available { return None; } let lua = Lua::new(); - let manager = lua.create_table().ok()?; + let manager = lua.create_table().unwrap(); lua.globals().set("plugin_logger", PluginLogger).unwrap(); let plugin_dir = Self::init_plugin_dir(); let mut index = 0; + println!("{plugin_dir:?}"); for entry in WalkDir::new(plugin_dir).into_iter().filter_map(|e| e.ok()) { let plugin_dir = entry.path().to_path_buf(); if plugin_dir.is_dir() { @@ -51,16 +52,32 @@ impl PluginManager { } } - lua.globals().set("manager", manager).ok()?; + lua.globals().set("manager", manager).unwrap(); Some(Self { lua }) } + pub fn load_all_plugins(&self) -> anyhow::Result<()> { + let lua = &self.lua; + let manager = lua.globals().get::<_, Table>("manager")?; + println!("{:?}", manager.len()); + for i in 0..(manager.len()? as i32) { + let v = manager.get::(i)?; + println!("{:?}", v.name); + let code = format!("manager[{i}].onLoad()"); + lua.load(&code).exec()?; + } + Ok(()) + } + fn init_plugin_dir() -> PathBuf { + log::info!("📖 Start to init plugin library ..."); + let app_path = app_path(); let plugin_path = app_path.join("plugins"); if !plugin_path.is_dir() { - create_dir_all(&plugin_path).unwrap(); + let url = "https://github.com/DioxusLabs/cli-plugin-library"; + clone_repo(&plugin_path, url).unwrap(); } plugin_path } diff --git a/src/tools.rs b/src/tools.rs index dc922050a..3f95ccac1 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -1,8 +1,8 @@ use std::{ fs::{create_dir_all, File}, + io::{Read, Write}, path::{Path, PathBuf}, process::Command, - io::{Read, Write} }; use anyhow::Context; @@ -40,6 +40,16 @@ pub fn temp_path() -> PathBuf { temp_path } +pub fn clone_repo(dir: &Path, url: &str) -> anyhow::Result<()> { + let target_dir = dir.parent().unwrap(); + let dir_name = dir.file_name().unwrap(); + + let mut cmd = Command::new("git"); + let cmd = cmd.current_dir(target_dir); + let _res = cmd.arg("clone").arg(url).arg(dir_name).output()?; + Ok(()) +} + pub fn tools_path() -> PathBuf { let app_path = app_path(); let temp_path = app_path.join("tools"); @@ -121,15 +131,9 @@ impl Tool { /// get tool version pub fn tool_version(&self) -> &str { match self { - Self::Binaryen => { - "version_105" - } - Self::Sass => { - "1.51.0" - } - Self::Tailwind => { - "v3.1.6" - } + Self::Binaryen => "version_105", + Self::Sass => "1.51.0", + Self::Tailwind => "v3.1.6", } } @@ -154,7 +158,7 @@ impl Tool { Self::Tailwind => { let windows_extension = match self.target_platform() { "windows" => ".exe", - _ => "" + _ => "", }; format!( "https://github.com/tailwindlabs/tailwindcss/releases/download/{version}/tailwindcss-{target}-x64{optional_ext}", @@ -177,7 +181,7 @@ impl Tool { "tar.gz" } } - Self::Tailwind => "bin" + Self::Tailwind => "bin", } } @@ -218,7 +222,7 @@ impl Tool { let dir_name = match self { Self::Binaryen => format!("binaryen-{}", self.tool_version()), Self::Sass => "dart-sass".to_string(), - Self::Tailwind => self.name().to_string() + Self::Tailwind => self.name().to_string(), }; if self.extension() == "tar.gz" { @@ -234,14 +238,14 @@ impl Tool { } else if self.extension() == "bin" { let bin_path = match self.target_platform() { "windows" => tool_path.join(&dir_name).join(self.name()).join(".exe"), - _ => tool_path.join(&dir_name).join(self.name()) - } ; + _ => tool_path.join(&dir_name).join(self.name()), + }; // Manualy creating tool directory because we directly download the binary via Github - std::fs::create_dir( tool_path.join(dir_name))?; + std::fs::create_dir(tool_path.join(dir_name))?; let mut final_file = std::fs::File::create(&bin_path)?; let mut temp_file = File::open(&temp_path)?; - let mut content = Vec::new(); + let mut content = Vec::new(); temp_file.read_to_end(&mut content)?; final_file.write_all(&content)?; From a21433016adf92eef937859daa4a290ecd4edf59 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 26 Jul 2022 17:03:34 +0800 Subject: [PATCH 07/48] fix: update wasm-bindgen version --- Cargo.lock | 46 +++++++++++++++++++++++----------------------- Cargo.toml | 2 +- src/builder.rs | 2 +- src/plugin/mod.rs | 6 ++++-- 4 files changed, 29 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4f7ee9f05..eaff1048a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2964,9 +2964,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c53b543413a17a202f4be280a7e5c62a1c69345f5de525ee64f8cfdbc954994" +checksum = "fc7652e3f6c4706c8d9cd54832c4a4ccb9b5336e2c3bd154d5cccfbf1c1f5f7d" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -2974,13 +2974,13 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5491a68ab4500fa6b4d726bd67408630c3dbe9c4fe7bda16d5c82a1fd8c7340a" +checksum = "662cd44805586bd52971b9586b1df85cdbbd9112e4ef4d8f41559c334dc6ac3f" dependencies = [ "bumpalo", - "lazy_static", "log", + "once_cell", "proc-macro2", "quote", "syn", @@ -2989,9 +2989,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-cli-support" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4016fbd42224de21aab2f009aeaec61067d278a298ba7f8f7f8d40fbffea0822" +checksum = "f583642dbe7dcd382bdefe7d66bfc1b9915677aebafe90da5b30c1951b8eb6b4" dependencies = [ "anyhow", "base64 0.9.3", @@ -3013,9 +3013,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-externref-xform" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f33c8e2d3f3b6f6647f982911eb4cb44998c8cca97a4fe7afc99f616ebb33a73" +checksum = "160edba014673ad3d778bf6455a29ebf34eeec826205fd827ab77d2c5facb4ff" dependencies = [ "anyhow", "walrus", @@ -3035,9 +3035,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c441e177922bc58f1e12c022624b6216378e5febc2f0533e41ba443d505b80aa" +checksum = "b260f13d3012071dfb1512849c033b1925038373aea48ced3012c09df952c602" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3045,9 +3045,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d94ac45fcf608c1f45ef53e748d35660f168490c10b23704c7779ab8f5c3048" +checksum = "5be8e654bdd9b79216c2929ab90721aa82faf65c48cdf08bdc4e7f51357b80da" dependencies = [ "proc-macro2", "quote", @@ -3058,9 +3058,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-multi-value-xform" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7015b54357604811162710d5cf274ab85d974fe1e324222dd5b2133afdefe9b9" +checksum = "f325e04a6c8054111290e264928836909af56d702ee4cf66e453951365a18b13" dependencies = [ "anyhow", "walrus", @@ -3068,15 +3068,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a89911bd99e5f3659ec4acf9c4d93b0a90fe4a2a11f15328472058edc5261be" +checksum = "6598dd0bd3c7d51095ff6531a5b23e02acdc81804e30d8f07afb77b7215a140a" [[package]] name = "wasm-bindgen-threads-xform" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6961b838d9a9c121ba4a1eea1628014cc759469e3defb42bbac9c5ed0f65be14" +checksum = "49a8f631f078e8e8dedec16ca98dc23cc47d4b63db9bf067cb4471aa768d7256" dependencies = [ "anyhow", "walrus", @@ -3085,9 +3085,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-wasm-conventions" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0a0eca38fe89471f57d6903f3e17e732d2d6f995a7af5b23f27df7fee0f0d18" +checksum = "f550ec6c59aad41a02ba60f59aa92bca03ada228e0a01fd5d5f21d889ef97a23" dependencies = [ "anyhow", "walrus", @@ -3095,9 +3095,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-wasm-interpreter" -version = "0.2.81" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b1c9fb7f71137840932bbb853ef1f83d68c88584b716c9bbae38675c9fb8b86" +checksum = "9c736fc384fa38ac5a906f7409d0e99832a79993dd76315d3befc3471d494141" dependencies = [ "anyhow", "log", diff --git a/Cargo.toml b/Cargo.toml index 31ac60386..9f0f18aef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ license = "MIT/Apache-2.0" # cli core clap = { version = "3.0.14", features = ["derive"] } thiserror = "1.0.30" -wasm-bindgen-cli-support = "0.2.79" +wasm-bindgen-cli-support = "0.2.82" colored = "2.0.0" # features diff --git a/src/builder.rs b/src/builder.rs index 2c7192c78..7f87757bd 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -124,7 +124,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result { .unwrap(); }); if bindgen_result.is_err() { - return Err(Error::BuildFailed("Bindgen build failed! \nThis is probably due to the Bindgen version, dioxus-cli using `0.2.79` Bindgen crate.".to_string())); + return Err(Error::BuildFailed("Bindgen build failed! \nThis is probably due to the Bindgen version, dioxus-cli using `0.2.82` Bindgen crate.".to_string())); } // check binaryen:wasm-opt tool diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index c69fb620b..0379b4fe9 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -36,8 +36,7 @@ impl PluginManager { let plugin_dir = Self::init_plugin_dir(); let mut index = 0; - println!("{plugin_dir:?}"); - for entry in WalkDir::new(plugin_dir).into_iter().filter_map(|e| e.ok()) { + for entry in WalkDir::new(&plugin_dir).into_iter().filter_map(|e| e.ok()) { let plugin_dir = entry.path().to_path_buf(); if plugin_dir.is_dir() { let init_file = plugin_dir.join("init.lua"); @@ -52,6 +51,9 @@ impl PluginManager { } } + lua.globals() + .set("package.path", format!("{}", plugin_dir.display())).unwrap(); + lua.globals().set("manager", manager).unwrap(); Some(Self { lua }) From da53c6784141bfe49dbdf82750120114b7e188a8 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Wed, 27 Jul 2022 23:51:35 +0800 Subject: [PATCH 08/48] feat: commit plugin interface --- Cargo.lock | 136 ++++++++++++++------------- Cargo.toml | 2 +- src/builder.rs | 2 +- src/plugin/interface.rs | 54 ----------- src/plugin/interface/command.rs | 51 ++++++++++ src/plugin/{ => interface}/logger.rs | 0 src/plugin/interface/mod.rs | 84 +++++++++++++++++ src/plugin/mod.rs | 33 +++---- 8 files changed, 222 insertions(+), 140 deletions(-) delete mode 100644 src/plugin/interface.rs create mode 100644 src/plugin/interface/command.rs rename src/plugin/{ => interface}/logger.rs (100%) create mode 100644 src/plugin/interface/mod.rs diff --git a/Cargo.lock b/Cargo.lock index eaff1048a..0457bed9a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -86,9 +86,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.5.11" +version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2cc6e8e8c993cb61a005fab8c1e5093a29199b7253b05a6883999312935c1ff" +checksum = "c943a505c17b494638a38a9af129067f760c9c06794b9f57d499266909be8e72" dependencies = [ "async-trait", "axum-core", @@ -121,9 +121,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4d047478b986f14a13edad31a009e2e05cb241f9805d0d75e4cba4e129ad4d" +checksum = "e4f44a0e6200e9d11a1cdc989e4b358f6e3d354fbf48478f345a17f4e43f8635" dependencies = [ "async-trait", "bytes", @@ -263,9 +263,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" +checksum = "f0b3de4a0c5e67e16066a0715723abd91edc2f9001d09c46e1dca929351e130e" [[package]] name = "bzip2" @@ -369,9 +369,9 @@ dependencies = [ [[package]] name = "clap" -version = "3.2.8" +version = "3.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190814073e85d238f31ff738fcb0bf6910cedeb73376c87cd69291028966fd83" +checksum = "44bbe24bbd31a185bc2c4f7c2abe80bea13a20d57ee4e55be70ac512bdc76417" dependencies = [ "atty", "bitflags", @@ -386,9 +386,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "3.2.7" +version = "3.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "759bf187376e1afa7b85b959e6a664a3e7a95203415dba952ad19139e798f902" +checksum = "9ba52acd3b0a5c33aeada5cdaa3267cdc7c594a98731d4268cdc1532f4264cb4" dependencies = [ "heck 0.4.0", "proc-macro-error", @@ -491,9 +491,9 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c02a4d71819009c192cf4872265391563fd6a84c81ff2c0f2a7026ca4c1d85c" +checksum = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521" dependencies = [ "cfg-if", "crossbeam-utils", @@ -501,9 +501,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d82ee10ce34d7bc12c2122495e7593a9c41347ecdd64185af4ecf72cb1a7f83" +checksum = "51887d4adc7b564537b15adcfb307936f8075dfcd5f00dde9a9f1d29383682bc" dependencies = [ "cfg-if", "once_cell", @@ -511,9 +511,9 @@ dependencies = [ [[package]] name = "crypto-common" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ccfd8c0ee4cce11e45b3fd6f9d5e69e0cc62912aa6a0cb1bf4617b0eba5a12f" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array 0.14.5", "typenum", @@ -521,9 +521,9 @@ dependencies = [ [[package]] name = "curl" -version = "0.4.43" +version = "0.4.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37d855aeef205b43f65a5001e0997d81f8efca7badad4fad7d897aa7f0d0651f" +checksum = "509bd11746c7ac09ebd19f0b17782eae80aadee26237658a6b4808afb5c11a22" dependencies = [ "curl-sys", "libc", @@ -536,9 +536,9 @@ dependencies = [ [[package]] name = "curl-sys" -version = "0.4.55+curl-7.83.1" +version = "0.4.56+curl-7.83.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23734ec77368ec583c2e61dd3f0b0e5c98b93abe6d2a004ca06b91dd7e3e2762" +checksum = "6093e169dd4de29e468fa649fbae11cdcd5551c81fe5bf1b0677adad7ef3d26f" dependencies = [ "cc", "libc", @@ -612,7 +612,7 @@ dependencies = [ [[package]] name = "dioxus" version = "0.2.4" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "dioxus-core", "dioxus-core-macro", @@ -670,7 +670,7 @@ dependencies = [ [[package]] name = "dioxus-core" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "backtrace", "bumpalo", @@ -689,7 +689,7 @@ dependencies = [ [[package]] name = "dioxus-core-macro" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "dioxus-rsx", "dioxus-rsx-interpreter", @@ -701,7 +701,7 @@ dependencies = [ [[package]] name = "dioxus-hooks" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "dioxus-core", "futures-channel", @@ -711,7 +711,7 @@ dependencies = [ [[package]] name = "dioxus-html" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "dioxus-core", "enumset", @@ -722,7 +722,7 @@ dependencies = [ [[package]] name = "dioxus-rsx" version = "0.0.0" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "proc-macro2", "quote", @@ -732,7 +732,7 @@ dependencies = [ [[package]] name = "dioxus-rsx-interpreter" version = "0.1.0" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "dioxus-core", "dioxus-hooks", @@ -750,7 +750,7 @@ dependencies = [ [[package]] name = "dioxus-ssr" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#2369b0cc7f54cf9a99db2114f9fc6481f14ffd30" +source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" dependencies = [ "dioxus-core", ] @@ -873,9 +873,9 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" [[package]] name = "fastrand" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" +checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" dependencies = [ "instant", ] @@ -898,7 +898,7 @@ checksum = "e94a7bbaa59354bc20dd75b67f23e2797b4490e9d6928203fb105c79e448c86c" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.2.13", + "redox_syscall 0.2.16", "windows-sys", ] @@ -1099,9 +1099,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.26.1" +version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4" +checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" [[package]] name = "h2" @@ -1124,9 +1124,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.12.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "607c8a29735385251a339424dd462993c0fed8fa09d378f259377df08c126022" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" [[package]] name = "headers" @@ -1424,9 +1424,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.58" +version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fac17f7123a73ca62df411b1bf727ccc805daa070338fda671c86dac1bdc27" +checksum = "258451ab10b34f8af53416d1fdab72c22e805f0c92a1136d59470ec0b11138b2" dependencies = [ "wasm-bindgen", ] @@ -1619,9 +1619,9 @@ dependencies = [ [[package]] name = "mlua" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82d0b12c7c8d3bdda5933d2aa322c76e4833d822796495f299990ca652bd1bf" +checksum = "8afb4815a6d6a3bd1c23e6c647f7df18c9800c12e80526a98e18d7decd7cedcd" dependencies = [ "bstr", "cc", @@ -1788,9 +1788,9 @@ dependencies = [ [[package]] name = "os_str_bytes" -version = "6.1.0" +version = "6.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21326818e99cfe6ce1e524c2a805c189a99b5ae555a35d19f9a284b427d86afa" +checksum = "648001efe5d5c0102d8cea768e348da85d90af8ba91f0bea908f157951493cd4" [[package]] name = "parking_lot" @@ -1810,7 +1810,7 @@ checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.2.13", + "redox_syscall 0.2.16", "smallvec", "windows-sys", ] @@ -1957,9 +1957,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.40" +version = "1.0.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd96a1e8ed2596c337f8eae5f24924ec83f5ad5ab21ea8e455d3566c69fbcaf7" +checksum = "c278e965f1d8cf32d6e0e96de3d3e79712178ae67986d9cf9151f51e95aac89b" dependencies = [ "unicode-ident", ] @@ -2017,9 +2017,9 @@ checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" [[package]] name = "redox_syscall" -version = "0.2.13" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ "bitflags", ] @@ -2042,7 +2042,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" dependencies = [ "getrandom 0.2.7", - "redox_syscall 0.2.13", + "redox_syscall 0.2.16", "thiserror", ] @@ -2267,18 +2267,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.138" +version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1578c6245786b9d168c5447eeacfb96856573ca56c9d68fdcf394be134882a47" +checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.138" +version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "023e9b1467aef8a10fb88f25611870ada9800ef7e22afce356bb0d2387b6f27c" +checksum = "6f2122636b9fe3b81f1cb25099fcf2d3f542cdb1d45940d56c713158884a05da" dependencies = [ "proc-macro2", "quote", @@ -2370,9 +2370,12 @@ checksum = "0b8de496cf83d4ed58b6be86c3a275b8602f6ffe98d3024a869e124147a9a3ac" [[package]] name = "slab" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb703cfe953bccee95685111adeedb76fabe4e97549a58d16f03ea7b9367bb32" +checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" +dependencies = [ + "autocfg", +] [[package]] name = "smallvec" @@ -2457,7 +2460,7 @@ dependencies = [ "cfg-if", "fastrand", "libc", - "redox_syscall 0.2.13", + "redox_syscall 0.2.16", "remove_dir_all", "winapi", ] @@ -2553,10 +2556,11 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "tokio" -version = "1.19.2" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c51a52ed6686dd62c320f9b89299e9dfb46f730c7a48e635c19f21d116cb1439" +checksum = "7a8325f63a7d4774dd041e363b2409ed1c5cbbd0f867795e661df066b2b0a581" dependencies = [ + "autocfg", "bytes", "libc", "memchr", @@ -2605,9 +2609,9 @@ dependencies = [ [[package]] name = "tokio-tungstenite" -version = "0.17.1" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06cda1232a49558c46f8a504d5b93101d42c0bf7f911f12a105ba48168f821ae" +checksum = "f714dd15bead90401d77e04243611caec13726c2408afd5b31901dfcdcb3b181" dependencies = [ "futures-util", "log", @@ -2784,9 +2788,9 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" [[package]] name = "tungstenite" -version = "0.17.2" +version = "0.17.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d96a2dea40e7570482f28eb57afbe42d97551905da6a9400acc5c328d24004f5" +checksum = "e27992fd6a8c29ee7eef28fc78349aa244134e10ad447ce3b9f0ac0ed0fa4ce0" dependencies = [ "base64 0.13.0", "byteorder", @@ -2830,9 +2834,9 @@ checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" [[package]] name = "unicode-ident" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c" +checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" [[package]] name = "unicode-normalization" @@ -3023,9 +3027,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.31" +version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de9a9cec1733468a8c657e57fa2413d2ae2c0129b95e87c5b72b8ace4d13f31f" +checksum = "fa76fb221a1f8acddf5b54ace85912606980ad661ac7a503b4570ffd3a624dad" dependencies = [ "cfg-if", "js-sys", @@ -3128,9 +3132,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.58" +version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fed94beee57daf8dd7d51f2b15dc2bcde92d7a72304cdf662a4371008b71b90" +checksum = "ed055ab27f941423197eb86b2035720b1a3ce40504df082cac2ecc6ed73335a1" dependencies = [ "js-sys", "wasm-bindgen", diff --git a/Cargo.toml b/Cargo.toml index 9f0f18aef..31ac60386 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ license = "MIT/Apache-2.0" # cli core clap = { version = "3.0.14", features = ["derive"] } thiserror = "1.0.30" -wasm-bindgen-cli-support = "0.2.82" +wasm-bindgen-cli-support = "0.2.79" colored = "2.0.0" # features diff --git a/src/builder.rs b/src/builder.rs index 7f87757bd..5cb994a65 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -124,7 +124,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result { .unwrap(); }); if bindgen_result.is_err() { - return Err(Error::BuildFailed("Bindgen build failed! \nThis is probably due to the Bindgen version, dioxus-cli using `0.2.82` Bindgen crate.".to_string())); + return Err(Error::BuildFailed("Bindgen build failed! \nThis is probably due to the Bindgen version, dioxus-cli using `0.2.81` Bindgen crate.".to_string())); } // check binaryen:wasm-opt tool diff --git a/src/plugin/interface.rs b/src/plugin/interface.rs deleted file mode 100644 index 399b6919f..000000000 --- a/src/plugin/interface.rs +++ /dev/null @@ -1,54 +0,0 @@ -use mlua::{FromLua, Function}; - -pub struct PluginInfo<'lua> { - pub name: String, - repository: String, - author: String, - - on_init: Option>, - on_load: Option>, - on_build_start: Option>, - on_build_end: Option>, -} - -impl<'lua> FromLua<'lua> for PluginInfo<'lua> { - fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { - let mut res = Self { - name: String::default(), - repository: String::default(), - author: String::default(), - - on_init: None, - on_load: None, - on_build_start: None, - on_build_end: None, - }; - if let mlua::Value::Table(tab) = lua_value { - if let Ok(v) = tab.get::<_, String>("name") { - res.name = v; - } - if let Ok(v) = tab.get::<_, String>("repository") { - res.repository = v; - } - if let Ok(v) = tab.get::<_, String>("author") { - res.author = v; - } - - if let Ok(v) = tab.get::<_, Function>("onInit") { - res.on_init = Some(v); - } - if let Ok(v) = tab.get::<_, Function>("onLoad") { - res.on_load = Some(v); - } - if let Ok(v) = tab.get::<_, Function>("onBuildStart") { - res.on_build_start = Some(v); - } - if let Ok(v) = tab.get::<_, Function>("onBuildEnd") { - res.on_build_end = Some(v); - } - - } - - Ok(res) - } -} diff --git a/src/plugin/interface/command.rs b/src/plugin/interface/command.rs new file mode 100644 index 000000000..23d940601 --- /dev/null +++ b/src/plugin/interface/command.rs @@ -0,0 +1,51 @@ +use std::process::{Command, Stdio}; + +use mlua::UserData; + +pub struct PluginCommander; +impl UserData for PluginCommander { + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_function("exec", |_, cmd: Vec| { + if cmd.len() == 0 { + return Ok(()); + } + let cmd_name = cmd.get(0).unwrap(); + let mut command = Command::new(cmd_name); + let t = cmd + .iter() + .enumerate() + .filter(|(i, _)| *i > 0) + .map(|v| v.1.clone()) + .collect::>(); + command.args(t); + command.stdout(Stdio::inherit()); + command.output()?; + Ok(()) + }); + methods.add_function("execQuiet", |_, cmd: Vec| { + if cmd.len() == 0 { + return Ok(()); + } + let cmd_name = cmd.get(0).unwrap(); + let mut command = Command::new(cmd_name); + let t = cmd + .iter() + .enumerate() + .filter(|(i, _)| *i > 0) + .map(|v| v.1.clone()) + .collect::>(); + command.args(t); + command.stdout(Stdio::null()); + command.output()?; + Ok(()) + }); + methods.add_function("execSimple", |_, cmd: String| { + let _ = Command::new(cmd).stdout(Stdio::inherit()).output()?; + Ok(()) + }); + } + + fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(_fields: &mut F) { + + } +} diff --git a/src/plugin/logger.rs b/src/plugin/interface/logger.rs similarity index 100% rename from src/plugin/logger.rs rename to src/plugin/interface/logger.rs diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs new file mode 100644 index 000000000..219ba2f47 --- /dev/null +++ b/src/plugin/interface/mod.rs @@ -0,0 +1,84 @@ +use mlua::{FromLua, Function, ToLua}; + +pub mod logger; +pub mod command; + +#[derive(Debug)] +pub struct PluginInfo<'lua> { + pub name: String, + pub repository: String, + pub author: String, + + pub on_init: Option>, + pub on_load: Option>, + pub on_build_start: Option>, + pub on_build_finish: Option>, +} + +impl<'lua> FromLua<'lua> for PluginInfo<'lua> { + fn from_lua(lua_value: mlua::Value<'lua>, _lua: &'lua mlua::Lua) -> mlua::Result { + let mut res = Self { + name: String::default(), + repository: String::default(), + author: String::default(), + + on_init: None, + on_load: None, + on_build_start: None, + on_build_finish: None, + }; + if let mlua::Value::Table(tab) = lua_value { + if let Ok(v) = tab.get::<_, String>("name") { + res.name = v; + } + if let Ok(v) = tab.get::<_, String>("repository") { + res.repository = v; + } + if let Ok(v) = tab.get::<_, String>("author") { + res.author = v; + } + + if let Ok(v) = tab.get::<_, Function>("onInit") { + res.on_init = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("onLoad") { + res.on_load = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("onBuildStart") { + res.on_build_start = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("onBuildFinish") { + res.on_build_finish = Some(v); + } + + } + + Ok(res) + } +} + +impl<'lua> ToLua<'lua> for PluginInfo<'lua> { + fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { + + let res = lua.create_table()?; + + res.set("name", self.name.to_string())?; + res.set("repository", self.repository.to_string())?; + res.set("author", self.author.to_string())?; + + if let Some(e) = self.on_init { + res.set("onInit", e)?; + } + if let Some(e) = self.on_load { + res.set("onLoad", e)?; + } + if let Some(e) = self.on_build_start { + res.set("onBuildStart", e)?; + } + if let Some(e) = self.on_build_finish { + res.set("onBuildFinish", e)?; + } + + Ok(mlua::Value::Table(res)) + } +} \ No newline at end of file diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 0379b4fe9..0defe1b55 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -1,16 +1,13 @@ -use std::{fs::create_dir_all, io::Read, path::PathBuf}; +use std::{io::Read, path::PathBuf}; use mlua::{Lua, Table}; use serde::{Deserialize, Serialize}; -use walkdir::WalkDir; use crate::tools::{app_path, clone_repo}; -use self::{interface::PluginInfo, logger::PluginLogger}; +use self::{interface::{logger::PluginLogger, command::PluginCommander}, interface::PluginInfo}; -pub mod logger; - -mod interface; +pub mod interface; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PluginConfig { @@ -33,10 +30,15 @@ impl PluginManager { let manager = lua.create_table().unwrap(); lua.globals().set("plugin_logger", PluginLogger).unwrap(); + lua.globals().set("plugin_commander", PluginCommander).unwrap(); let plugin_dir = Self::init_plugin_dir(); - let mut index = 0; - for entry in WalkDir::new(&plugin_dir).into_iter().filter_map(|e| e.ok()) { + let mut index = 1; + for entry in std::fs::read_dir(&plugin_dir).ok()? { + if entry.is_err() { + continue; + } + let entry = entry.unwrap(); let plugin_dir = entry.path().to_path_buf(); if plugin_dir.is_dir() { let init_file = plugin_dir.join("init.lua"); @@ -44,16 +46,13 @@ impl PluginManager { let mut file = std::fs::File::open(init_file).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); - let info = lua.load(&buffer).eval::().unwrap(); + let info = lua.load(&buffer).eval::().unwrap(); let _ = manager.set(index, info); + index += 1; } - index += 1; } } - lua.globals() - .set("package.path", format!("{}", plugin_dir.display())).unwrap(); - lua.globals().set("manager", manager).unwrap(); Some(Self { lua }) @@ -62,10 +61,9 @@ impl PluginManager { pub fn load_all_plugins(&self) -> anyhow::Result<()> { let lua = &self.lua; let manager = lua.globals().get::<_, Table>("manager")?; - println!("{:?}", manager.len()); - for i in 0..(manager.len()? as i32) { + for i in 1..(manager.len()? as i32 + 1) { let v = manager.get::(i)?; - println!("{:?}", v.name); + println!("{v:?}"); let code = format!("manager[{i}].onLoad()"); lua.load(&code).exec()?; } @@ -73,11 +71,10 @@ impl PluginManager { } fn init_plugin_dir() -> PathBuf { - log::info!("📖 Start to init plugin library ..."); - let app_path = app_path(); let plugin_path = app_path.join("plugins"); if !plugin_path.is_dir() { + log::info!("📖 Start to init plugin library ..."); let url = "https://github.com/DioxusLabs/cli-plugin-library"; clone_repo(&plugin_path, url).unwrap(); } From 99b300d8d3caee7662a094a14780bfc5693bccfd Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Thu, 28 Jul 2022 00:31:07 +0800 Subject: [PATCH 09/48] feat: commit code --- src/plugin/interface/command.rs | 77 ++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 21 deletions(-) diff --git a/src/plugin/interface/command.rs b/src/plugin/interface/command.rs index 23d940601..bc7040047 100644 --- a/src/plugin/interface/command.rs +++ b/src/plugin/interface/command.rs @@ -1,27 +1,64 @@ use std::process::{Command, Stdio}; -use mlua::UserData; +use mlua::{FromLua, UserData}; + +enum StdioFromString { + Inhert, + Piped, + Null, +} +impl<'lua> FromLua<'lua> for StdioFromString { + fn from_lua(lua_value: mlua::Value<'lua>, _lua: &'lua mlua::Lua) -> mlua::Result { + if let mlua::Value::String(v) = lua_value { + let v = v.to_str().unwrap(); + return Ok(match v.to_lowercase().as_str() { + "inhert" => Self::Inhert, + "piped" => Self::Piped, + "null" => Self::Null, + _ => Self::Inhert, + }); + } + Ok(Self::Inhert) + } +} +impl StdioFromString { + pub fn to_stdio(self) -> Stdio { + match self { + StdioFromString::Inhert => Stdio::inherit(), + StdioFromString::Piped => Stdio::piped(), + StdioFromString::Null => Stdio::null(), + } + } +} pub struct PluginCommander; impl UserData for PluginCommander { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { - methods.add_function("exec", |_, cmd: Vec| { - if cmd.len() == 0 { - return Ok(()); - } - let cmd_name = cmd.get(0).unwrap(); - let mut command = Command::new(cmd_name); - let t = cmd - .iter() - .enumerate() - .filter(|(i, _)| *i > 0) - .map(|v| v.1.clone()) - .collect::>(); - command.args(t); - command.stdout(Stdio::inherit()); - command.output()?; - Ok(()) - }); + methods.add_function( + "exec", + |_, args: (Vec, StdioFromString, StdioFromString)| { + + let cmd = args.0; + let stdout = args.1; + let stderr = args.2; + + if cmd.len() == 0 { + return Ok(()); + } + let cmd_name = cmd.get(0).unwrap(); + let mut command = Command::new(cmd_name); + let t = cmd + .iter() + .enumerate() + .filter(|(i, _)| *i > 0) + .map(|v| v.1.clone()) + .collect::>(); + command.args(t); + command.stdout(stdout.to_stdio()).stderr(stderr.to_stdio()); + command.output()?; + Ok(()) + }, + ); methods.add_function("execQuiet", |_, cmd: Vec| { if cmd.len() == 0 { return Ok(()); @@ -45,7 +82,5 @@ impl UserData for PluginCommander { }); } - fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(_fields: &mut F) { - - } + fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(_fields: &mut F) {} } From 2065193b63e2e3bcd22f0b328d3fa981ae88ff80 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Thu, 28 Jul 2022 00:34:36 +0800 Subject: [PATCH 10/48] feat: commit code --- src/plugin/mod.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 0defe1b55..ffb012e32 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -5,7 +5,10 @@ use serde::{Deserialize, Serialize}; use crate::tools::{app_path, clone_repo}; -use self::{interface::{logger::PluginLogger, command::PluginCommander}, interface::PluginInfo}; +use self::{ + interface::PluginInfo, + interface::{command::PluginCommander, logger::PluginLogger}, +}; pub mod interface; @@ -30,7 +33,9 @@ impl PluginManager { let manager = lua.create_table().unwrap(); lua.globals().set("plugin_logger", PluginLogger).unwrap(); - lua.globals().set("plugin_commander", PluginCommander).unwrap(); + lua.globals() + .set("plugin_commander", PluginCommander) + .unwrap(); let plugin_dir = Self::init_plugin_dir(); let mut index = 1; @@ -54,6 +59,9 @@ impl PluginManager { } lua.globals().set("manager", manager).unwrap(); + lua.globals() + .set("LIBDIR", plugin_dir.join("library").to_str().unwrap()) + .unwrap(); Some(Self { lua }) } From 59acefadc9415066789b07c9d849be2a59a87280 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Thu, 28 Jul 2022 10:31:25 +0800 Subject: [PATCH 11/48] feat: commit code --- src/plugin/interface/command.rs | 21 --------------------- src/plugin/interface/fs.rs | 21 +++++++++++++++++++++ src/plugin/interface/mod.rs | 17 +++++++++-------- src/plugin/mod.rs | 7 ++++--- 4 files changed, 34 insertions(+), 32 deletions(-) create mode 100644 src/plugin/interface/fs.rs diff --git a/src/plugin/interface/command.rs b/src/plugin/interface/command.rs index bc7040047..34b6f9082 100644 --- a/src/plugin/interface/command.rs +++ b/src/plugin/interface/command.rs @@ -59,27 +59,6 @@ impl UserData for PluginCommander { Ok(()) }, ); - methods.add_function("execQuiet", |_, cmd: Vec| { - if cmd.len() == 0 { - return Ok(()); - } - let cmd_name = cmd.get(0).unwrap(); - let mut command = Command::new(cmd_name); - let t = cmd - .iter() - .enumerate() - .filter(|(i, _)| *i > 0) - .map(|v| v.1.clone()) - .collect::>(); - command.args(t); - command.stdout(Stdio::null()); - command.output()?; - Ok(()) - }); - methods.add_function("execSimple", |_, cmd: String| { - let _ = Command::new(cmd).stdout(Stdio::inherit()).output()?; - Ok(()) - }); } fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(_fields: &mut F) {} diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs new file mode 100644 index 000000000..24169e011 --- /dev/null +++ b/src/plugin/interface/fs.rs @@ -0,0 +1,21 @@ +use std::path::PathBuf; + +use mlua::UserData; + +pub struct PluginFileSystem; +impl UserData for PluginFileSystem { + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_function("exists", |_, path: String| { + let path = PathBuf::from(path); + Ok(path.exists()) + }); + methods.add_function("is_dir", |_, path: String| { + let path = PathBuf::from(path); + Ok(path.is_dir()) + }); + methods.add_function("is_file", |_, path: String| { + let path = PathBuf::from(path); + Ok(path.is_file()) + }); + } +} \ No newline at end of file diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index 219ba2f47..d843c0e6a 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -2,6 +2,7 @@ use mlua::{FromLua, Function, ToLua}; pub mod logger; pub mod command; +pub mod fs; #[derive(Debug)] pub struct PluginInfo<'lua> { @@ -38,16 +39,16 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { res.author = v; } - if let Ok(v) = tab.get::<_, Function>("onInit") { + if let Ok(v) = tab.get::<_, Function>("on_init") { res.on_init = Some(v); } - if let Ok(v) = tab.get::<_, Function>("onLoad") { + if let Ok(v) = tab.get::<_, Function>("on_load") { res.on_load = Some(v); } - if let Ok(v) = tab.get::<_, Function>("onBuildStart") { + if let Ok(v) = tab.get::<_, Function>("on_build_start") { res.on_build_start = Some(v); } - if let Ok(v) = tab.get::<_, Function>("onBuildFinish") { + if let Ok(v) = tab.get::<_, Function>("on_build_finish") { res.on_build_finish = Some(v); } @@ -67,16 +68,16 @@ impl<'lua> ToLua<'lua> for PluginInfo<'lua> { res.set("author", self.author.to_string())?; if let Some(e) = self.on_init { - res.set("onInit", e)?; + res.set("on_init", e)?; } if let Some(e) = self.on_load { - res.set("onLoad", e)?; + res.set("on_load", e)?; } if let Some(e) = self.on_build_start { - res.set("onBuildStart", e)?; + res.set("on_build_start", e)?; } if let Some(e) = self.on_build_finish { - res.set("onBuildFinish", e)?; + res.set("on_build_finish", e)?; } Ok(mlua::Value::Table(res)) diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index ffb012e32..aa98d7684 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -7,7 +7,7 @@ use crate::tools::{app_path, clone_repo}; use self::{ interface::PluginInfo, - interface::{command::PluginCommander, logger::PluginLogger}, + interface::{command::PluginCommander, logger::PluginLogger, fs::PluginFileSystem}, }; pub mod interface; @@ -32,10 +32,11 @@ impl PluginManager { let manager = lua.create_table().unwrap(); - lua.globals().set("plugin_logger", PluginLogger).unwrap(); + lua.globals().set("PLUGIN_LOGGER", PluginLogger).unwrap(); lua.globals() - .set("plugin_commander", PluginCommander) + .set("PLUGIN_COMMAND", PluginCommander) .unwrap(); + lua.globals().set("PLUGINFS", PluginFileSystem).unwrap(); let plugin_dir = Self::init_plugin_dir(); let mut index = 1; From 363022465964a45111ece9cee6c66a4470b1216f Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Thu, 28 Jul 2022 23:07:55 +0800 Subject: [PATCH 12/48] feat: commit codee --- .vscode/settings.json | 3 ++- src/plugin/interface/download.rs | 8 +++++++ src/plugin/interface/fs.rs | 36 ++++++++++++++++++++++++++++++-- src/plugin/interface/mod.rs | 1 + src/plugin/mod.rs | 7 ++++--- 5 files changed, 49 insertions(+), 6 deletions(-) create mode 100644 src/plugin/interface/download.rs diff --git a/.vscode/settings.json b/.vscode/settings.json index e56c13485..40461adda 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,6 @@ { "Lua.diagnostics.globals": [ - "plugin_logger" + "plugin_logger", + "PLUGIN_DOWNLOADER" ] } diff --git a/src/plugin/interface/download.rs b/src/plugin/interface/download.rs new file mode 100644 index 000000000..8718e6547 --- /dev/null +++ b/src/plugin/interface/download.rs @@ -0,0 +1,8 @@ +use mlua::UserData; + +pub struct PluginDownloader; +impl UserData for PluginDownloader { + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(_methods: &mut M) { + // methods.add_function("name", function) + } +} \ No newline at end of file diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs index 24169e011..13b5e928e 100644 --- a/src/plugin/interface/fs.rs +++ b/src/plugin/interface/fs.rs @@ -1,4 +1,7 @@ -use std::path::PathBuf; +use std::{ + fs::{create_dir, create_dir_all}, + path::PathBuf, io::{Read, Write}, +}; use mlua::UserData; @@ -17,5 +20,34 @@ impl UserData for PluginFileSystem { let path = PathBuf::from(path); Ok(path.is_file()) }); + methods.add_function("create_dir", |_, args: (String, bool)| { + let path = args.0; + let recursive = args.1; + let path = PathBuf::from(path); + if !path.exists() { + let v = if recursive { + create_dir_all(path) + } else { + create_dir(path) + }; + return Ok(v.is_ok()); + } + Ok(true) + }); + methods.add_function("file_get_content", |_, path: String| { + let path = PathBuf::from(path); + let mut file = std::fs::File::open(path)?; + let mut buffer = String::new(); + file.read_to_string(&mut buffer)?; + Ok(buffer) + }); + methods.add_function("file_set_content", |_, args: (String, String)| { + let path = args.0; + let content = args.1; + let path = PathBuf::from(path); + let mut file = std::fs::File::create(path)?; + file.write_all(content.as_bytes())?; + Ok(()) + }); } -} \ No newline at end of file +} diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index d843c0e6a..026bc04de 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -3,6 +3,7 @@ use mlua::{FromLua, Function, ToLua}; pub mod logger; pub mod command; pub mod fs; +pub mod download; #[derive(Debug)] pub struct PluginInfo<'lua> { diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index aa98d7684..d12a394f8 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -7,7 +7,7 @@ use crate::tools::{app_path, clone_repo}; use self::{ interface::PluginInfo, - interface::{command::PluginCommander, logger::PluginLogger, fs::PluginFileSystem}, + interface::{command::PluginCommander, logger::PluginLogger, fs::PluginFileSystem, download::PluginDownloader}, }; pub mod interface; @@ -36,7 +36,8 @@ impl PluginManager { lua.globals() .set("PLUGIN_COMMAND", PluginCommander) .unwrap(); - lua.globals().set("PLUGINFS", PluginFileSystem).unwrap(); + lua.globals().set("PLUGIN_FS", PluginFileSystem).unwrap(); + lua.globals().set("PLUGIN_DOWNLOAD", PluginDownloader).unwrap(); let plugin_dir = Self::init_plugin_dir(); let mut index = 1; @@ -73,7 +74,7 @@ impl PluginManager { for i in 1..(manager.len()? as i32 + 1) { let v = manager.get::(i)?; println!("{v:?}"); - let code = format!("manager[{i}].onLoad()"); + let code = format!("manager[{i}].on_load()"); lua.load(&code).exec()?; } Ok(()) From 54dc59360ee5002cfd002b1983478bdfaf109061 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sat, 30 Jul 2022 09:57:38 +0800 Subject: [PATCH 13/48] feat: commit dirs library --- src/plugin/interface/dirs.rs | 29 +++++++++++++++++++++++++++++ src/plugin/interface/mod.rs | 1 + src/plugin/mod.rs | 11 ++++++++--- 3 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 src/plugin/interface/dirs.rs diff --git a/src/plugin/interface/dirs.rs b/src/plugin/interface/dirs.rs new file mode 100644 index 000000000..914ed60bb --- /dev/null +++ b/src/plugin/interface/dirs.rs @@ -0,0 +1,29 @@ +use mlua::UserData; + +use crate::tools::app_path; + +pub struct PluginDirs; +impl UserData for PluginDirs { + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_function("plugin_dir", |_, ()| { + let path = app_path().join("plugins"); + Ok(path.to_str().unwrap().to_string()) + }); + methods.add_function("self_dir", |_, name: String| { + let path = app_path().join("plugins").join(name); + Ok(path.to_str().unwrap().to_string()) + }); + methods.add_function("document_dir", |_, ()| { + let path = dirs::document_dir().unwrap().to_str().unwrap().to_string(); + Ok(path) + }); + methods.add_function("download_dir", |_, ()| { + let path = dirs::download_dir().unwrap().to_str().unwrap().to_string(); + Ok(path) + }); + methods.add_function("cache_dir", |_, ()| { + let path = dirs::cache_dir().unwrap().to_str().unwrap().to_string(); + Ok(path) + }); + } +} \ No newline at end of file diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index 026bc04de..c4db1528a 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -4,6 +4,7 @@ pub mod logger; pub mod command; pub mod fs; pub mod download; +pub mod dirs; #[derive(Debug)] pub struct PluginInfo<'lua> { diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index d12a394f8..bf8a73cb6 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -7,7 +7,10 @@ use crate::tools::{app_path, clone_repo}; use self::{ interface::PluginInfo, - interface::{command::PluginCommander, logger::PluginLogger, fs::PluginFileSystem, download::PluginDownloader}, + interface::{ + command::PluginCommander, download::PluginDownloader, fs::PluginFileSystem, + logger::PluginLogger, + }, }; pub mod interface; @@ -37,7 +40,9 @@ impl PluginManager { .set("PLUGIN_COMMAND", PluginCommander) .unwrap(); lua.globals().set("PLUGIN_FS", PluginFileSystem).unwrap(); - lua.globals().set("PLUGIN_DOWNLOAD", PluginDownloader).unwrap(); + lua.globals() + .set("PLUGIN_DOWNLOAD", PluginDownloader) + .unwrap(); let plugin_dir = Self::init_plugin_dir(); let mut index = 1; @@ -60,10 +65,10 @@ impl PluginManager { } } - lua.globals().set("manager", manager).unwrap(); lua.globals() .set("LIBDIR", plugin_dir.join("library").to_str().unwrap()) .unwrap(); + lua.globals().set("manager", manager).unwrap(); Some(Self { lua }) } From d13955e39bfb37573fe4c1e822ff083ce8255d43 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 31 Jul 2022 23:15:54 +0800 Subject: [PATCH 14/48] feat: commit code --- src/plugin/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index bf8a73cb6..090dbc6f1 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -8,8 +8,8 @@ use crate::tools::{app_path, clone_repo}; use self::{ interface::PluginInfo, interface::{ - command::PluginCommander, download::PluginDownloader, fs::PluginFileSystem, - logger::PluginLogger, + command::PluginCommander, dirs::PluginDirs, download::PluginDownloader, + fs::PluginFileSystem, logger::PluginLogger, }, }; @@ -43,6 +43,7 @@ impl PluginManager { lua.globals() .set("PLUGIN_DOWNLOAD", PluginDownloader) .unwrap(); + lua.globals().set("PLUGIN_DIRS", PluginDirs).unwrap(); let plugin_dir = Self::init_plugin_dir(); let mut index = 1; From 2ad5c7e282ec9611525bb7bbfd0f4bed7e3d1f66 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Mon, 1 Aug 2022 16:03:17 +0800 Subject: [PATCH 15/48] feat: commit file download --- Cargo.lock | 3 +++ Cargo.toml | 2 +- src/plugin/interface/download.rs | 27 +++++++++++++++++++++++---- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0457bed9a..97e4d0a6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1625,6 +1625,9 @@ checksum = "8afb4815a6d6a3bd1c23e6c647f7df18c9800c12e80526a98e18d7decd7cedcd" dependencies = [ "bstr", "cc", + "futures-core", + "futures-task", + "futures-util", "lua-src", "luajit-src", "num-traits", diff --git a/Cargo.toml b/Cargo.toml index 31ac60386..8b2a3904e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ dioxus-rsx-interpreter = { git = "https://github.com/dioxuslabs/dioxus/" } proc-macro2 = { version = "1.0", features = ["span-locations"] } # plugin packages -mlua = { version = "0.8.1", features = ["lua54", "vendored"] } +mlua = { version = "0.8.1", features = ["lua54", "vendored", "async"] } [[bin]] path = "src/main.rs" diff --git a/src/plugin/interface/download.rs b/src/plugin/interface/download.rs index 8718e6547..2edc68c9d 100644 --- a/src/plugin/interface/download.rs +++ b/src/plugin/interface/download.rs @@ -1,8 +1,27 @@ +use std::{io::Cursor, path::PathBuf}; + use mlua::UserData; pub struct PluginDownloader; impl UserData for PluginDownloader { - fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(_methods: &mut M) { - // methods.add_function("name", function) - } -} \ No newline at end of file + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_async_function("download_file", |_, args: (String, String)| async move { + let url = args.0; + let path = args.1; + + let resp = reqwest::get(url).await; + if let Ok(resp) = resp { + let mut content = Cursor::new(resp.bytes().await.unwrap()); + let file = std::fs::File::create(PathBuf::from(path)); + if file.is_err() { + return Ok(false); + } + let mut file = file.unwrap(); + let res = std::io::copy(&mut content, &mut file); + return Ok(res.is_ok()); + } + + Ok(false) + }); + } +} From 7609406bcd28bbbcefbe3d474b73c093ffc3d6fa Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Mon, 1 Aug 2022 16:14:29 +0800 Subject: [PATCH 16/48] feat: commit version info --- src/plugin/interface/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index c4db1528a..c23bc71d1 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -11,6 +11,7 @@ pub struct PluginInfo<'lua> { pub name: String, pub repository: String, pub author: String, + pub version: String, pub on_init: Option>, pub on_load: Option>, @@ -24,6 +25,7 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { name: String::default(), repository: String::default(), author: String::default(), + version: String::from("0.1.0"), on_init: None, on_load: None, @@ -40,6 +42,9 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { if let Ok(v) = tab.get::<_, String>("author") { res.author = v; } + if let Ok(v) = tab.get::<_, String>("version") { + res.version = v; + } if let Ok(v) = tab.get::<_, Function>("on_init") { res.on_init = Some(v); @@ -68,6 +73,7 @@ impl<'lua> ToLua<'lua> for PluginInfo<'lua> { res.set("name", self.name.to_string())?; res.set("repository", self.repository.to_string())?; res.set("author", self.author.to_string())?; + res.set("version", self.version.to_string())?; if let Some(e) = self.on_init { res.set("on_init", e)?; From f915a38ad4a1f352a73642823a46718d15b1569b Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 2 Aug 2022 15:22:48 +0800 Subject: [PATCH 17/48] feat: commit plugin init --- src/plugin/interface/fs.rs | 7 ++++++- src/plugin/interface/mod.rs | 2 +- src/plugin/mod.rs | 37 ++++++++++++++++++++++++++++++++----- 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs index 13b5e928e..3557c343a 100644 --- a/src/plugin/interface/fs.rs +++ b/src/plugin/interface/fs.rs @@ -1,5 +1,5 @@ use std::{ - fs::{create_dir, create_dir_all}, + fs::{create_dir, create_dir_all, remove_dir_all}, path::PathBuf, io::{Read, Write}, }; @@ -34,6 +34,11 @@ impl UserData for PluginFileSystem { } Ok(true) }); + methods.add_function("remove_dir", |_, path: String| { + let path = PathBuf::from(path); + let r = remove_dir_all(path); + Ok(r.is_ok()) + }); methods.add_function("file_get_content", |_, path: String| { let path = PathBuf::from(path); let mut file = std::fs::File::open(path)?; diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index c23bc71d1..b5f0b2f30 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -6,7 +6,7 @@ pub mod fs; pub mod download; pub mod dirs; -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct PluginInfo<'lua> { pub name: String, pub repository: String, diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 090dbc6f1..1fca4874a 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -1,7 +1,11 @@ -use std::{io::Read, path::PathBuf}; +use std::{ + io::{Read, Write}, + path::PathBuf, +}; use mlua::{Lua, Table}; use serde::{Deserialize, Serialize}; +use serde_json::json; use crate::tools::{app_path, clone_repo}; @@ -46,7 +50,8 @@ impl PluginManager { lua.globals().set("PLUGIN_DIRS", PluginDirs).unwrap(); let plugin_dir = Self::init_plugin_dir(); - let mut index = 1; + let mut index: u32 = 1; + let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); for entry in std::fs::read_dir(&plugin_dir).ok()? { if entry.is_err() { continue; @@ -60,7 +65,14 @@ impl PluginManager { let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); let info = lua.load(&buffer).eval::().unwrap(); - let _ = manager.set(index, info); + let _ = manager.set(index, info.clone()); + + // call `on_init` if file "dcp.json" not exists + let dcp_file = plugin_dir.join("dcp.json"); + if !dcp_file.is_file() { + init_list.push((index, dcp_file, info)); + } + index += 1; } } @@ -71,6 +83,22 @@ impl PluginManager { .unwrap(); lua.globals().set("manager", manager).unwrap(); + for (idx, path, info) in init_list { + let res = lua.load(&format!("manager[{idx}].on_init()")).exec(); + if res.is_ok() { + let mut file = std::fs::File::create(path).unwrap(); + let buffer = json!({ + "name": info.name, + "author": info.author, + "repository": info.repository, + "version": info.version, + }) + .to_string(); + let buffer = buffer.as_bytes(); + file.write_all(buffer).unwrap(); + } + } + Some(Self { lua }) } @@ -78,8 +106,7 @@ impl PluginManager { let lua = &self.lua; let manager = lua.globals().get::<_, Table>("manager")?; for i in 1..(manager.len()? as i32 + 1) { - let v = manager.get::(i)?; - println!("{v:?}"); + let _ = manager.get::(i)?; let code = format!("manager[{i}].on_load()"); lua.load(&code).exec()?; } From d8506301eb6b8b869242276a1c35edb1c09eeb4e Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 2 Aug 2022 17:23:53 +0800 Subject: [PATCH 18/48] feat: commit generate info --- src/plugin/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 1fca4874a..7bda5b105 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -87,13 +87,14 @@ impl PluginManager { let res = lua.load(&format!("manager[{idx}].on_init()")).exec(); if res.is_ok() { let mut file = std::fs::File::create(path).unwrap(); - let buffer = json!({ + let value = json!({ "name": info.name, "author": info.author, "repository": info.repository, "version": info.version, - }) - .to_string(); + "generate_time": chrono::Local::now().timestamp(), + }); + let buffer = serde_json::to_string_pretty(&value).unwrap(); let buffer = buffer.as_bytes(); file.write_all(buffer).unwrap(); } From b28043a944a953c90ee1d95de625e00c64226272 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sat, 13 Aug 2022 15:21:34 -0700 Subject: [PATCH 19/48] feat: commit `unzip_file` function --- src/plugin/interface/fs.rs | 11 +++++++++++ src/tools.rs | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs index 3557c343a..562448637 100644 --- a/src/plugin/interface/fs.rs +++ b/src/plugin/interface/fs.rs @@ -5,6 +5,8 @@ use std::{ use mlua::UserData; +use crate::tools::extract_zip; + pub struct PluginFileSystem; impl UserData for PluginFileSystem { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { @@ -54,5 +56,14 @@ impl UserData for PluginFileSystem { file.write_all(content.as_bytes())?; Ok(()) }); + methods.add_function("unzip_file", |_, args: (String, String)| { + let file = PathBuf::from(args.0); + let target = PathBuf::from(args.1); + let res = extract_zip(&file, &target); + if let Err(e) = res { + return Err(mlua::Error::RuntimeError(e.to_string())); + } + Ok(()) + }); } } diff --git a/src/tools.rs b/src/tools.rs index 3f95ccac1..a8266c8ec 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -313,7 +313,7 @@ impl Tool { } } -fn extract_zip(file: &Path, target: &Path) -> anyhow::Result<()> { +pub fn extract_zip(file: &Path, target: &Path) -> anyhow::Result<()> { let zip_file = std::fs::File::open(&file)?; let mut zip = zip::ZipArchive::new(zip_file)?; From 6f4028f065da22830767e926a86df0fb66afa1d3 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 14 Aug 2022 18:30:34 -0700 Subject: [PATCH 20/48] feat: make new plugin api --- src/plugin/interface/dirs.rs | 18 +---------- src/plugin/interface/{logger.rs => log.rs} | 0 src/plugin/interface/mod.rs | 6 ++-- .../interface/{download.rs => network.rs} | 4 +-- src/plugin/interface/os.rs | 20 ++++++++++++ src/plugin/interface/path.rs | 14 ++++++++ src/plugin/mod.rs | 32 ++++++++++++------- 7 files changed, 62 insertions(+), 32 deletions(-) rename src/plugin/interface/{logger.rs => log.rs} (100%) rename src/plugin/interface/{download.rs => network.rs} (92%) create mode 100644 src/plugin/interface/os.rs create mode 100644 src/plugin/interface/path.rs diff --git a/src/plugin/interface/dirs.rs b/src/plugin/interface/dirs.rs index 914ed60bb..7837482dc 100644 --- a/src/plugin/interface/dirs.rs +++ b/src/plugin/interface/dirs.rs @@ -5,25 +5,9 @@ use crate::tools::app_path; pub struct PluginDirs; impl UserData for PluginDirs { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { - methods.add_function("plugin_dir", |_, ()| { + methods.add_function("plugins_dir", |_, ()| { let path = app_path().join("plugins"); Ok(path.to_str().unwrap().to_string()) }); - methods.add_function("self_dir", |_, name: String| { - let path = app_path().join("plugins").join(name); - Ok(path.to_str().unwrap().to_string()) - }); - methods.add_function("document_dir", |_, ()| { - let path = dirs::document_dir().unwrap().to_str().unwrap().to_string(); - Ok(path) - }); - methods.add_function("download_dir", |_, ()| { - let path = dirs::download_dir().unwrap().to_str().unwrap().to_string(); - Ok(path) - }); - methods.add_function("cache_dir", |_, ()| { - let path = dirs::cache_dir().unwrap().to_str().unwrap().to_string(); - Ok(path) - }); } } \ No newline at end of file diff --git a/src/plugin/interface/logger.rs b/src/plugin/interface/log.rs similarity index 100% rename from src/plugin/interface/logger.rs rename to src/plugin/interface/log.rs diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index b5f0b2f30..6ac9730e1 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -1,10 +1,12 @@ use mlua::{FromLua, Function, ToLua}; -pub mod logger; +pub mod log; pub mod command; pub mod fs; -pub mod download; +pub mod network; pub mod dirs; +pub mod path; +pub mod os; #[derive(Debug, Clone)] pub struct PluginInfo<'lua> { diff --git a/src/plugin/interface/download.rs b/src/plugin/interface/network.rs similarity index 92% rename from src/plugin/interface/download.rs rename to src/plugin/interface/network.rs index 2edc68c9d..af6b6ae12 100644 --- a/src/plugin/interface/download.rs +++ b/src/plugin/interface/network.rs @@ -2,8 +2,8 @@ use std::{io::Cursor, path::PathBuf}; use mlua::UserData; -pub struct PluginDownloader; -impl UserData for PluginDownloader { +pub struct PluginNetwork; +impl UserData for PluginNetwork { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { methods.add_async_function("download_file", |_, args: (String, String)| async move { let url = args.0; diff --git a/src/plugin/interface/os.rs b/src/plugin/interface/os.rs new file mode 100644 index 000000000..f533a0ae9 --- /dev/null +++ b/src/plugin/interface/os.rs @@ -0,0 +1,20 @@ +use std::path::PathBuf; + +use mlua::UserData; + +pub struct PluginOS; +impl UserData for PluginOS { + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_function("current_platform", |_, ()| { + if cfg!(target_os = "windows") { + Ok("windows") + } else if cfg!(target_os = "macos") { + Ok("macos") + } else if cfg!(target_os = "linux") { + Ok("linux") + } else { + panic!("unsupported platformm"); + } + }); + } +} \ No newline at end of file diff --git a/src/plugin/interface/path.rs b/src/plugin/interface/path.rs new file mode 100644 index 000000000..66584cc52 --- /dev/null +++ b/src/plugin/interface/path.rs @@ -0,0 +1,14 @@ +use std::path::PathBuf; + +use mlua::UserData; + +pub struct PluginPath; +impl UserData for PluginPath { + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_function("join", |_, args: (String, String)| { + let current_path = PathBuf::from(args.0); + let new_path = current_path.join(args.1); + Ok(new_path.to_str().unwrap().to_string()) + }); + } +} \ No newline at end of file diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 7bda5b105..7bca24c97 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -12,8 +12,8 @@ use crate::tools::{app_path, clone_repo}; use self::{ interface::PluginInfo, interface::{ - command::PluginCommander, dirs::PluginDirs, download::PluginDownloader, - fs::PluginFileSystem, logger::PluginLogger, + command::PluginCommander, dirs::PluginDirs, fs::PluginFileSystem, log::PluginLogger, + network::PluginNetwork, }, }; @@ -39,15 +39,25 @@ impl PluginManager { let manager = lua.create_table().unwrap(); - lua.globals().set("PLUGIN_LOGGER", PluginLogger).unwrap(); - lua.globals() - .set("PLUGIN_COMMAND", PluginCommander) - .unwrap(); - lua.globals().set("PLUGIN_FS", PluginFileSystem).unwrap(); - lua.globals() - .set("PLUGIN_DOWNLOAD", PluginDownloader) - .unwrap(); - lua.globals().set("PLUGIN_DIRS", PluginDirs).unwrap(); + let api = lua.create_table().unwrap(); + + api.set("log", PluginLogger).unwrap(); + api.set("command", PluginCommander).unwrap(); + api.set("network", PluginNetwork).unwrap(); + api.set("dirs", PluginDirs).unwrap(); + api.set("fs", PluginFileSystem).unwrap(); + + lua.globals().set("plugin_lib", api).unwrap(); + + // lua.globals().set("PLUGIN_LOGGER", PluginLogger).unwrap(); + // lua.globals() + // .set("PLUGIN_COMMAND", PluginCommander) + // .unwrap(); + // lua.globals().set("PLUGIN_FS", PluginFileSystem).unwrap(); + // lua.globals() + // .set("PLUGIN_DOWNLOAD", PluginDownloader) + // .unwrap(); + // lua.globals().set("PLUGIN_DIRS", PluginDirs).unwrap(); let plugin_dir = Self::init_plugin_dir(); let mut index: u32 = 1; From d9891d9f0c492b8440140dcc74b7999341a555cb Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Thu, 18 Aug 2022 15:54:42 -0700 Subject: [PATCH 21/48] feat: commit `build` field --- Cargo.lock | 333 +++++++++++++++--------------------- src/cli/build/mod.rs | 6 +- src/cli/mod.rs | 14 ++ src/main.rs | 4 +- src/plugin/argument/mod.rs | 0 src/plugin/interface/mod.rs | 77 ++++++--- src/plugin/interface/os.rs | 2 - src/plugin/mod.rs | 55 ++++-- src/server/mod.rs | 6 +- 9 files changed, 249 insertions(+), 248 deletions(-) create mode 100644 src/plugin/argument/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 97e4d0a6f..a7644663c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,7 +26,7 @@ dependencies = [ "cfg-if", "cipher", "cpufeatures", - "opaque-debug 0.3.0", + "opaque-debug", ] [[package]] @@ -39,10 +39,19 @@ dependencies = [ ] [[package]] -name = "anyhow" -version = "1.0.58" +name = "android_system_properties" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb07d2053ccdbe10e2af2995a2f116c1330396493dc1269f6a91d0ae82e19704" +checksum = "d7ed72e1635e121ca3e79420540282af22da58be50de153d36f81ddc6b83aa9e" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "508b352bb5c066aac251f6daf6b36eccd03e8a88e8081cd44959ea277a3af9a8" [[package]] name = "arrayref" @@ -58,9 +67,9 @@ checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" [[package]] name = "async-trait" -version = "0.1.56" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96cf8829f67d2eab0b2dfa42c5d0ef737e0724e4a82b01b3e292456202b19716" +checksum = "76464446b8bc32758d7e88ee1a804d9914cd9b1cb264c029899680b0be29826f" dependencies = [ "proc-macro2", "quote", @@ -86,9 +95,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.5.14" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c943a505c17b494638a38a9af129067f760c9c06794b9f57d499266909be8e72" +checksum = "9de18bc5f2e9df8f52da03856bf40e29b747de5a84e43aefff90e3dc4a21529b" dependencies = [ "async-trait", "axum-core", @@ -109,7 +118,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sha-1 0.10.0", + "sha-1", "sync_wrapper", "tokio", "tokio-tungstenite", @@ -204,34 +213,13 @@ dependencies = [ "constant_time_eq", ] -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding", - "byte-tools", - "byteorder", - "generic-array 0.12.4", -] - [[package]] name = "block-buffer" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" dependencies = [ - "generic-array 0.14.5", -] - -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", + "generic-array", ] [[package]] @@ -249,12 +237,6 @@ version = "3.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3" -[[package]] -name = "byte-tools" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" - [[package]] name = "byteorder" version = "1.4.3" @@ -263,9 +245,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0b3de4a0c5e67e16066a0715723abd91edc2f9001d09c46e1dca929351e130e" +checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" [[package]] name = "bzip2" @@ -290,9 +272,9 @@ dependencies = [ [[package]] name = "camino" -version = "1.0.9" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "869119e97797867fd90f5e22af7d0bd274bd4635ebb9eb68c04f3f513ae6c412" +checksum = "88ad0e1e3e88dd237a156ab9f571021b8a158caa0ae44b1968a241efb5144c1e" dependencies = [ "serde", ] @@ -347,14 +329,16 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.19" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" +checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1" dependencies = [ - "libc", + "iana-time-zone", + "js-sys", "num-integer", "num-traits", "time 0.1.44", + "wasm-bindgen", "winapi", ] @@ -364,14 +348,14 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" dependencies = [ - "generic-array 0.14.5", + "generic-array", ] [[package]] name = "clap" -version = "3.2.15" +version = "3.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44bbe24bbd31a185bc2c4f7c2abe80bea13a20d57ee4e55be70ac512bdc76417" +checksum = "29e724a68d9319343bb3328c9cc2dfde263f4b3142ee1059a9980580171c954b" dependencies = [ "atty", "bitflags", @@ -386,9 +370,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "3.2.15" +version = "3.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba52acd3b0a5c33aeada5cdaa3267cdc7c594a98731d4268cdc1532f4264cb4" +checksum = "13547f7012c01ab4a0e8f8967730ada8f9fdf419e8b6c792788f39cf4e46eefa" dependencies = [ "heck 0.4.0", "proc-macro-error", @@ -430,14 +414,13 @@ dependencies = [ [[package]] name = "console" -version = "0.15.0" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28b32d32ca44b70c3e4acd7db1babf555fa026e385fb95f18028f88848b3c31" +checksum = "89eab4d20ce20cea182308bca13088fecea9c05f6776cf287205d41a0ed3c847" dependencies = [ "encode_unicode", "libc", "once_cell", - "regex", "terminal_size", "unicode-width", "winapi", @@ -515,7 +498,7 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ - "generic-array 0.14.5", + "generic-array", "typenum", ] @@ -589,22 +572,13 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ee2393c4a91429dffb4bedf19f4d6abf27d8a732c8ce4980305d782e5426d57" -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - [[package]] name = "digest" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" dependencies = [ - "block-buffer 0.10.2", + "block-buffer", "crypto-common", "subtle", ] @@ -612,7 +586,7 @@ dependencies = [ [[package]] name = "dioxus" version = "0.2.4" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "dioxus-core", "dioxus-core-macro", @@ -670,7 +644,7 @@ dependencies = [ [[package]] name = "dioxus-core" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "backtrace", "bumpalo", @@ -689,7 +663,7 @@ dependencies = [ [[package]] name = "dioxus-core-macro" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "dioxus-rsx", "dioxus-rsx-interpreter", @@ -701,7 +675,7 @@ dependencies = [ [[package]] name = "dioxus-hooks" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "dioxus-core", "futures-channel", @@ -711,7 +685,7 @@ dependencies = [ [[package]] name = "dioxus-html" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "dioxus-core", "enumset", @@ -722,7 +696,7 @@ dependencies = [ [[package]] name = "dioxus-rsx" version = "0.0.0" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "proc-macro2", "quote", @@ -732,7 +706,7 @@ dependencies = [ [[package]] name = "dioxus-rsx-interpreter" version = "0.1.0" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "dioxus-core", "dioxus-hooks", @@ -750,7 +724,7 @@ dependencies = [ [[package]] name = "dioxus-ssr" version = "0.2.1" -source = "git+https://github.com/dioxuslabs/dioxus/#15e9aa1958d45438a537a4bb01da0b79c5a3d54d" +source = "git+https://github.com/dioxuslabs/dioxus/#baf180733871848a178a5397a1e1934c768e04e8" dependencies = [ "dioxus-core", ] @@ -865,12 +839,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "fake-simd" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" - [[package]] name = "fastrand" version = "1.8.0" @@ -960,9 +928,9 @@ dependencies = [ [[package]] name = "futures" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f73fe65f54d1e12b726f517d3e2135ca3125a437b6d998caf1962961f7172d9e" +checksum = "ab30e97ab6aacfe635fad58f22c2bb06c8b685f7421eb1e064a729e2a5f481fa" dependencies = [ "futures-channel", "futures-core", @@ -975,9 +943,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3083ce4b914124575708913bca19bfe887522d6e2e6d0952943f5eac4a74010" +checksum = "2bfc52cbddcfd745bf1740338492bb0bd83d76c67b445f91c5fb29fae29ecaa1" dependencies = [ "futures-core", "futures-sink", @@ -985,15 +953,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3" +checksum = "d2acedae88d38235936c3922476b10fced7b2b68136f5e3c03c2d5be348a1115" [[package]] name = "futures-executor" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9420b90cfa29e327d0429f19be13e7ddb68fa1cccb09d65e5706b8c7a749b8a6" +checksum = "1d11aa21b5b587a64682c0094c2bdd4df0076c5324961a40cc3abd7f37930528" dependencies = [ "futures-core", "futures-task", @@ -1002,15 +970,15 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" +checksum = "93a66fc6d035a26a3ae255a6d2bca35eda63ae4c5512bef54449113f7a1228e5" [[package]] name = "futures-macro" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" +checksum = "0db9cce532b0eae2ccf2766ab246f114b56b9cf6d445e00c2549fbc100ca045d" dependencies = [ "proc-macro2", "quote", @@ -1019,21 +987,21 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21163e139fa306126e6eedaf49ecdb4588f939600f0b1e770f4205ee4b7fa868" +checksum = "ca0bae1fe9752cf7fd9b0064c674ae63f97b37bc714d745cbde0afb7ec4e6765" [[package]] name = "futures-task" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c66a976bf5909d801bbef33416c41372779507e7a6b3a5e25e4749c58f776a" +checksum = "842fc63b931f4056a24d59de13fb1272134ce261816e063e634ad0c15cdc5306" [[package]] name = "futures-util" -version = "0.3.21" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b7abd5d659d9b90c8cba917f6ec750a74e2dc23902ef9cd4cc8c8b22e6036a" +checksum = "f0828a5471e340229c11c77ca80017937ce3c58cb788a17e5f1c2d5c485a9577" dependencies = [ "futures-channel", "futures-core", @@ -1058,18 +1026,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.12.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" +checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9" dependencies = [ "typenum", "version_check", @@ -1141,7 +1100,7 @@ dependencies = [ "http", "httpdate", "mime", - "sha-1 0.10.0", + "sha-1", ] [[package]] @@ -1189,7 +1148,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest 0.10.3", + "digest", ] [[package]] @@ -1307,6 +1266,19 @@ dependencies = [ "tokio-native-tls", ] +[[package]] +name = "iana-time-zone" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808cf7d67cf4a22adc5be66e75ebdf769b3f2ea032041437a7061f97a63dad4b" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "js-sys", + "wasm-bindgen", + "winapi", +] + [[package]] name = "id-arena" version = "2.2.1" @@ -1342,9 +1314,9 @@ dependencies = [ [[package]] name = "indicatif" -version = "0.17.0-rc.11" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4017d0ce94b8e91e29d2c78ed891e57e5ec3dc4371820a9d96abab4af09eb8ad" +checksum = "fcc42b206e70d86ec03285b123e65a5458c92027d1fb2ae3555878b8113b3ddf" dependencies = [ "console", "number_prefix", @@ -1409,9 +1381,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" +checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" [[package]] name = "jobserver" @@ -1476,9 +1448,9 @@ checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" [[package]] name = "libc" -version = "0.2.126" +version = "0.2.131" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" +checksum = "04c3b4822ccebfa39c02fc03d1534441b22ead323fa0f48bb7ddd8e6ba076a40" [[package]] name = "libz-sys" @@ -1543,19 +1515,13 @@ dependencies = [ [[package]] name = "luajit-src" -version = "210.4.0+resty124ff8d" +version = "210.4.1+restyaa7a722" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f76fb2e2c0c7192e18719d321c9a148f7625c4dcbe3df5f4c19e685e4c286f6c" +checksum = "c92879345f9a97ee140cfe2e08eff49b101533d784527d46ce6d2dc0096d27b3" dependencies = [ "cc", ] -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - [[package]] name = "match_cfg" version = "0.1.0" @@ -1619,9 +1585,9 @@ dependencies = [ [[package]] name = "mlua" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb4815a6d6a3bd1c23e6c647f7df18c9800c12e80526a98e18d7decd7cedcd" +checksum = "10277581090f5cb7ecf814bc611152ce4db6dc8deffcaa08e24ed4c5197d9186" dependencies = [ "bstr", "cc", @@ -1656,9 +1622,9 @@ dependencies = [ [[package]] name = "notify" -version = "5.0.0-pre.15" +version = "5.0.0-pre.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "553f9844ad0b0824605c20fb55a661679782680410abfb1a8144c2e7e437e7a7" +checksum = "530f6314d6904508082f4ea424a0275cf62d341e118b313663f266429cb19693" dependencies = [ "bitflags", "crossbeam-channel", @@ -1732,12 +1698,6 @@ version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" -[[package]] -name = "opaque-debug" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" - [[package]] name = "opaque-debug" version = "0.3.0" @@ -1791,9 +1751,9 @@ dependencies = [ [[package]] name = "os_str_bytes" -version = "6.2.0" +version = "6.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "648001efe5d5c0102d8cea768e348da85d90af8ba91f0bea908f157951493cd4" +checksum = "9ff7415e9ae3fff1225851df9e0d9e4e5479f947619774677a63572e55e80eff" [[package]] name = "parking_lot" @@ -1835,7 +1795,7 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271779f35b581956db91a3e55737327a03aa051e90b1c47aeb189508533adfd7" dependencies = [ - "digest 0.10.3", + "digest", "hmac", "password-hash", "sha2", @@ -1849,18 +1809,19 @@ checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] name = "pest" -version = "2.1.3" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" +checksum = "69486e2b8c2d2aeb9762db7b4e00b0331156393555cff467f4163ff06821eef8" dependencies = [ + "thiserror", "ucd-trie", ] [[package]] name = "pest_derive" -version = "2.1.0" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "833d1ae558dc601e9a60366421196a8d94bc0ac980476d0b67e1d0988d72b2d0" +checksum = "b13570633aff33c6d22ce47dd566b10a3b9122c2fe9d8e7501895905be532b91" dependencies = [ "pest", "pest_generator", @@ -1868,9 +1829,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.1.3" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55" +checksum = "b3c567e5702efdc79fb18859ea74c3eb36e14c43da7b8c1f098a4ed6514ec7a0" dependencies = [ "pest", "pest_meta", @@ -1881,13 +1842,13 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.1.3" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54be6e404f5317079812fc8f9f5279de376d8856929e21c184ecf6bbd692a11d" +checksum = "5eb32be5ee3bbdafa8c7a18b0a8a8d962b66cfa2ceee4037f49267a50ee821fe" dependencies = [ - "maplit", + "once_cell", "pest", - "sha-1 0.8.2", + "sha-1", ] [[package]] @@ -1960,9 +1921,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.42" +version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c278e965f1d8cf32d6e0e96de3d3e79712178ae67986d9cf9151f51e95aac89b" +checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" dependencies = [ "unicode-ident", ] @@ -1975,9 +1936,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quote" -version = "1.0.20" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] @@ -2182,18 +2143,18 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7522c9de787ff061458fe9a829dc790a3f5b22dc571694fc5883f448b94d9a9" +checksum = "0864aeff53f8c05aa08d86e5ef839d3dfcf07aeba2db32f12db0ef716e87bd55" dependencies = [ "base64 0.13.0", ] [[package]] name = "ryu" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" +checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" [[package]] name = "safemem" @@ -2261,27 +2222,27 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.12" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2333e6df6d6598f2b1974829f853c2b4c5f4a6e503c10af918081aa6f8564e1" +checksum = "93f6841e709003d68bb2deee8c343572bf446003ec20a583e76f7b15cebf3711" dependencies = [ "serde", ] [[package]] name = "serde" -version = "1.0.140" +version = "1.0.143" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03" +checksum = "53e8e5d5b70924f74ff5c6d64d9a5acd91422117c60f48c4e07855238a254553" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.140" +version = "1.0.143" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f2122636b9fe3b81f1cb25099fcf2d3f542cdb1d45940d56c713158884a05da" +checksum = "d3d8e8de557aee63c26b85b947f5e59b690d0454c753f3adeb5cd7835ab88391" dependencies = [ "proc-macro2", "quote", @@ -2290,9 +2251,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.82" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82c2c1fdcd807d1098552c5b9a36e425e42e9fbd7c6a37a8425f390f781f7fa7" +checksum = "38dd04e3c8279e75b31ef29dbdceebfe5ad89f4d0937213c53f7d49d01b3d5a7" dependencies = [ "itoa", "ryu", @@ -2311,18 +2272,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha-1" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d94d0bede923b3cea61f3f1ff57ff8cdfd77b400fb8f9998949e0cf04163df" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "fake-simd", - "opaque-debug 0.2.3", -] - [[package]] name = "sha-1" version = "0.10.0" @@ -2331,7 +2280,7 @@ checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" dependencies = [ "cfg-if", "cpufeatures", - "digest 0.10.3", + "digest", ] [[package]] @@ -2342,7 +2291,7 @@ checksum = "c77f4e7f65455545c2153c1253d25056825e77ee2533f0e41deb65a93a34852f" dependencies = [ "cfg-if", "cpufeatures", - "digest 0.10.3", + "digest", ] [[package]] @@ -2353,7 +2302,7 @@ checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" dependencies = [ "cfg-if", "cpufeatures", - "digest 0.10.3", + "digest", ] [[package]] @@ -2416,9 +2365,9 @@ checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" [[package]] name = "syn" -version = "1.0.98" +version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" +checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" dependencies = [ "proc-macro2", "quote", @@ -2495,18 +2444,18 @@ checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" [[package]] name = "thiserror" -version = "1.0.31" +version = "1.0.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" +checksum = "f5f6586b7f764adc0231f4c79be7b920e766bb2f3e51b3661cdb263828f19994" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.31" +version = "1.0.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" +checksum = "12bafc5b54507e0149cdf1b145a5d80ab80a90bcd9275df43d4fff68460f6c21" dependencies = [ "proc-macro2", "quote", @@ -2526,9 +2475,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.11" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72c91f41dcb2f096c05f0873d667dceec1087ce5bcf984ec8ffb19acddbb3217" +checksum = "db76ff9fa4b1458b3c7f077f3ff9887394058460d21e634355b273aaf11eea45" dependencies = [ "itoa", "libc", @@ -2719,9 +2668,9 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.35" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a400e31aa60b9d44a52a8ee0343b5b18566b03a8321e0d321f695cf56e940160" +checksum = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307" dependencies = [ "cfg-if", "log", @@ -2731,9 +2680,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.28" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b7358be39f2f274f322d2aaed611acc57f382e8eb1e5b48cb9ae30933495ce7" +checksum = "5aeea4303076558a00714b823f9ad67d58a3bbda1df83d8827d21193156e22f7" dependencies = [ "once_cell", ] @@ -2802,7 +2751,7 @@ dependencies = [ "httparse", "log", "rand", - "sha-1 0.10.0", + "sha-1", "thiserror", "url", "utf-8", @@ -2837,9 +2786,9 @@ checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" [[package]] name = "unicode-ident" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" +checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" [[package]] name = "unicode-normalization" @@ -3363,7 +3312,7 @@ dependencies = [ "hmac", "pbkdf2", "sha1", - "time 0.3.11", + "time 0.3.13", "zstd", ] diff --git a/src/cli/build/mod.rs b/src/cli/build/mod.rs index f857bfc13..42fcc4c0a 100644 --- a/src/cli/build/mod.rs +++ b/src/cli/build/mod.rs @@ -1,3 +1,5 @@ +use crate::plugin::PluginManager; + use super::*; /// Build the Rust WASM app and all of its assets. @@ -9,7 +11,7 @@ pub struct Build { } impl Build { - pub fn build(self) -> Result<()> { + pub fn build(self, plugin_manager: PluginManager) -> Result<()> { let mut crate_config = crate::CrateConfig::new()?; // change the release state. @@ -32,6 +34,8 @@ impl Build { .clone() }); + let _ = plugin_manager.on_build_event(&crate_config, &platform); + match platform.as_str() { "web" => { crate::builder::build(&crate_config, false)?; diff --git a/src/cli/mod.rs b/src/cli/mod.rs index b456d4705..818b3fa8f 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -56,3 +56,17 @@ pub enum Commands { #[clap(subcommand)] Tool(tool::Tool), } + +impl Commands { + pub fn to_string(&self) -> String { + match self { + Commands::Build(_) => "build", + Commands::Translate(_) => "translate", + Commands::Serve(_) => "sevre", + Commands::Create(_) => "create", + Commands::Clean(_) => "clean", + Commands::Config(_) => "config", + Commands::Tool(_) => "tool", + }.to_string() + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index bc36e1071..7758c6a63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,8 +11,6 @@ async fn main() -> Result<()> { required: vec![], }).unwrap(); - plugin_manager.load_all_plugins().unwrap(); - match args.action { Commands::Translate(opts) => { if let Err(e) = opts.translate() { @@ -21,7 +19,7 @@ async fn main() -> Result<()> { } Commands::Build(opts) => { - if let Err(e) = opts.build() { + if let Err(e) = opts.build(plugin_manager) { log::error!("🚫 Build project failed: {}", e); } } diff --git a/src/plugin/argument/mod.rs b/src/plugin/argument/mod.rs new file mode 100644 index 000000000..e69de29bb diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index 6ac9730e1..e5abeafb6 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -1,12 +1,12 @@ use mlua::{FromLua, Function, ToLua}; -pub mod log; pub mod command; -pub mod fs; -pub mod network; pub mod dirs; -pub mod path; +pub mod fs; +pub mod log; +pub mod network; pub mod os; +pub mod path; #[derive(Debug, Clone)] pub struct PluginInfo<'lua> { @@ -16,9 +16,7 @@ pub struct PluginInfo<'lua> { pub version: String, pub on_init: Option>, - pub on_load: Option>, - pub on_build_start: Option>, - pub on_build_finish: Option>, + pub build: PluginBuildInfo<'lua>, } impl<'lua> FromLua<'lua> for PluginInfo<'lua> { @@ -30,9 +28,7 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { version: String::from("0.1.0"), on_init: None, - on_load: None, - on_build_start: None, - on_build_finish: None, + build: Default::default(), }; if let mlua::Value::Table(tab) = lua_value { if let Ok(v) = tab.get::<_, String>("name") { @@ -51,16 +47,6 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { if let Ok(v) = tab.get::<_, Function>("on_init") { res.on_init = Some(v); } - if let Ok(v) = tab.get::<_, Function>("on_load") { - res.on_load = Some(v); - } - if let Ok(v) = tab.get::<_, Function>("on_build_start") { - res.on_build_start = Some(v); - } - if let Ok(v) = tab.get::<_, Function>("on_build_finish") { - res.on_build_finish = Some(v); - } - } Ok(res) @@ -69,9 +55,8 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { impl<'lua> ToLua<'lua> for PluginInfo<'lua> { fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { - let res = lua.create_table()?; - + res.set("name", self.name.to_string())?; res.set("repository", self.repository.to_string())?; res.set("author", self.author.to_string())?; @@ -80,14 +65,50 @@ impl<'lua> ToLua<'lua> for PluginInfo<'lua> { if let Some(e) = self.on_init { res.set("on_init", e)?; } - if let Some(e) = self.on_load { - res.set("on_load", e)?; + res.set("build", self.build)?; + + Ok(mlua::Value::Table(res)) + } +} + +#[derive(Debug, Clone, Default)] +pub struct PluginBuildInfo<'lua> { + pub on_start: Option>, + pub on_finish: Option>, +} + +impl<'lua> FromLua<'lua> for PluginBuildInfo<'lua> { + fn from_lua(lua_value: mlua::Value<'lua>, _lua: &'lua mlua::Lua) -> mlua::Result { + let mut res = Self { + on_start: None, + on_finish: None, + }; + + if let mlua::Value::Table(t) = lua_value { + if let Ok(v) = t.get::<_, Function>("on_start") { + res.on_start = Some(v); + } + if let Ok(v) = t.get::<_, Function>("on_finish") { + res.on_finish = Some(v); + } } - if let Some(e) = self.on_build_start { - res.set("on_build_start", e)?; + + Ok(res) + } +} + +impl<'lua> ToLua<'lua> for PluginBuildInfo<'lua> { + fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { + + let res = lua.create_table()?; + + + if let Some(v) = self.on_start { + res.set("on_start", v)?; } - if let Some(e) = self.on_build_finish { - res.set("on_build_finish", e)?; + + if let Some(v) = self.on_finish { + res.set("on_finish", v)?; } Ok(mlua::Value::Table(res)) diff --git a/src/plugin/interface/os.rs b/src/plugin/interface/os.rs index f533a0ae9..33368f38a 100644 --- a/src/plugin/interface/os.rs +++ b/src/plugin/interface/os.rs @@ -1,5 +1,3 @@ -use std::path::PathBuf; - use mlua::UserData; pub struct PluginOS; diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 7bca24c97..b4de68d4c 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -3,20 +3,21 @@ use std::{ path::PathBuf, }; -use mlua::{Lua, Table}; +use mlua::{AsChunk, Lua, Table}; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::tools::{app_path, clone_repo}; +use crate::{tools::{app_path, clone_repo}, CrateConfig}; use self::{ interface::PluginInfo, interface::{ command::PluginCommander, dirs::PluginDirs, fs::PluginFileSystem, log::PluginLogger, - network::PluginNetwork, + network::PluginNetwork, os::PluginOS, path::PluginPath, }, }; +pub mod argument; pub mod interface; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -38,6 +39,7 @@ impl PluginManager { let lua = Lua::new(); let manager = lua.create_table().unwrap(); + let plugin_dir = Self::init_plugin_dir(); let api = lua.create_table().unwrap(); @@ -46,20 +48,14 @@ impl PluginManager { api.set("network", PluginNetwork).unwrap(); api.set("dirs", PluginDirs).unwrap(); api.set("fs", PluginFileSystem).unwrap(); + api.set("path", PluginPath).unwrap(); + api.set("os", PluginOS).unwrap(); lua.globals().set("plugin_lib", api).unwrap(); + lua.globals() + .set("library_dir", plugin_dir.to_str().unwrap()) + .unwrap(); - // lua.globals().set("PLUGIN_LOGGER", PluginLogger).unwrap(); - // lua.globals() - // .set("PLUGIN_COMMAND", PluginCommander) - // .unwrap(); - // lua.globals().set("PLUGIN_FS", PluginFileSystem).unwrap(); - // lua.globals() - // .set("PLUGIN_DOWNLOAD", PluginDownloader) - // .unwrap(); - // lua.globals().set("PLUGIN_DIRS", PluginDirs).unwrap(); - - let plugin_dir = Self::init_plugin_dir(); let mut index: u32 = 1; let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); for entry in std::fs::read_dir(&plugin_dir).ok()? { @@ -77,6 +73,9 @@ impl PluginManager { let info = lua.load(&buffer).eval::().unwrap(); let _ = manager.set(index, info.clone()); + let dir_name_str = plugin_dir.name().unwrap().to_string(); + lua.globals().set("current_dir_name", dir_name_str).unwrap(); + // call `on_init` if file "dcp.json" not exists let dcp_file = plugin_dir.join("dcp.json"); if !dcp_file.is_file() { @@ -88,9 +87,6 @@ impl PluginManager { } } - lua.globals() - .set("LIBDIR", plugin_dir.join("library").to_str().unwrap()) - .unwrap(); lua.globals().set("manager", manager).unwrap(); for (idx, path, info) in init_list { @@ -113,14 +109,35 @@ impl PluginManager { Some(Self { lua }) } - pub fn load_all_plugins(&self) -> anyhow::Result<()> { + // pub fn load_all_plugins(&self) -> anyhow::Result<()> { + // let lua = &self.lua; + // let manager = lua.globals().get::<_, Table>("manager")?; + // for i in 1..(manager.len()? as i32 + 1) { + // let _ = manager.get::(i)?; + // let code = format!("manager[{i}].on_load()"); + // lua.load(&code).exec()?; + // } + // Ok(()) + // } + + pub fn on_build_event(&self, crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { let lua = &self.lua; + let manager = lua.globals().get::<_, Table>("manager")?; + + let info = json!({ + "name": crate_config.dioxus_config.application.name, + "platform": platform, + "out_dir": crate_config.out_dir.to_str().unwrap(), + "asset_dir": crate_config.asset_dir.to_str().unwrap(), + }); + for i in 1..(manager.len()? as i32 + 1) { let _ = manager.get::(i)?; - let code = format!("manager[{i}].on_load()"); + let code = format!("manager[{i}].build.on_start({})", info.to_string()); lua.load(&code).exec()?; } + Ok(()) } diff --git a/src/server/mod.rs b/src/server/mod.rs index 8acf17848..2298960ff 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -9,7 +9,7 @@ use axum::{ use cargo_metadata::diagnostic::Diagnostic; use colored::Colorize; use dioxus_rsx_interpreter::SetRsxMessage; -use notify::{RecommendedWatcher, Watcher}; +use notify::Watcher; use syn::spanned::Spanned; use std::{net::UdpSocket, path::PathBuf, process::Command, sync::Arc}; @@ -98,7 +98,7 @@ pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { .unwrap_or_else(|| vec![PathBuf::from("src")]); let watcher_config = config.clone(); - let mut watcher = RecommendedWatcher::new(move |evt: notify::Result| { + let mut watcher = notify::recommended_watcher(move |evt: notify::Result| { let config = watcher_config.clone(); if chrono::Local::now().timestamp() > last_update_time { // Give time for the change to take effect before reading the file @@ -304,7 +304,7 @@ pub async fn startup_default(port: u16, config: CrateConfig) -> Result<()> { .unwrap_or_else(|| vec![PathBuf::from("src")]); let watcher_config = config.clone(); - let mut watcher = RecommendedWatcher::new(move |info: notify::Result| { + let mut watcher = notify::recommended_watcher(move |info: notify::Result| { let config = watcher_config.clone(); if info.is_ok() { if chrono::Local::now().timestamp() > last_update_time { From 6c1374edb357ae3551e5c88567abbafc9cd55292 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Mon, 22 Aug 2022 11:00:31 -0700 Subject: [PATCH 22/48] feat: commit code --- Cargo.lock | 11 ++++ Cargo.toml | 2 +- src/cli/build/mod.rs | 4 +- src/plugin/interface/mod.rs | 15 +++++ src/plugin/mod.rs | 113 +++++++++++++++++++++++++----------- src/server/mod.rs | 83 ++++++++++++-------------- 6 files changed, 146 insertions(+), 82 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a7644663c..98c751dcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -808,6 +808,15 @@ dependencies = [ "syn", ] +[[package]] +name = "erased-serde" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "003000e712ad0f95857bd4d2ef8d1890069e06554101697d12050668b2f6f020" +dependencies = [ + "serde", +] + [[package]] name = "euclid" version = "0.22.7" @@ -1591,6 +1600,7 @@ checksum = "10277581090f5cb7ecf814bc611152ce4db6dc8deffcaa08e24ed4c5197d9186" dependencies = [ "bstr", "cc", + "erased-serde", "futures-core", "futures-task", "futures-util", @@ -1600,6 +1610,7 @@ dependencies = [ "once_cell", "pkg-config", "rustc-hash", + "serde", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 2690def1b..1714f4f2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ dioxus-rsx-interpreter = { git = "https://github.com/dioxuslabs/dioxus/" } proc-macro2 = { version = "1.0", features = ["span-locations"] } # plugin packages -mlua = { version = "0.8.1", features = ["lua54", "vendored", "async"] } +mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "serialize"] } [[bin]] path = "src/main.rs" diff --git a/src/cli/build/mod.rs b/src/cli/build/mod.rs index 42fcc4c0a..233878645 100644 --- a/src/cli/build/mod.rs +++ b/src/cli/build/mod.rs @@ -34,7 +34,7 @@ impl Build { .clone() }); - let _ = plugin_manager.on_build_event(&crate_config, &platform); + let _ = plugin_manager.on_build_start(&crate_config, &platform); match platform.as_str() { "web" => { @@ -65,6 +65,8 @@ impl Build { )?; file.write_all(temp.as_bytes())?; + let _ = plugin_manager.on_build_finish(&crate_config, &platform); + Ok(()) } } diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index e5abeafb6..12b5a407d 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -1,4 +1,5 @@ use mlua::{FromLua, Function, ToLua}; +use serde::Serialize; pub mod command; pub mod dirs; @@ -47,6 +48,11 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { if let Ok(v) = tab.get::<_, Function>("on_init") { res.on_init = Some(v); } + + if let Ok(v) = tab.get::<_, PluginBuildInfo>("build") { + res.build = v; + } + } Ok(res) @@ -113,4 +119,13 @@ impl<'lua> ToLua<'lua> for PluginBuildInfo<'lua> { Ok(mlua::Value::Table(res)) } +} + +#[derive(Debug, Clone, Default, Serialize)] +pub struct PluginServeInfo<'lua> { + + pub interval: i32, + + pub on_start: Option>, + pub on_interval: Option>, } \ No newline at end of file diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index b4de68d4c..c1012f3f6 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -3,11 +3,14 @@ use std::{ path::PathBuf, }; -use mlua::{AsChunk, Lua, Table}; +use mlua::{AsChunk, Lua, Table, ToLuaMulti}; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::{tools::{app_path, clone_repo}, CrateConfig}; +use crate::{ + tools::{app_path, clone_repo}, + CrateConfig, +}; use self::{ interface::PluginInfo, @@ -70,19 +73,28 @@ impl PluginManager { let mut file = std::fs::File::open(init_file).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); - let info = lua.load(&buffer).eval::().unwrap(); - let _ = manager.set(index, info.clone()); - let dir_name_str = plugin_dir.name().unwrap().to_string(); - lua.globals().set("current_dir_name", dir_name_str).unwrap(); + let info = lua.load(&buffer).eval::(); + match info { + Ok(info) => { + let _ = manager.set(index, info.clone()); - // call `on_init` if file "dcp.json" not exists - let dcp_file = plugin_dir.join("dcp.json"); - if !dcp_file.is_file() { - init_list.push((index, dcp_file, info)); + let dir_name_str = plugin_dir.name().unwrap().to_string(); + lua.globals().set("current_dir_name", dir_name_str).unwrap(); + + // call `on_init` if file "dcp.json" not exists + let dcp_file = plugin_dir.join("dcp.json"); + if !dcp_file.is_file() { + init_list.push((index, dcp_file, info)); + } + + index += 1; + } + Err(_e) => { + let dir_name = plugin_dir.file_name().unwrap().to_str().unwrap(); + log::error!("Plugin '{dir_name}' load failed."); + } } - - index += 1; } } } @@ -109,33 +121,68 @@ impl PluginManager { Some(Self { lua }) } - // pub fn load_all_plugins(&self) -> anyhow::Result<()> { - // let lua = &self.lua; - // let manager = lua.globals().get::<_, Table>("manager")?; - // for i in 1..(manager.len()? as i32 + 1) { - // let _ = manager.get::(i)?; - // let code = format!("manager[{i}].on_load()"); - // lua.load(&code).exec()?; - // } - // Ok(()) - // } - - pub fn on_build_event(&self, crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { + pub fn on_build_start(&self, crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { let lua = &self.lua; let manager = lua.globals().get::<_, Table>("manager")?; - let info = json!({ - "name": crate_config.dioxus_config.application.name, - "platform": platform, - "out_dir": crate_config.out_dir.to_str().unwrap(), - "asset_dir": crate_config.asset_dir.to_str().unwrap(), - }); + let args = lua.create_table()?; + args.set("name", crate_config.dioxus_config.application.name.clone())?; + args.set("platform", platform)?; + args.set("out_dir", crate_config.out_dir.to_str().unwrap())?; + args.set("asset_dir", crate_config.asset_dir.to_str().unwrap())?; for i in 1..(manager.len()? as i32 + 1) { - let _ = manager.get::(i)?; - let code = format!("manager[{i}].build.on_start({})", info.to_string()); - lua.load(&code).exec()?; + let info = manager.get::(i)?; + if let Some(func) = info.build.on_start { + func.call::(args.clone())?; + } + } + + Ok(()) + } + + pub fn on_build_finish( + &self, + crate_config: &CrateConfig, + platform: &str, + ) -> anyhow::Result<()> { + let lua = &self.lua; + + let manager = lua.globals().get::<_, Table>("manager")?; + + let args = lua.create_table()?; + args.set("name", crate_config.dioxus_config.application.name.clone())?; + args.set("platform", platform)?; + args.set("out_dir", crate_config.out_dir.to_str().unwrap())?; + args.set("asset_dir", crate_config.asset_dir.to_str().unwrap())?; + + for i in 1..(manager.len()? as i32 + 1) { + let info = manager.get::(i)?; + if let Some(func) = info.build.on_finish { + func.call::(args.clone())?; + } + } + + Ok(()) + } + + pub fn call_event<'lua>(&self, event: &str, args: impl ToLuaMulti<'lua>) -> anyhow::Result<()> { + let lua = &self.lua; + + let manager = lua.globals().get::<_, Table>("manager")?; + + for i in 1..(manager.len()? as i32 + 1) { + let info = manager.get::<_, PluginInfo>(i)?; + let func = match event { + "on_init" => info.on_init, + "build.on_start" => info.build.on_start, + _ => None, + }; + + if let Some(func) = func { + func.call(args)?; + } } Ok(()) diff --git a/src/server/mod.rs b/src/server/mod.rs index bf7d5dfbb..eed3834a7 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -151,58 +151,47 @@ pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { } else { *last = last.split_at(end.column).0; } - if let Some(last) = lines.last_mut() { - // if there is only one line the start index of last line will be the start of the rsx!, not the start of the line - if start.line == end.line { - *last = last - .split_at(end.column - start.column) - .0; - } else { - *last = last.split_at(end.column).0; - } - } - let rsx = lines.join("\n"); - messages.push(SetRsxMessage { - location: hr, - new_text: rsx, - }); } + let rsx = lines.join("\n"); + messages.push(SetRsxMessage { + location: hr, + new_text: rsx, + }); } } } - } else { - // if this is a new file, rebuild the project - *last_file_rebuild = FileMap::new(crate_dir.clone()); } + } else { + // if this is a new file, rebuild the project + *last_file_rebuild = FileMap::new(crate_dir.clone()); } } - if needs_rebuild { - match build_manager.rebuild() { - Ok(res) => { - print_console_info( - port, - &config, - PrettierOptions { - changed: evt.paths, - warnings: res.warnings, - elapsed_time: res.elapsed_time, - }, - ); - } - Err(err) => { - log::error!("{}", err); - } - } - } - if !messages.is_empty() { - let _ = hot_reload_tx.send(SetManyRsxMessage(messages)); - } } - last_update_time = chrono::Local::now().timestamp(); + if needs_rebuild { + match build_manager.rebuild() { + Ok(res) => { + print_console_info( + port, + &config, + PrettierOptions { + changed: evt.paths, + warnings: res.warnings, + elapsed_time: res.elapsed_time, + }, + ); + } + Err(err) => { + log::error!("{}", err); + } + } + } + if !messages.is_empty() { + let _ = hot_reload_tx.send(SetManyRsxMessage(messages)); + } } - }, - notify::Config::default(), - ) + last_update_time = chrono::Local::now().timestamp(); + } + }) .unwrap(); for sub_path in allow_watch_path { @@ -332,11 +321,11 @@ pub async fn startup_default(port: u16, config: CrateConfig) -> Result<()> { }, ); } + Err(e) => log::error!("{}", e), } } - }, - notify::Config::default(), - ) + } + }) .unwrap(); for sub_path in allow_watch_path { @@ -610,4 +599,4 @@ async fn ws_handler( reload_watcher.await.unwrap(); }) -} +} \ No newline at end of file From 062d0eab4758b53788856a4a86738d519997c0fe Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 23 Aug 2022 15:41:39 -0700 Subject: [PATCH 23/48] feat: commit `serve` info --- Cargo.lock | 11 ------- Cargo.toml | 2 +- src/plugin/interface/mod.rs | 63 ++++++++++++++++++++++++++++++++----- src/plugin/mod.rs | 21 ------------- 4 files changed, 57 insertions(+), 40 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 98c751dcc..a7644663c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -808,15 +808,6 @@ dependencies = [ "syn", ] -[[package]] -name = "erased-serde" -version = "0.3.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "003000e712ad0f95857bd4d2ef8d1890069e06554101697d12050668b2f6f020" -dependencies = [ - "serde", -] - [[package]] name = "euclid" version = "0.22.7" @@ -1600,7 +1591,6 @@ checksum = "10277581090f5cb7ecf814bc611152ce4db6dc8deffcaa08e24ed4c5197d9186" dependencies = [ "bstr", "cc", - "erased-serde", "futures-core", "futures-task", "futures-util", @@ -1610,7 +1600,6 @@ dependencies = [ "once_cell", "pkg-config", "rustc-hash", - "serde", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1714f4f2d..2690def1b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ dioxus-rsx-interpreter = { git = "https://github.com/dioxuslabs/dioxus/" } proc-macro2 = { version = "1.0", features = ["span-locations"] } # plugin packages -mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "serialize"] } +mlua = { version = "0.8.1", features = ["lua54", "vendored", "async"] } [[bin]] path = "src/main.rs" diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index 12b5a407d..0852f7211 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -1,5 +1,4 @@ use mlua::{FromLua, Function, ToLua}; -use serde::Serialize; pub mod command; pub mod dirs; @@ -52,7 +51,6 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { if let Ok(v) = tab.get::<_, PluginBuildInfo>("build") { res.build = v; } - } Ok(res) @@ -105,10 +103,8 @@ impl<'lua> FromLua<'lua> for PluginBuildInfo<'lua> { impl<'lua> ToLua<'lua> for PluginBuildInfo<'lua> { fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { - let res = lua.create_table()?; - if let Some(v) = self.on_start { res.set("on_start", v)?; } @@ -121,11 +117,64 @@ impl<'lua> ToLua<'lua> for PluginBuildInfo<'lua> { } } -#[derive(Debug, Clone, Default, Serialize)] +#[derive(Debug, Clone, Default)] pub struct PluginServeInfo<'lua> { - pub interval: i32, pub on_start: Option>, pub on_interval: Option>, -} \ No newline at end of file + pub on_rebuild: Option>, + pub on_shutdown: Option>, +} + +impl<'lua> FromLua<'lua> for PluginServeInfo<'lua> { + fn from_lua(lua_value: mlua::Value<'lua>, _lua: &'lua mlua::Lua) -> mlua::Result { + let mut res = Self::default(); + + if let mlua::Value::Table(tab) = lua_value { + if let Ok(v) = tab.get::<_, i32>("interval") { + res.interval = v; + } + if let Ok(v) = tab.get::<_, Function>("on_start") { + res.on_start = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("on_interval") { + res.on_interval = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("on_rebuild") { + res.on_rebuild = Some(v); + } + if let Ok(v) = tab.get::<_, Function>("on_shutdown") { + res.on_shutdown = Some(v); + } + } + + Ok(res) + } +} + +impl<'lua> ToLua<'lua> for PluginServeInfo<'lua> { + fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { + let res = lua.create_table()?; + + res.set("interval", self.interval)?; + + if let Some(v) = self.on_start { + res.set("on_start", v)?; + } + + if let Some(v) = self.on_interval { + res.set("on_interval", v)?; + } + + if let Some(v) = self.on_rebuild { + res.set("on_rebuild", v)?; + } + + if let Some(v) = self.on_shutdown { + res.set("on_shutdown", v)?; + } + + Ok(mlua::Value::Table(res)) + } +} diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index c1012f3f6..45b783281 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -167,27 +167,6 @@ impl PluginManager { Ok(()) } - pub fn call_event<'lua>(&self, event: &str, args: impl ToLuaMulti<'lua>) -> anyhow::Result<()> { - let lua = &self.lua; - - let manager = lua.globals().get::<_, Table>("manager")?; - - for i in 1..(manager.len()? as i32 + 1) { - let info = manager.get::<_, PluginInfo>(i)?; - let func = match event { - "on_init" => info.on_init, - "build.on_start" => info.build.on_start, - _ => None, - }; - - if let Some(func) = func { - func.call(args)?; - } - } - - Ok(()) - } - fn init_plugin_dir() -> PathBuf { let app_path = app_path(); let plugin_path = app_path.join("plugins"); From 6cce4b9f4da055fb75fc555b1fae43be58ba3463 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Fri, 26 Aug 2022 10:27:06 -0700 Subject: [PATCH 24/48] feat: commit code --- src/cli/mod.rs | 8 ++--- src/cli/plugin/mod.rs | 67 +++++++++++++++++++++++++++++++++++++ src/main.rs | 6 ++-- src/plugin/interface/mod.rs | 7 ++++ src/plugin/mod.rs | 2 +- 5 files changed, 82 insertions(+), 8 deletions(-) create mode 100644 src/cli/plugin/mod.rs diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 818b3fa8f..4508982d1 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -4,7 +4,7 @@ pub mod clean; pub mod config; pub mod create; pub mod serve; -pub mod tool; +pub mod plugin; pub mod translate; use crate::{ @@ -52,9 +52,9 @@ pub enum Commands { /// Dioxus config file controls. #[clap(subcommand)] Config(config::Config), - /// Install & Manage tools for Dioxus-cli. #[clap(subcommand)] - Tool(tool::Tool), + /// Manage plugins for dioxus cli + Plugin(plugin::Plugin), } impl Commands { @@ -66,7 +66,7 @@ impl Commands { Commands::Create(_) => "create", Commands::Clean(_) => "clean", Commands::Config(_) => "config", - Commands::Tool(_) => "tool", + Commands::Plugin(_) => "plugin", }.to_string() } } \ No newline at end of file diff --git a/src/cli/plugin/mod.rs b/src/cli/plugin/mod.rs new file mode 100644 index 000000000..aee4b54b0 --- /dev/null +++ b/src/cli/plugin/mod.rs @@ -0,0 +1,67 @@ +use crate::tools; + +use super::*; + +/// Build the Rust WASM app and all of its assets. +#[derive(Clone, Debug, Deserialize, Subcommand)] +#[clap(name = "plugin")] +pub enum Plugin { + /// Return all dioxus-cli support tools. + List {}, + /// Get default app install path. + AppPath {}, + /// Install a new tool. + Add { name: String }, +} + +impl Plugin { + pub async fn plugin(self) -> Result<()> { + match self { + Plugin::List {} => { + for item in tools::tool_list() { + if tools::Tool::from_str(item).unwrap().is_installed() { + println!("- {item} [installed]"); + } else { + println!("- {item}"); + } + } + } + Plugin::AppPath {} => { + if let Some(v) = tools::tools_path().to_str() { + println!("{}", v); + } else { + log::error!("Tools path get failed."); + } + } + Plugin::Add { name } => { + let tool_list = tools::tool_list(); + + if !tool_list.contains(&name.as_str()) { + log::error!("Tool {name} not found."); + return Ok(()); + } + let target_tool = tools::Tool::from_str(&name).unwrap(); + + if target_tool.is_installed() { + log::warn!("Tool {name} is installed."); + return Ok(()); + } + + log::info!("Start to download tool package..."); + if let Err(e) = target_tool.download_package().await { + log::error!("Tool download failed: {e}"); + return Ok(()); + } + + log::info!("Start to install tool package..."); + if let Err(e) = target_tool.install_package().await { + log::error!("Tool install failed: {e}"); + return Ok(()); + } + + log::info!("Tool {name} install successfully!"); + } + } + Ok(()) + } +} diff --git a/src/main.rs b/src/main.rs index 7758c6a63..e7b96d4b5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -48,9 +48,9 @@ async fn main() -> Result<()> { } } - Commands::Tool(opts) => { - if let Err(e) = opts.tool().await { - log::error!("tool error: {}", e); + Commands::Plugin(opts) => { + if let Err(e) = opts.plugin().await { + log::error!("plugin error: {}", e); } } } diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index 0852f7211..2ef1920fc 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -17,6 +17,7 @@ pub struct PluginInfo<'lua> { pub on_init: Option>, pub build: PluginBuildInfo<'lua>, + pub serve: PluginServeInfo<'lua>, } impl<'lua> FromLua<'lua> for PluginInfo<'lua> { @@ -29,6 +30,7 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { on_init: None, build: Default::default(), + serve: Default::default(), }; if let mlua::Value::Table(tab) = lua_value { if let Ok(v) = tab.get::<_, String>("name") { @@ -51,6 +53,10 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { if let Ok(v) = tab.get::<_, PluginBuildInfo>("build") { res.build = v; } + + if let Ok(v) = tab.get::<_, PluginServeInfo>("serve") { + res.serve = v; + } } Ok(res) @@ -70,6 +76,7 @@ impl<'lua> ToLua<'lua> for PluginInfo<'lua> { res.set("on_init", e)?; } res.set("build", self.build)?; + res.set("serve", self.serve)?; Ok(mlua::Value::Table(res)) } diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 45b783281..7f0bd99db 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -3,7 +3,7 @@ use std::{ path::PathBuf, }; -use mlua::{AsChunk, Lua, Table, ToLuaMulti}; +use mlua::{AsChunk, Lua, Table}; use serde::{Deserialize, Serialize}; use serde_json::json; From 603aaa1c0952ad029a162ea4375b6f2a16b80511 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Sat, 27 Aug 2022 10:41:15 -0700 Subject: [PATCH 25/48] feat: plugin `serve` support --- src/cli/serve/mod.rs | 4 +++- src/main.rs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cli/serve/mod.rs b/src/cli/serve/mod.rs index 93770b6ed..bb24c1e83 100644 --- a/src/cli/serve/mod.rs +++ b/src/cli/serve/mod.rs @@ -1,3 +1,5 @@ +use crate::plugin::PluginManager; + use super::*; use std::{ io::Write, @@ -14,7 +16,7 @@ pub struct Serve { } impl Serve { - pub async fn serve(self) -> Result<()> { + pub async fn serve(self, plugin_manager: PluginManager) -> Result<()> { let mut crate_config = crate::CrateConfig::new()?; // change the relase state. diff --git a/src/main.rs b/src/main.rs index e7b96d4b5..873aa4bf7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,7 +31,7 @@ async fn main() -> Result<()> { } Commands::Serve(opts) => { - if let Err(e) = opts.serve().await { + if let Err(e) = opts.serve(plugin_manager).await { log::error!("🚫 Serve startup failed: {}", e); } } From 9f20337e5e7eebf8bca76b380059c96d1df578f9 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Sat, 27 Aug 2022 21:56:31 -0700 Subject: [PATCH 26/48] feat: `rebuild` supported --- Cargo.toml | 2 +- src/cli/serve/mod.rs | 2 +- src/plugin/mod.rs | 59 ++++++++++++++++++++++++++++++++++++++++++++ src/server/mod.rs | 32 +++++++++++++++++------- 4 files changed, 84 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2690def1b..e88323fd1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ dioxus-rsx-interpreter = { git = "https://github.com/dioxuslabs/dioxus/" } proc-macro2 = { version = "1.0", features = ["span-locations"] } # plugin packages -mlua = { version = "0.8.1", features = ["lua54", "vendored", "async"] } +mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "send"] } [[bin]] path = "src/main.rs" diff --git a/src/cli/serve/mod.rs b/src/cli/serve/mod.rs index bb24c1e83..44061149e 100644 --- a/src/cli/serve/mod.rs +++ b/src/cli/serve/mod.rs @@ -65,7 +65,7 @@ impl Serve { Serve::regen_dev_page(&crate_config)?; // start the develop server - server::startup(self.serve.port, crate_config.clone()).await?; + server::startup(self.serve.port, crate_config.clone(), plugin_manager).await?; Ok(()) } diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 7f0bd99db..c32eee9a3 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -167,6 +167,65 @@ impl PluginManager { Ok(()) } + pub fn on_serve_start(&self, crate_config: &CrateConfig) -> anyhow::Result<()> { + let lua = &self.lua; + + let manager = lua.globals().get::<_, Table>("manager")?; + + let args = lua.create_table()?; + args.set("name", crate_config.dioxus_config.application.name.clone())?; + + for i in 1..(manager.len()? as i32 + 1) { + let info = manager.get::(i)?; + if let Some(func) = info.serve.on_start { + func.call::(args.clone())?; + } + } + + Ok(()) + } + + pub fn on_serve_rebuild(&self, timestamp: i64, files: Vec) -> anyhow::Result<()> { + let lua = &self.lua; + + let manager = lua.globals().get::<_, Table>("manager")?; + + let args = lua.create_table()?; + args.set("timestamp", timestamp)?; + let files: Vec = files + .iter() + .map(|v| v.to_str().unwrap().to_string()) + .collect(); + args.set("changed_files", files)?; + + for i in 1..(manager.len()? as i32 + 1) { + let info = manager.get::(i)?; + if let Some(func) = info.serve.on_rebuild { + func.call::(args.clone())?; + } + } + + Ok(()) + } + + pub fn on_serve_shutdown(&self, crate_config: &CrateConfig) -> anyhow::Result<()> { + let lua = &self.lua; + + let manager = lua.globals().get::<_, Table>("manager")?; + + let args = lua.create_table()?; + args.set("name", crate_config.dioxus_config.application.name.clone())?; + + for i in 1..(manager.len()? as i32 + 1) { + let info = manager.get::(i)?; + if let Some(func) = info.serve.on_shutdown { + func.call::(args.clone())?; + } + } + + Ok(()) + } + fn init_plugin_dir() -> PathBuf { let app_path = app_path(); let plugin_path = app_path.join("plugins"); diff --git a/src/server/mod.rs b/src/server/mod.rs index eed3834a7..a0ee63839 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -16,7 +16,7 @@ use std::{net::UdpSocket, path::PathBuf, process::Command, sync::Arc}; use tower::ServiceBuilder; use tower_http::services::fs::{ServeDir, ServeFileSystemResponseBody}; -use crate::{builder, serve::Serve, BuildResult, CrateConfig, Result}; +use crate::{builder, plugin::PluginManager, serve::Serve, BuildResult, CrateConfig, Result}; use tokio::sync::broadcast; mod hot_reload; @@ -52,20 +52,26 @@ struct WsReloadState { update: broadcast::Sender<()>, } -pub async fn startup(port: u16, config: CrateConfig) -> Result<()> { +pub async fn startup(port: u16, config: CrateConfig, plugin_manager: PluginManager) -> Result<()> { if config.hot_reload { - startup_hot_reload(port, config).await? + startup_hot_reload(port, config, plugin_manager).await? } else { - startup_default(port, config).await? + startup_default(port, config, plugin_manager).await? } Ok(()) } -pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { +pub async fn startup_hot_reload( + port: u16, + config: CrateConfig, + plugin_manager: PluginManager, +) -> Result<()> { let first_build_result = crate::builder::build(&config, false)?; log::info!("🚀 Starting development server..."); + plugin_manager.on_serve_start(&config)?; + let dist_path = config.out_dir.clone(); let (reload_tx, _) = broadcast::channel(100); let last_file_rebuild = Arc::new(Mutex::new(FileMap::new(config.crate_dir.clone()))); @@ -274,11 +280,17 @@ pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { Ok(()) } -pub async fn startup_default(port: u16, config: CrateConfig) -> Result<()> { +pub async fn startup_default( + port: u16, + config: CrateConfig, + plugin_manager: PluginManager, +) -> Result<()> { let first_build_result = crate::builder::build(&config, false)?; log::info!("🚀 Starting development server..."); + plugin_manager.on_serve_start(&config)?; + let dist_path = config.out_dir.clone(); let (reload_tx, _) = broadcast::channel(100); @@ -306,7 +318,7 @@ pub async fn startup_default(port: u16, config: CrateConfig) -> Result<()> { let watcher_config = config.clone(); let mut watcher = notify::recommended_watcher(move |info: notify::Result| { let config = watcher_config.clone(); - if info.is_ok() { + if let Ok(e) = info { if chrono::Local::now().timestamp() > last_update_time { match build_manager.rebuild() { Ok(res) => { @@ -315,11 +327,13 @@ pub async fn startup_default(port: u16, config: CrateConfig) -> Result<()> { port, &config, PrettierOptions { - changed: info.unwrap().paths, + changed: e.paths.clone(), warnings: res.warnings, elapsed_time: res.elapsed_time, }, ); + let _ = plugin_manager + .on_serve_rebuild(chrono::Local::now().timestamp(), e.paths); } Err(e) => log::error!("{}", e), } @@ -599,4 +613,4 @@ async fn ws_handler( reload_watcher.await.unwrap(); }) -} \ No newline at end of file +} From 59b8a84530aa2ea3c94bc7fdb474c2d218cd8235 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Tue, 30 Aug 2022 21:12:57 -0700 Subject: [PATCH 27/48] feat: commit code --- src/server/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/server/mod.rs b/src/server/mod.rs index a0ee63839..89be7920f 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -289,8 +289,6 @@ pub async fn startup_default( log::info!("🚀 Starting development server..."); - plugin_manager.on_serve_start(&config)?; - let dist_path = config.out_dir.clone(); let (reload_tx, _) = broadcast::channel(100); @@ -316,6 +314,7 @@ pub async fn startup_default( .unwrap_or_else(|| vec![PathBuf::from("src")]); let watcher_config = config.clone(); + let wacher_plugin_manager = plugin_manager; let mut watcher = notify::recommended_watcher(move |info: notify::Result| { let config = watcher_config.clone(); if let Ok(e) = info { @@ -362,6 +361,8 @@ pub async fn startup_default( }, ); + plugin_manager.on_serve_start(&config)?; + let file_service_config = config.clone(); let file_service = ServiceBuilder::new() .and_then( From 37ef7c3ff9c7d8860df40cc353494280aeb9fc9d Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Wed, 21 Sep 2022 16:56:36 -0700 Subject: [PATCH 28/48] feat: support some event --- Cargo.lock | 1 + Cargo.toml | 1 + src/cli/build/mod.rs | 6 ++--- src/cli/serve/mod.rs | 6 ++--- src/main.rs | 8 +++---- src/plugin/mod.rs | 54 +++++++++++++++++++++++++------------------- src/server/mod.rs | 19 ++++++++-------- 7 files changed, 51 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a7644663c..745fa3505 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -621,6 +621,7 @@ dependencies = [ "html_parser", "hyper", "indicatif", + "lazy_static", "log", "mlua", "notify", diff --git a/Cargo.toml b/Cargo.toml index e88323fd1..89558b451 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,7 @@ proc-macro2 = { version = "1.0", features = ["span-locations"] } # plugin packages mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "send"] } +lazy_static = "1.4.0" [[bin]] path = "src/main.rs" diff --git a/src/cli/build/mod.rs b/src/cli/build/mod.rs index 0086114ae..384bdfff1 100644 --- a/src/cli/build/mod.rs +++ b/src/cli/build/mod.rs @@ -11,7 +11,7 @@ pub struct Build { } impl Build { - pub fn build(self, plugin_manager: PluginManager) -> Result<()> { + pub fn build(self) -> Result<()> { let mut crate_config = crate::CrateConfig::new()?; // change the release state. @@ -34,7 +34,7 @@ impl Build { .clone() }); - let _ = plugin_manager.on_build_start(&crate_config, &platform); + let _ = PluginManager::on_build_start(&crate_config, &platform); match platform.as_str() { "web" => { @@ -65,7 +65,7 @@ impl Build { )?; file.write_all(temp.as_bytes())?; - let _ = plugin_manager.on_build_finish(&crate_config, &platform); + let _ = PluginManager::on_build_finish(&crate_config, &platform); Ok(()) } diff --git a/src/cli/serve/mod.rs b/src/cli/serve/mod.rs index 44061149e..93770b6ed 100644 --- a/src/cli/serve/mod.rs +++ b/src/cli/serve/mod.rs @@ -1,5 +1,3 @@ -use crate::plugin::PluginManager; - use super::*; use std::{ io::Write, @@ -16,7 +14,7 @@ pub struct Serve { } impl Serve { - pub async fn serve(self, plugin_manager: PluginManager) -> Result<()> { + pub async fn serve(self) -> Result<()> { let mut crate_config = crate::CrateConfig::new()?; // change the relase state. @@ -65,7 +63,7 @@ impl Serve { Serve::regen_dev_page(&crate_config)?; // start the develop server - server::startup(self.serve.port, crate_config.clone(), plugin_manager).await?; + server::startup(self.serve.port, crate_config.clone()).await?; Ok(()) } diff --git a/src/main.rs b/src/main.rs index 6f99e409d..c54971ba0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,10 +7,10 @@ async fn main() -> Result<()> { let args = Cli::parse(); set_up_logging(); - let plugin_manager = PluginManager::init(&PluginConfig { + let _ = PluginManager::init(&PluginConfig { available: true, required: vec![], - }).unwrap(); + }); match args.action { Commands::Translate(opts) => { @@ -21,7 +21,7 @@ async fn main() -> Result<()> { } Commands::Build(opts) => { - if let Err(e) = opts.build(plugin_manager) { + if let Err(e) = opts.build() { log::error!("🚫 Build project failed: {}", e); exit(1); } @@ -35,7 +35,7 @@ async fn main() -> Result<()> { } Commands::Serve(opts) => { - if let Err(e) = opts.serve(plugin_manager).await { + if let Err(e) = opts.serve().await { log::error!("🚫 Serve startup failed: {}", e); exit(1); } diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index c32eee9a3..f3c5af446 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -1,6 +1,7 @@ use std::{ io::{Read, Write}, path::PathBuf, + sync::Mutex, }; use mlua::{AsChunk, Lua, Table}; @@ -23,23 +24,29 @@ use self::{ pub mod argument; pub mod interface; +lazy_static::lazy_static! { + static ref LUA: Mutex = Mutex::new(Lua::new()); +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PluginConfig { pub available: bool, pub required: Vec, } -pub struct PluginManager { - lua: Lua, -} +pub struct PluginManager; impl PluginManager { - pub fn init(config: &PluginConfig) -> Option { + pub fn init(config: &PluginConfig) -> bool { if !config.available { - return None; + return false; } - let lua = Lua::new(); + let lua = if let Ok(v) = LUA.lock() { + v + } else { + return false; + }; let manager = lua.create_table().unwrap(); let plugin_dir = Self::init_plugin_dir(); @@ -61,7 +68,12 @@ impl PluginManager { let mut index: u32 = 1; let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); - for entry in std::fs::read_dir(&plugin_dir).ok()? { + let dirs = if let Ok(v) = std::fs::read_dir(&plugin_dir) { + v + } else { + return false; + }; + for entry in dirs { if entry.is_err() { continue; } @@ -117,12 +129,12 @@ impl PluginManager { file.write_all(buffer).unwrap(); } } - - Some(Self { lua }) + true } - pub fn on_build_start(&self, crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { - let lua = &self.lua; + pub fn on_build_start(crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { + + let lua = LUA.lock().unwrap(); let manager = lua.globals().get::<_, Table>("manager")?; @@ -142,12 +154,8 @@ impl PluginManager { Ok(()) } - pub fn on_build_finish( - &self, - crate_config: &CrateConfig, - platform: &str, - ) -> anyhow::Result<()> { - let lua = &self.lua; + pub fn on_build_finish(crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { + let lua = LUA.lock().unwrap(); let manager = lua.globals().get::<_, Table>("manager")?; @@ -167,8 +175,8 @@ impl PluginManager { Ok(()) } - pub fn on_serve_start(&self, crate_config: &CrateConfig) -> anyhow::Result<()> { - let lua = &self.lua; + pub fn on_serve_start(crate_config: &CrateConfig) -> anyhow::Result<()> { + let lua = LUA.lock().unwrap(); let manager = lua.globals().get::<_, Table>("manager")?; @@ -185,8 +193,8 @@ impl PluginManager { Ok(()) } - pub fn on_serve_rebuild(&self, timestamp: i64, files: Vec) -> anyhow::Result<()> { - let lua = &self.lua; + pub fn on_serve_rebuild(timestamp: i64, files: Vec) -> anyhow::Result<()> { + let lua = LUA.lock().unwrap(); let manager = lua.globals().get::<_, Table>("manager")?; @@ -208,8 +216,8 @@ impl PluginManager { Ok(()) } - pub fn on_serve_shutdown(&self, crate_config: &CrateConfig) -> anyhow::Result<()> { - let lua = &self.lua; + pub fn on_serve_shutdown(crate_config: &CrateConfig) -> anyhow::Result<()> { + let lua = LUA.lock().unwrap(); let manager = lua.globals().get::<_, Table>("manager")?; diff --git a/src/server/mod.rs b/src/server/mod.rs index 89be7920f..5abc29ae4 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -52,11 +52,11 @@ struct WsReloadState { update: broadcast::Sender<()>, } -pub async fn startup(port: u16, config: CrateConfig, plugin_manager: PluginManager) -> Result<()> { +pub async fn startup(port: u16, config: CrateConfig) -> Result<()> { if config.hot_reload { - startup_hot_reload(port, config, plugin_manager).await? + startup_hot_reload(port, config).await? } else { - startup_default(port, config, plugin_manager).await? + startup_default(port, config).await? } Ok(()) } @@ -64,13 +64,12 @@ pub async fn startup(port: u16, config: CrateConfig, plugin_manager: PluginManag pub async fn startup_hot_reload( port: u16, config: CrateConfig, - plugin_manager: PluginManager, ) -> Result<()> { let first_build_result = crate::builder::build(&config, false)?; log::info!("🚀 Starting development server..."); - plugin_manager.on_serve_start(&config)?; + PluginManager::on_serve_start(&config)?; let dist_path = config.out_dir.clone(); let (reload_tx, _) = broadcast::channel(100); @@ -283,7 +282,6 @@ pub async fn startup_hot_reload( pub async fn startup_default( port: u16, config: CrateConfig, - plugin_manager: PluginManager, ) -> Result<()> { let first_build_result = crate::builder::build(&config, false)?; @@ -314,7 +312,6 @@ pub async fn startup_default( .unwrap_or_else(|| vec![PathBuf::from("src")]); let watcher_config = config.clone(); - let wacher_plugin_manager = plugin_manager; let mut watcher = notify::recommended_watcher(move |info: notify::Result| { let config = watcher_config.clone(); if let Ok(e) = info { @@ -331,8 +328,10 @@ pub async fn startup_default( elapsed_time: res.elapsed_time, }, ); - let _ = plugin_manager - .on_serve_rebuild(chrono::Local::now().timestamp(), e.paths); + let _ = PluginManager::on_serve_rebuild( + chrono::Local::now().timestamp(), + e.paths, + ); } Err(e) => log::error!("{}", e), } @@ -361,7 +360,7 @@ pub async fn startup_default( }, ); - plugin_manager.on_serve_start(&config)?; + PluginManager::on_serve_start(&config)?; let file_service_config = config.clone(); let file_service = ServiceBuilder::new() From f47d2d3d3077d25e3ca65c0b23b43d3cd0a39780 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Wed, 21 Sep 2022 22:36:12 -0700 Subject: [PATCH 29/48] feat: empty manager check --- src/main.rs | 6 +++++- src/plugin/mod.rs | 21 ++++++++++++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index c54971ba0..500e3a2ac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,10 +7,14 @@ async fn main() -> Result<()> { let args = Cli::parse(); set_up_logging(); - let _ = PluginManager::init(&PluginConfig { + let plugin_state = PluginManager::init(&PluginConfig { available: true, required: vec![], }); + if !plugin_state { + log::error!("🚫 Plugin system initialization failed"); + exit(1); + } match args.action { Commands::Translate(opts) => { diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index f3c5af446..879f92aa6 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -38,9 +38,6 @@ pub struct PluginManager; impl PluginManager { pub fn init(config: &PluginConfig) -> bool { - if !config.available { - return false; - } let lua = if let Ok(v) = LUA.lock() { v @@ -48,6 +45,12 @@ impl PluginManager { return false; }; + if !config.available { + // // if plugin system is available, just set manager to nil. + // lua.globals().set("manager", mlua::Value::Nil).unwrap(); + return true; + } + let manager = lua.create_table().unwrap(); let plugin_dir = Self::init_plugin_dir(); @@ -136,6 +139,9 @@ impl PluginManager { let lua = LUA.lock().unwrap(); + if !lua.globals().contains_key("manager")? { + return Ok(()); + } let manager = lua.globals().get::<_, Table>("manager")?; let args = lua.create_table()?; @@ -157,6 +163,9 @@ impl PluginManager { pub fn on_build_finish(crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { let lua = LUA.lock().unwrap(); + if !lua.globals().contains_key("manager")? { + return Ok(()); + } let manager = lua.globals().get::<_, Table>("manager")?; let args = lua.create_table()?; @@ -178,6 +187,9 @@ impl PluginManager { pub fn on_serve_start(crate_config: &CrateConfig) -> anyhow::Result<()> { let lua = LUA.lock().unwrap(); + if !lua.globals().contains_key("manager")? { + return Ok(()); + } let manager = lua.globals().get::<_, Table>("manager")?; let args = lua.create_table()?; @@ -219,6 +231,9 @@ impl PluginManager { pub fn on_serve_shutdown(crate_config: &CrateConfig) -> anyhow::Result<()> { let lua = LUA.lock().unwrap(); + if !lua.globals().contains_key("manager")? { + return Ok(()); + } let manager = lua.globals().get::<_, Table>("manager")?; let args = lua.create_table()?; From 20c29ed042dd702f406a7b29fe4a3f823518bad2 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Wed, 21 Sep 2022 22:57:26 -0700 Subject: [PATCH 30/48] feat: add `serve-shutdown` support --- Cargo.lock | 23 +++++++++++++++++++++++ Cargo.toml | 3 ++- src/main.rs | 1 + src/server/mod.rs | 17 +++++++++-------- 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 745fa3505..f4dc5ba6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -502,6 +502,16 @@ dependencies = [ "typenum", ] +[[package]] +name = "ctrlc" +version = "3.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d91974fbbe88ec1df0c24a4f00f99583667a7e2e6272b2b92d294d81e462173" +dependencies = [ + "nix", + "winapi", +] + [[package]] name = "curl" version = "0.4.44" @@ -610,6 +620,7 @@ dependencies = [ "clap", "colored 2.0.0", "convert_case", + "ctrlc", "dioxus", "dioxus-rsx-interpreter", "dirs 4.0.0", @@ -1621,6 +1632,18 @@ dependencies = [ "tempfile", ] +[[package]] +name = "nix" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e322c04a9e3440c327fca7b6c8a63e6890a32fa2ad689db972425f07e0d22abb" +dependencies = [ + "autocfg", + "bitflags", + "cfg-if", + "libc", +] + [[package]] name = "notify" version = "5.0.0-pre.16" diff --git a/Cargo.toml b/Cargo.toml index 89558b451..6d707cfab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,10 +58,11 @@ dioxus = { git = "https://github.com/dioxuslabs/dioxus/", features = ["hot-reloa dioxus-rsx-interpreter = { git = "https://github.com/dioxuslabs/dioxus/" } proc-macro2 = { version = "1.0", features = ["span-locations"] } +lazy_static = "1.4.0" # plugin packages mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "send"] } -lazy_static = "1.4.0" +ctrlc = "3.2.3" [[bin]] path = "src/main.rs" diff --git a/src/main.rs b/src/main.rs index 500e3a2ac..e60606fb6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,6 +11,7 @@ async fn main() -> Result<()> { available: true, required: vec![], }); + if !plugin_state { log::error!("🚫 Plugin system initialization failed"); exit(1); diff --git a/src/server/mod.rs b/src/server/mod.rs index 5abc29ae4..ebb328ad0 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -53,6 +53,13 @@ struct WsReloadState { } pub async fn startup(port: u16, config: CrateConfig) -> Result<()> { + // ctrl-c shutdown checker + let crate_config = config.clone(); + let _ = ctrlc::set_handler(move || { + let _ = PluginManager::on_serve_shutdown(&crate_config); + std::process::exit(0); + }); + if config.hot_reload { startup_hot_reload(port, config).await? } else { @@ -61,10 +68,7 @@ pub async fn startup(port: u16, config: CrateConfig) -> Result<()> { Ok(()) } -pub async fn startup_hot_reload( - port: u16, - config: CrateConfig, -) -> Result<()> { +pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { let first_build_result = crate::builder::build(&config, false)?; log::info!("🚀 Starting development server..."); @@ -279,10 +283,7 @@ pub async fn startup_hot_reload( Ok(()) } -pub async fn startup_default( - port: u16, - config: CrateConfig, -) -> Result<()> { +pub async fn startup_default(port: u16, config: CrateConfig) -> Result<()> { let first_build_result = crate::builder::build(&config, false)?; log::info!("🚀 Starting development server..."); From f099042726344dda4e173f5bf940ea2b73252dfc Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Thu, 22 Sep 2022 00:24:07 -0700 Subject: [PATCH 31/48] docs: commit new document --- docs/src/SUMMARY.md | 4 +- docs/src/plugin/README.md | 79 ++++++++++++++++++++++++++++ docs/src/plugin/interface/command.md | 21 ++++++++ 3 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 docs/src/plugin/README.md create mode 100644 docs/src/plugin/interface/command.md diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index ed7bcbfaf..3a260d75b 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -8,4 +8,6 @@ - [Build](./cmd/build.md) - [Serve](./cmd/serve.md) - [Clean](./cmd/clean.md) - - [Translate](./cmd/translate.md) \ No newline at end of file + - [Translate](./cmd/translate.md) +- [Plugin Development](./plugin/README.md) + - [API.Command](./plugin/interface/command.md) \ No newline at end of file diff --git a/docs/src/plugin/README.md b/docs/src/plugin/README.md new file mode 100644 index 000000000..9983f024b --- /dev/null +++ b/docs/src/plugin/README.md @@ -0,0 +1,79 @@ +# CLI Plugin Development + +> For Cli 0.2.0 we will add `plugin-develop` support. + +Before the 0.2.0 we use `dioxus tool` to use & install some plugin, but we think that is not good for extend cli program, some people want tailwind support, some people want sass support, we can't add all this thing in to the cli source code and we don't have time to maintain a lot of tools that user request, so maybe user make plugin by themself is a good choice. + +### Why Lua ? + +We choose `Lua: 5.4` to be the plugin develop language, because cli plugin is not complex, just like a workflow, and user & developer can write some easy code for their plugin. We have **vendored** lua in cli program, and user don't need install lua runtime in their computer, and the lua parser & runtime doesn't take up much disk memory. + +### Event Management + +The plugin library have pre-define some important event you can control: + +- `build.on_start` +- `build.on_finished` +- `serve.on_start` +- `serve.on_rebuild` +- `serve.on_shutdown` + +### Plugin Template + +```lua +package.path = library_dir .. "/?.lua" + +local plugin = require("plugin") +local manager = require("manager") + +-- deconstruct api functions +local log = plugin.log + +-- plugin information +manager.name = "Hello Dixous Plugin" +manager.repository = "https://github.com/mrxiaozhuox/hello-dioxus-plugin" +manager.author = "YuKun Liu " +manager.version = "0.0.1" + +-- init manager info to plugin api +plugin.init(manager) + +manager.on_init = function () + -- when the first time plugin been load, this function will be execute. + -- system will create a `dcp.json` file to verify init state. + log.info("[plugin] Start to init plugin: " .. manager.name) +end + +---@param info BuildInfo +manager.build.on_start = function (info) + -- before the build work start, system will execute this function. + log.info("[plugin] Build starting: " .. info.name) +end + +---@param info BuildInfo +manager.build.on_finish = function (info) + -- when the build work is done, system will execute this function. + log.info("[plugin] Build finished: " .. info.name) +end + +---@param info ServeStartInfo +manager.serve.on_start = function (info) + -- this function will after clean & print to run, so you can print some thing. + log.info("[plugin] Serve start: " .. info.name) +end + +---@param info ServeRebuildInfo +manager.serve.on_rebuild = function (info) + -- this function will after clean & print to run, so you can print some thing. + local files = plugin.tool.dump(info.changed_files) + log.info("[plugin] Serve rebuild: '" .. files .. "'") +end + +manager.serve.on_shutdown = function () + log.info("[plugin] Serve shutdown") +end + +manager.serve.interval = 1000 + +return manager +``` \ No newline at end of file diff --git a/docs/src/plugin/interface/command.md b/docs/src/plugin/interface/command.md new file mode 100644 index 000000000..c9b1dc48f --- /dev/null +++ b/docs/src/plugin/interface/command.md @@ -0,0 +1,21 @@ +# Command Functions + +> you can use command functions to execute some code & script + +Type Define: +``` +Stdio: "Inhert" | "Piped" | "Null" +``` + +### `exec(commands: [string], stdout: Stdio, stderr: Stdio)` + +you can use this function to run some command on the current system. + +```lua +local cmd = plugin.command + +manager.test = function () + cmd.exec({"git", "clone", "https://github.com/DioxusLabs/cli-plugin-library"}) +end +``` +> Warning: This function don't have exception catch. \ No newline at end of file From d47319526c20d88f14e21a8216fd01ea97c61b25 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Thu, 22 Sep 2022 08:32:57 -0700 Subject: [PATCH 32/48] docs: commit new document --- docs/src/SUMMARY.md | 4 +++- docs/src/plugin/interface/dirs.md | 35 +++++++++++++++++++++++++++++++ docs/src/plugin/interface/os.md | 11 ++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 docs/src/plugin/interface/dirs.md create mode 100644 docs/src/plugin/interface/os.md diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 3a260d75b..18ae0f5aa 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -10,4 +10,6 @@ - [Clean](./cmd/clean.md) - [Translate](./cmd/translate.md) - [Plugin Development](./plugin/README.md) - - [API.Command](./plugin/interface/command.md) \ No newline at end of file + - [API.Command](./plugin/interface/command.md) + - [API.OS](./plugin/interface/os.md) + - [API.Directories](./plugin/interface/dirs.md) \ No newline at end of file diff --git a/docs/src/plugin/interface/dirs.md b/docs/src/plugin/interface/dirs.md new file mode 100644 index 000000000..4173c922f --- /dev/null +++ b/docs/src/plugin/interface/dirs.md @@ -0,0 +1,35 @@ +# Dirs Functions + +> you can use Dirs functions to get some directory path + + +### plugin_dir() -> string + +You can get current plugin **root** directory path + +```lua +local path = plugin.dirs.plugin_dir() +-- example: ~/Development/DioxusCli/plugin/test-plugin/ +``` + +### bin_dir() -> string + +You can get plugin **bin** direcotry path + +Sometime you need install some binary file like `tailwind-cli` & `sass-cli` to help your plugin work, then you should put binary file in this directory. + +```lua +local path = plugin.dirs.bin_dir() +-- example: ~/Development/DioxusCli/plugin/test-plugin/bin/ +``` + +### temp_dir() -> string + +You can get plugin **temp** direcotry path + +Just put some temporary file in this directory. + +```lua +local path = plugin.dirs.bin_dir() +-- example: ~/Development/DioxusCli/plugin/test-plugin/temp/ +``` \ No newline at end of file diff --git a/docs/src/plugin/interface/os.md b/docs/src/plugin/interface/os.md new file mode 100644 index 000000000..72a17c336 --- /dev/null +++ b/docs/src/plugin/interface/os.md @@ -0,0 +1,11 @@ +# OS Functions + +> you can use OS functions to get some system information + +### current_platform() -> string ("windows" | "macos" | "linux") + +This function can help you get system & platform type: + +```lua +local platform = plugin.os.current_platform() +``` \ No newline at end of file From 1c59c902a6cfe8ec1c680fe5dd4b47963a2ea51c Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Thu, 22 Sep 2022 11:05:37 -0700 Subject: [PATCH 33/48] docs: commit docs --- docs/src/SUMMARY.md | 4 ++- docs/src/plugin/interface/log.md | 48 ++++++++++++++++++++++++++++ docs/src/plugin/interface/network.md | 34 ++++++++++++++++++++ 3 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 docs/src/plugin/interface/log.md create mode 100644 docs/src/plugin/interface/network.md diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 18ae0f5aa..4fa8a4ef3 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -10,6 +10,8 @@ - [Clean](./cmd/clean.md) - [Translate](./cmd/translate.md) - [Plugin Development](./plugin/README.md) + - [API.Log](./plugin/interface/log.md) - [API.Command](./plugin/interface/command.md) - [API.OS](./plugin/interface/os.md) - - [API.Directories](./plugin/interface/dirs.md) \ No newline at end of file + - [API.Directories](./plugin/interface/dirs.md) + - [API.Network](./plugin/interface/network.md) \ No newline at end of file diff --git a/docs/src/plugin/interface/log.md b/docs/src/plugin/interface/log.md new file mode 100644 index 000000000..fcd72595b --- /dev/null +++ b/docs/src/plugin/interface/log.md @@ -0,0 +1,48 @@ +# Log Functions + +> You can use log function to print some useful log info + +### Trace(info: string) + +Print trace log info + +```lua +local log = plugin.log +log.trace("trace information") +``` + +### Debug(info: string) + +Print debug log info + +```lua +local log = plugin.log +log.debug("debug information") +``` + +### Info(info: string) + +Print info log info + +```lua +local log = plugin.log +log.info("info information") +``` + +### Warn(info: string) + +Print warning log info + +```lua +local log = plugin.log +log.warn("warn information") +``` + +### Error(info: string) + +Print error log info + +```lua +local log = plugin.log +log.error("error information") +``` \ No newline at end of file diff --git a/docs/src/plugin/interface/network.md b/docs/src/plugin/interface/network.md new file mode 100644 index 000000000..358c9c498 --- /dev/null +++ b/docs/src/plugin/interface/network.md @@ -0,0 +1,34 @@ +# Network Functions + +> you can use Network functions to download & read some data from internet + +### download_file(url: string, path: string) -> boolean + +This function can help you download some file from url, and it will return a *boolean* value to check the download status. (true: success | false: fail) + +You need pass a target url and a local path (where you want to save this file) + +```lua +-- this file will download to plugin temp directory +local status = plugin.network.download_file( + "http://xxx.com/xxx.zip", + plugin.dirs.temp_dir() +) +if status != true then + log.error("Download Failed") +end +``` + +### clone_repo(url: string, path: string) -> boolean + +This function can help you use `git clone` command (this system must have been installed git) + +```lua +local status = plugin.network.clone_repo( + "http://github.com/mrxiaozhuox/dioxus-starter", + plugin.dirs.bin_dir() +) +if status != true then + log.error("Clone Failed") +end +``` \ No newline at end of file From b59e41eaeecfa9c5827ee73e4343cd1c6442f0d5 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Thu, 22 Sep 2022 17:01:38 -0700 Subject: [PATCH 34/48] fix: move `is_dir` & `is_file` to path --- src/plugin/interface/fs.rs | 8 -------- src/plugin/interface/path.rs | 22 +++++++++++++++++++++- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs index 562448637..8f9be6e0a 100644 --- a/src/plugin/interface/fs.rs +++ b/src/plugin/interface/fs.rs @@ -14,14 +14,6 @@ impl UserData for PluginFileSystem { let path = PathBuf::from(path); Ok(path.exists()) }); - methods.add_function("is_dir", |_, path: String| { - let path = PathBuf::from(path); - Ok(path.is_dir()) - }); - methods.add_function("is_file", |_, path: String| { - let path = PathBuf::from(path); - Ok(path.is_file()) - }); methods.add_function("create_dir", |_, args: (String, bool)| { let path = args.0; let recursive = args.1; diff --git a/src/plugin/interface/path.rs b/src/plugin/interface/path.rs index 66584cc52..a3d2da186 100644 --- a/src/plugin/interface/path.rs +++ b/src/plugin/interface/path.rs @@ -5,10 +5,30 @@ use mlua::UserData; pub struct PluginPath; impl UserData for PluginPath { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + // join function methods.add_function("join", |_, args: (String, String)| { let current_path = PathBuf::from(args.0); let new_path = current_path.join(args.1); Ok(new_path.to_str().unwrap().to_string()) }); + + // parent function + methods.add_function("parent", |_, path: String| { + let current_path = PathBuf::from(&path); + let parent = current_path.parent(); + if parent.is_none() { + return Ok(path); + } else { + return Ok(parent.unwrap().to_str().unwrap().to_string()); + } + }); + methods.add_function("is_dir", |_, path: String| { + let path = PathBuf::from(path); + Ok(path.is_dir()) + }); + methods.add_function("is_file", |_, path: String| { + let path = PathBuf::from(path); + Ok(path.is_file()) + }); } -} \ No newline at end of file +} From e2852a60d15b066a27f5fd8accb22b4963cff19f Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Thu, 22 Sep 2022 17:03:15 -0700 Subject: [PATCH 35/48] feat: commit code --- src/plugin/interface/fs.rs | 4 ---- src/plugin/interface/path.rs | 4 ++++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs index 8f9be6e0a..afe9a8183 100644 --- a/src/plugin/interface/fs.rs +++ b/src/plugin/interface/fs.rs @@ -10,10 +10,6 @@ use crate::tools::extract_zip; pub struct PluginFileSystem; impl UserData for PluginFileSystem { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { - methods.add_function("exists", |_, path: String| { - let path = PathBuf::from(path); - Ok(path.exists()) - }); methods.add_function("create_dir", |_, args: (String, bool)| { let path = args.0; let recursive = args.1; diff --git a/src/plugin/interface/path.rs b/src/plugin/interface/path.rs index a3d2da186..1dd3997cf 100644 --- a/src/plugin/interface/path.rs +++ b/src/plugin/interface/path.rs @@ -22,6 +22,10 @@ impl UserData for PluginPath { return Ok(parent.unwrap().to_str().unwrap().to_string()); } }); + methods.add_function("exists", |_, path: String| { + let path = PathBuf::from(path); + Ok(path.exists()) + }); methods.add_function("is_dir", |_, path: String| { let path = PathBuf::from(path); Ok(path.is_dir()) From 9ee572ad26f8031b40e718c863b00ece77003ec0 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Fri, 23 Sep 2022 09:34:12 -0700 Subject: [PATCH 36/48] docs: add path docs --- docs/src/SUMMARY.md | 3 ++- docs/src/plugin/interface/path.md | 35 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 docs/src/plugin/interface/path.md diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 4fa8a4ef3..b5e3b91ae 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -14,4 +14,5 @@ - [API.Command](./plugin/interface/command.md) - [API.OS](./plugin/interface/os.md) - [API.Directories](./plugin/interface/dirs.md) - - [API.Network](./plugin/interface/network.md) \ No newline at end of file + - [API.Network](./plugin/interface/network.md) + - [API.Path](./plugin/interface/path.md) \ No newline at end of file diff --git a/docs/src/plugin/interface/path.md b/docs/src/plugin/interface/path.md new file mode 100644 index 000000000..ee787ecf9 --- /dev/null +++ b/docs/src/plugin/interface/path.md @@ -0,0 +1,35 @@ +# Path Functions + +> you can use path functions to operate valid path string + +### join(path: string, extra: string) -> string + +This function can help you extend a path, you can extend any path, dirname or filename. + +```lua +local current_path = "~/hello/dioxus" +local new_path = plugin.path.join(current_path, "world") +-- new_path = "~/hello/dioxus/world" +``` + +### parent(path: string) -> string + +This function will return `path` parent-path string, back to the parent. + +```lua +local current_path = "~/hello/dioxus" +local new_path = plugin.path.parent(current_path) +-- new_path = "~/hello/" +``` + +### exists(path: string) -> boolean + +This function can check some path (dir & file) is exists. + +### is_file(path: string) -> boolean + +This function can check some path is a exist file. + +### is_dir(path: string) -> boolean + +This function can check some path is a exist dir. \ No newline at end of file From 6004cfdd405539286da39f5baa61eb39f93baffa Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Fri, 23 Sep 2022 16:10:17 -0700 Subject: [PATCH 37/48] feat: add some command --- src/cli/plugin/mod.rs | 41 ++++++----------------------------------- src/main.rs | 4 ++-- src/plugin/mod.rs | 40 ++++++++++++++++++++++++---------------- src/tools.rs | 6 +++--- 4 files changed, 35 insertions(+), 56 deletions(-) diff --git a/src/cli/plugin/mod.rs b/src/cli/plugin/mod.rs index aee4b54b0..caffd2f10 100644 --- a/src/cli/plugin/mod.rs +++ b/src/cli/plugin/mod.rs @@ -18,48 +18,19 @@ impl Plugin { pub async fn plugin(self) -> Result<()> { match self { Plugin::List {} => { - for item in tools::tool_list() { - if tools::Tool::from_str(item).unwrap().is_installed() { - println!("- {item} [installed]"); - } else { - println!("- {item}"); - } + for item in crate::plugin::PluginManager::plugin_list() { + println!("- {item}"); } } Plugin::AppPath {} => { - if let Some(v) = tools::tools_path().to_str() { + if let Some(v) = crate::plugin::PluginManager::init_plugin_dir().to_str() { println!("{}", v); } else { - log::error!("Tools path get failed."); + log::error!("Plugin path get failed."); } } - Plugin::Add { name } => { - let tool_list = tools::tool_list(); - - if !tool_list.contains(&name.as_str()) { - log::error!("Tool {name} not found."); - return Ok(()); - } - let target_tool = tools::Tool::from_str(&name).unwrap(); - - if target_tool.is_installed() { - log::warn!("Tool {name} is installed."); - return Ok(()); - } - - log::info!("Start to download tool package..."); - if let Err(e) = target_tool.download_package().await { - log::error!("Tool download failed: {e}"); - return Ok(()); - } - - log::info!("Start to install tool package..."); - if let Err(e) = target_tool.install_package().await { - log::error!("Tool install failed: {e}"); - return Ok(()); - } - - log::info!("Tool {name} install successfully!"); + Plugin::Add { name: _ } => { + log::info!("You can use `dioxus plugin app-path` to get Installation position"); } } Ok(()) diff --git a/src/main.rs b/src/main.rs index e60606fb6..300d4ef73 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,8 +12,8 @@ async fn main() -> Result<()> { required: vec![], }); - if !plugin_state { - log::error!("🚫 Plugin system initialization failed"); + if let Err(e) = plugin_state { + log::error!("🚫 Plugin system initialization failed: {e}"); exit(1); } diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 879f92aa6..2cd4cb909 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -37,18 +37,13 @@ pub struct PluginConfig { pub struct PluginManager; impl PluginManager { - pub fn init(config: &PluginConfig) -> bool { - - let lua = if let Ok(v) = LUA.lock() { - v - } else { - return false; - }; + pub fn init(config: &PluginConfig) -> anyhow::Result<()> { + let lua = LUA.lock().unwrap(); if !config.available { // // if plugin system is available, just set manager to nil. // lua.globals().set("manager", mlua::Value::Nil).unwrap(); - return true; + return Ok(()); } let manager = lua.create_table().unwrap(); @@ -71,11 +66,7 @@ impl PluginManager { let mut index: u32 = 1; let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); - let dirs = if let Ok(v) = std::fs::read_dir(&plugin_dir) { - v - } else { - return false; - }; + let dirs = std::fs::read_dir(&plugin_dir)?; for entry in dirs { if entry.is_err() { continue; @@ -132,11 +123,10 @@ impl PluginManager { file.write_all(buffer).unwrap(); } } - true + return Ok(()); } pub fn on_build_start(crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { - let lua = LUA.lock().unwrap(); if !lua.globals().contains_key("manager")? { @@ -249,7 +239,7 @@ impl PluginManager { Ok(()) } - fn init_plugin_dir() -> PathBuf { + pub fn init_plugin_dir() -> PathBuf { let app_path = app_path(); let plugin_path = app_path.join("plugins"); if !plugin_path.is_dir() { @@ -259,4 +249,22 @@ impl PluginManager { } plugin_path } + + pub fn plugin_list() -> Vec { + let mut res = vec![]; + + let app_path = app_path(); + let plugin_path = app_path.join("plugins"); + + let child_dirs = std::fs::read_dir(plugin_path).unwrap(); + for p in child_dirs { + if let Ok(p) = p { + if p.path().is_dir() && p.file_name() != "library" { + res.push(p.file_name().to_str().unwrap().to_string()); + } + } + } + + res + } } diff --git a/src/tools.rs b/src/tools.rs index a8266c8ec..de762d364 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -18,9 +18,9 @@ pub enum Tool { Tailwind, } -pub fn tool_list() -> Vec<&'static str> { - vec!["binaryen", "sass", "tailwindcss"] -} +// pub fn tool_list() -> Vec<&'static str> { +// vec!["binaryen", "sass", "tailwindcss"] +// } pub fn app_path() -> PathBuf { let data_local = dirs::data_local_dir().unwrap(); From 6ad1333a94dbf4901a0712e1d55f03f3fa4d284f Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Sat, 24 Sep 2022 22:50:13 -0700 Subject: [PATCH 38/48] feat: commit code --- src/plugin/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 2cd4cb909..9c99c8266 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -260,7 +260,9 @@ impl PluginManager { for p in child_dirs { if let Ok(p) = p { if p.path().is_dir() && p.file_name() != "library" { - res.push(p.file_name().to_str().unwrap().to_string()); + if p.path().join("init.lua").is_file() { + res.push(p.file_name().to_str().unwrap().to_string()); + } } } } From 762093094fc73a8d5943cce580f9f8cb7efcf863 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Tue, 27 Sep 2022 20:34:32 -0700 Subject: [PATCH 39/48] feat: commit code --- src/cli/plugin/mod.rs | 2 -- src/server/mod.rs | 5 ++++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cli/plugin/mod.rs b/src/cli/plugin/mod.rs index caffd2f10..9179f5bd6 100644 --- a/src/cli/plugin/mod.rs +++ b/src/cli/plugin/mod.rs @@ -1,5 +1,3 @@ -use crate::tools; - use super::*; /// Build the Rust WASM app and all of its assets. diff --git a/src/server/mod.rs b/src/server/mod.rs index 2202f6f39..6ab38f16a 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -68,6 +68,7 @@ pub async fn startup(port: u16, config: CrateConfig) -> Result<()> { Ok(()) } +#[allow(unused_assignments)] pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { let first_build_result = crate::builder::build(&config, false)?; @@ -112,14 +113,15 @@ pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { if chrono::Local::now().timestamp() > last_update_time { // Give time for the change to take effect before reading the file std::thread::sleep(std::time::Duration::from_millis(100)); + let mut updated = false; if let Ok(evt) = evt { let mut messages = Vec::new(); let mut needs_rebuild = false; for path in evt.paths.clone() { - let mut file = File::open(path.clone()).unwrap(); if path.extension().map(|p| p.to_str()).flatten() != Some("rs") { continue; } + let mut file = File::open(path.clone()).unwrap(); let mut src = String::new(); file.read_to_string(&mut src).expect("Unable to read file"); // find changes to the rsx in the file @@ -127,6 +129,7 @@ pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { let mut last_file_rebuild = last_file_rebuild.lock().unwrap(); if let Some(old_str) = last_file_rebuild.map.get(&path) { if let Ok(old) = syn::parse_file(&old_str) { + updated = true; match find_rsx(&syntax, &old) { DiffResult::CodeChanged => { needs_rebuild = true; From 77393b273eff890f6fc0d2df28526b8e577860c8 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Sat, 1 Oct 2022 15:17:09 -0700 Subject: [PATCH 40/48] feat: commit plugin error handle --- Cargo.lock | 31 +++++++++++++++++++++++++++ Cargo.toml | 2 +- src/plugin/mod.rs | 54 ++++++++++++++++++++++++++++++++++------------- 3 files changed, 71 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f4dc5ba6c..75c5a10ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -772,6 +772,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "either" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" + [[package]] name = "encode_unicode" version = "0.3.6" @@ -1391,6 +1397,15 @@ dependencies = [ "winapi", ] +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.3" @@ -1608,12 +1623,28 @@ dependencies = [ "futures-util", "lua-src", "luajit-src", + "mlua_derive", "num-traits", "once_cell", "pkg-config", "rustc-hash", ] +[[package]] +name = "mlua_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9214e60d3cf1643013b107330fcd374ccec1e4ba1eef76e7e5da5e8202e71c0" +dependencies = [ + "itertools", + "once_cell", + "proc-macro-error", + "proc-macro2", + "quote", + "regex", + "syn", +] + [[package]] name = "native-tls" version = "0.2.10" diff --git a/Cargo.toml b/Cargo.toml index 6d707cfab..a76c3eb16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ proc-macro2 = { version = "1.0", features = ["span-locations"] } lazy_static = "1.4.0" # plugin packages -mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "send"] } +mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "send", "macros"] } ctrlc = "3.2.3" [[bin]] diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 9c99c8266..2e02b8946 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -4,7 +4,7 @@ use std::{ sync::Mutex, }; -use mlua::{AsChunk, Lua, Table}; +use mlua::{AsChunk, chunk, Lua, Table}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -44,7 +44,7 @@ impl PluginManager { // // if plugin system is available, just set manager to nil. // lua.globals().set("manager", mlua::Value::Nil).unwrap(); return Ok(()); - } + } let manager = lua.create_table().unwrap(); let plugin_dir = Self::init_plugin_dir(); @@ -108,19 +108,39 @@ impl PluginManager { lua.globals().set("manager", manager).unwrap(); for (idx, path, info) in init_list { - let res = lua.load(&format!("manager[{idx}].on_init()")).exec(); - if res.is_ok() { - let mut file = std::fs::File::create(path).unwrap(); - let value = json!({ - "name": info.name, - "author": info.author, - "repository": info.repository, - "version": info.version, - "generate_time": chrono::Local::now().timestamp(), - }); - let buffer = serde_json::to_string_pretty(&value).unwrap(); - let buffer = buffer.as_bytes(); - file.write_all(buffer).unwrap(); + let res = lua + .load(mlua::chunk! { + manager[$idx].on_init() + }) + .eval::(); + match res { + Ok(true) => { + // plugin init success, create `dcp.json` file. + let mut file = std::fs::File::create(path).unwrap(); + let value = json!({ + "name": info.name, + "author": info.author, + "repository": info.repository, + "version": info.version, + "generate_time": chrono::Local::now().timestamp(), + }); + let buffer = serde_json::to_string_pretty(&value).unwrap(); + let buffer = buffer.as_bytes(); + file.write_all(buffer).unwrap(); + } + Ok(false) => { + log::warn!("Plugin init function result is `false`, init failed."); + let _ = lua.load(mlua::chunk! { + table.remove(manager, $idx) + }).exec(); + } + Err(e) => { + // plugin init failed + let _ = lua.load(mlua::chunk! { + table.remove(manager, $idx) + }).exec(); + log::warn!("Plugin init failed: {e}"); + } } } return Ok(()); @@ -269,4 +289,8 @@ impl PluginManager { res } + + pub fn plugin_status() { + let lua = LUA.lock().unwrap(); + } } From b3dcebcc50fab94241f088503f783d1d6d8cc31b Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Mon, 3 Oct 2022 08:47:58 -0700 Subject: [PATCH 41/48] feat: commit code --- src/plugin/interface/fs.rs | 30 ++++++++++++++++++++++++++---- src/plugin/mod.rs | 10 +++------- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs index afe9a8183..cf90d171c 100644 --- a/src/plugin/interface/fs.rs +++ b/src/plugin/interface/fs.rs @@ -2,9 +2,11 @@ use std::{ fs::{create_dir, create_dir_all, remove_dir_all}, path::PathBuf, io::{Read, Write}, }; +use std::fs::File; use mlua::UserData; - +use flate2::read::GzDecoder; +use tar::Archive; use crate::tools::extract_zip; pub struct PluginFileSystem; @@ -48,10 +50,30 @@ impl UserData for PluginFileSystem { let file = PathBuf::from(args.0); let target = PathBuf::from(args.1); let res = extract_zip(&file, &target); - if let Err(e) = res { - return Err(mlua::Error::RuntimeError(e.to_string())); + if let Err(_) = res { + return Ok(false); } - Ok(()) + Ok(true) + }); + methods.add_function("untar_gz_file", |_, args: (String, String)| { + + let file = PathBuf::from(args.0); + let target = PathBuf::from(args.1); + + let tar_gz = if let Ok(v) = File::open(file) { + v + } else { + return Ok(false); + }; + + let tar = GzDecoder::new(tar_gz); + let mut archive = Archive::new(tar); + if archive.unpack(&target).is_err() { + return Ok(false); + } + + + Ok(true) }); } } diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 2e02b8946..4253280a1 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -4,7 +4,7 @@ use std::{ sync::Mutex, }; -use mlua::{AsChunk, chunk, Lua, Table}; +use mlua::{AsChunk, Lua, Table}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -136,10 +136,10 @@ impl PluginManager { } Err(e) => { // plugin init failed + log::warn!("Plugin init failed: {e}"); let _ = lua.load(mlua::chunk! { table.remove(manager, $idx) }).exec(); - log::warn!("Plugin init failed: {e}"); } } } @@ -289,8 +289,4 @@ impl PluginManager { res } - - pub fn plugin_status() { - let lua = LUA.lock().unwrap(); - } -} +} \ No newline at end of file From f238e43bff2ae66b8e095c2ec7d768383ded8595 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Thu, 6 Oct 2022 17:25:57 -0700 Subject: [PATCH 42/48] feat: commit code --- src/config.rs | 11 +++++------ src/main.rs | 11 +++++------ src/plugin/mod.rs | 16 ++++------------ 3 files changed, 14 insertions(+), 24 deletions(-) diff --git a/src/config.rs b/src/config.rs index 3d6fe65a4..309dcd9c0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,4 @@ -use crate::{error::Result, plugin::PluginConfig}; +use crate::error::Result; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, fs::File, io::Read, path::PathBuf}; @@ -6,6 +6,7 @@ use std::{collections::HashMap, fs::File, io::Read, path::PathBuf}; pub struct DioxusConfig { pub application: ApplicationConfig, pub web: WebConfig, + pub plugin: toml::Value, } impl DioxusConfig { @@ -36,8 +37,7 @@ impl Default for DioxusConfig { asset_dir: Some(PathBuf::from("public")), tools: None, - plugins: None, - + sub_package: None, }, web: WebConfig { @@ -59,6 +59,7 @@ impl Default for DioxusConfig { script: Some(vec![]), }, }, + plugin: toml::Value::Table(toml::map::Map::new()) } } } @@ -69,9 +70,8 @@ pub struct ApplicationConfig { pub default_platform: String, pub out_dir: Option, pub asset_dir: Option, - + pub tools: Option>, - pub plugins: Option, pub sub_package: Option, } @@ -223,5 +223,4 @@ impl CrateConfig { self.features = Some(features); self } - } diff --git a/src/main.rs b/src/main.rs index 300d4ef73..db8bbb6b7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,5 @@ use clap::Parser; -use dioxus_cli::{*, plugin::{PluginManager, PluginConfig}}; +use dioxus_cli::{plugin::PluginManager, *}; use std::process::exit; #[tokio::main] @@ -7,11 +7,10 @@ async fn main() -> Result<()> { let args = Cli::parse(); set_up_logging(); - let plugin_state = PluginManager::init(&PluginConfig { - available: true, - required: vec![], - }); - + let dioxus_config = DioxusConfig::load()?; + + let plugin_state = PluginManager::init(dioxus_config.plugin); + if let Err(e) = plugin_state { log::error!("🚫 Plugin system initialization failed: {e}"); exit(1); diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 4253280a1..464c83434 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -5,7 +5,6 @@ use std::{ }; use mlua::{AsChunk, Lua, Table}; -use serde::{Deserialize, Serialize}; use serde_json::json; use crate::{ @@ -28,23 +27,16 @@ lazy_static::lazy_static! { static ref LUA: Mutex = Mutex::new(Lua::new()); } -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PluginConfig { - pub available: bool, - pub required: Vec, -} - pub struct PluginManager; impl PluginManager { - pub fn init(config: &PluginConfig) -> anyhow::Result<()> { + pub fn init(config: toml::Value) -> anyhow::Result<()> { let lua = LUA.lock().unwrap(); - if !config.available { - // // if plugin system is available, just set manager to nil. - // lua.globals().set("manager", mlua::Value::Nil).unwrap(); + if !config.is_table() { + // if plugins config is not a table, then termination init return Ok(()); - } + } let manager = lua.create_table().unwrap(); let plugin_dir = Self::init_plugin_dir(); From cf9a9513df8cd7028594d4ab8d7608ac2f6d9226 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Sat, 8 Oct 2022 21:28:06 -0700 Subject: [PATCH 43/48] feat: commit code --- src/plugin/argument/mod.rs | 0 src/plugin/mod.rs | 25 +++++++++++++------------ 2 files changed, 13 insertions(+), 12 deletions(-) delete mode 100644 src/plugin/argument/mod.rs diff --git a/src/plugin/argument/mod.rs b/src/plugin/argument/mod.rs deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 464c83434..e09eeced8 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -33,11 +33,6 @@ impl PluginManager { pub fn init(config: toml::Value) -> anyhow::Result<()> { let lua = LUA.lock().unwrap(); - if !config.is_table() { - // if plugins config is not a table, then termination init - return Ok(()); - } - let manager = lua.create_table().unwrap(); let plugin_dir = Self::init_plugin_dir(); @@ -55,6 +50,8 @@ impl PluginManager { lua.globals() .set("library_dir", plugin_dir.to_str().unwrap()) .unwrap(); + // lua.globals() + // .set("config_info", ); let mut index: u32 = 1; let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); @@ -122,16 +119,20 @@ impl PluginManager { } Ok(false) => { log::warn!("Plugin init function result is `false`, init failed."); - let _ = lua.load(mlua::chunk! { - table.remove(manager, $idx) - }).exec(); + let _ = lua + .load(mlua::chunk! { + table.remove(manager, $idx) + }) + .exec(); } Err(e) => { // plugin init failed log::warn!("Plugin init failed: {e}"); - let _ = lua.load(mlua::chunk! { - table.remove(manager, $idx) - }).exec(); + let _ = lua + .load(mlua::chunk! { + table.remove(manager, $idx) + }) + .exec(); } } } @@ -281,4 +282,4 @@ impl PluginManager { res } -} \ No newline at end of file +} From e1497acef48559ce610ff430909559e646ecb6b1 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Mon, 10 Oct 2022 22:38:30 -0700 Subject: [PATCH 44/48] feat: types --- src/plugin/mod.rs | 2 +- src/plugin/types.rs | 119 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 src/plugin/types.rs diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index e09eeced8..55e8883de 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -20,7 +20,7 @@ use self::{ }, }; -pub mod argument; +mod types; pub mod interface; lazy_static::lazy_static! { diff --git a/src/plugin/types.rs b/src/plugin/types.rs new file mode 100644 index 000000000..181e09ddc --- /dev/null +++ b/src/plugin/types.rs @@ -0,0 +1,119 @@ +use std::collections::HashMap; + +use mlua::ToLua; + +use super::LUA; + +#[derive(Debug, Clone)] +pub struct PluginConfig { + available: bool, + config_info: HashMap>, +} + +impl<'lua> ToLua<'lua> for PluginConfig { + fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { + let table = lua.create_table()?; + + table.set("available", self.available)?; + + let config_info = lua.create_table()?; + + for (name, data) in self.config_info { + config_info.set(name, data)?; + } + + table.set("config_info", config_info)?; + + Ok(mlua::Value::Table(table)) + } +} + +impl PluginConfig { + pub fn from_toml_value(val: toml::Value) -> Self { + if let toml::Value::Table(tab) = val { + let available = tab + .get::<_>("available") + .unwrap_or(&toml::Value::Boolean(true)); + let available = available.as_bool().unwrap_or(true); + + let mut config_info = HashMap::new(); + + let lua = LUA.lock().unwrap(); + + for (name, value) in tab {} + + Self { + available, + config_info, + } + } else { + Self { + available: false, + config_info: HashMap::new(), + } + } + } +} + +#[derive(Debug, Clone)] +pub enum Value { + String(String), + Integer(i64), + Float(f64), + Boolean(bool), + Array(Vec), + Table(HashMap), +} + +impl Value { + pub fn from_toml(origin: toml::Value) -> Self { + match origin { + cargo_toml::Value::String(s) => Value::String(s), + cargo_toml::Value::Integer(i) => Value::Integer(i), + cargo_toml::Value::Float(f) => Value::Float(f), + cargo_toml::Value::Boolean(b) => Value::Boolean(b), + cargo_toml::Value::Datetime(d) => Value::String(d.to_string()), + cargo_toml::Value::Array(a) => { + let mut v = vec![]; + for i in a { + v.push(Value::from_toml(i)); + } + Value::Array(v) + }, + cargo_toml::Value::Table(t) => { + let mut h = HashMap::new(); + for (n, v) in t { + h.insert(n, Value::from_toml(v)); + } + Value::Table(h) + }, + } + } +} + +impl<'lua> ToLua<'lua> for Value { + fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { + Ok( + match self { + Value::String(s) => mlua::Value::String(lua.create_string(&s)?), + Value::Integer(i) => mlua::Value::Integer(i), + Value::Float(f) => mlua::Value::Number(f), + Value::Boolean(b) => mlua::Value::Boolean(b), + Value::Array(a) => { + let table = lua.create_table()?; + for (i, v) in a.iter().enumerate() { + table.set(i, v.clone())?; + } + mlua::Value::Table(table) + }, + Value::Table(t) => { + let table = lua.create_table()?; + for (i, v) in t.iter() { + table.set(i.clone(), v.clone())?; + } + mlua::Value::Table(table) + }, + } + ) + } +} \ No newline at end of file From 96ebe74d121a27e34c706240d4d645110d44b167 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Mon, 10 Oct 2022 22:49:52 -0700 Subject: [PATCH 45/48] feat: custom plugin config support --- src/plugin/mod.rs | 7 ++++--- src/plugin/types.rs | 15 ++++++++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 55e8883de..673f2ad5b 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -18,10 +18,11 @@ use self::{ command::PluginCommander, dirs::PluginDirs, fs::PluginFileSystem, log::PluginLogger, network::PluginNetwork, os::PluginOS, path::PluginPath, }, + types::PluginConfig, }; -mod types; pub mod interface; +mod types; lazy_static::lazy_static! { static ref LUA: Mutex = Mutex::new(Lua::new()); @@ -50,8 +51,8 @@ impl PluginManager { lua.globals() .set("library_dir", plugin_dir.to_str().unwrap()) .unwrap(); - // lua.globals() - // .set("config_info", ); + let config = PluginConfig::from_toml_value(config); + lua.globals().set("config_info", config)?; let mut index: u32 = 1; let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); diff --git a/src/plugin/types.rs b/src/plugin/types.rs index 181e09ddc..a73a09bf0 100644 --- a/src/plugin/types.rs +++ b/src/plugin/types.rs @@ -2,8 +2,6 @@ use std::collections::HashMap; use mlua::ToLua; -use super::LUA; - #[derive(Debug, Clone)] pub struct PluginConfig { available: bool, @@ -38,9 +36,15 @@ impl PluginConfig { let mut config_info = HashMap::new(); - let lua = LUA.lock().unwrap(); - - for (name, value) in tab {} + for (name, value) in tab { + if let toml::Value::Table(value) = value { + let mut map = HashMap::new(); + for (item, info) in value { + map.insert(item, Value::from_toml(info)); + } + config_info.insert(name, map); + } + } Self { available, @@ -55,6 +59,7 @@ impl PluginConfig { } } +#[allow(dead_code)] #[derive(Debug, Clone)] pub enum Value { String(String), From 0fe8e4bcbddaf29637d6d92d66038d81f6ffd94a Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Wed, 12 Oct 2022 11:47:05 -0700 Subject: [PATCH 46/48] fix: plugin init problem --- src/plugin/interface/fs.rs | 14 ++- src/plugin/interface/mod.rs | 46 +++++++++ src/plugin/mod.rs | 179 ++++++++++++++++++++++++------------ src/plugin/types.rs | 66 +++++++------ 4 files changed, 218 insertions(+), 87 deletions(-) diff --git a/src/plugin/interface/fs.rs b/src/plugin/interface/fs.rs index cf90d171c..d72e41375 100644 --- a/src/plugin/interface/fs.rs +++ b/src/plugin/interface/fs.rs @@ -42,9 +42,17 @@ impl UserData for PluginFileSystem { let path = args.0; let content = args.1; let path = PathBuf::from(path); - let mut file = std::fs::File::create(path)?; - file.write_all(content.as_bytes())?; - Ok(()) + + let file = std::fs::File::create(path); + if file.is_err() { + return Ok(false); + } + + if file.unwrap().write_all(content.as_bytes()).is_err() { + return Ok(false) + } + + Ok(true) }); methods.add_function("unzip_file", |_, args: (String, String)| { let file = PathBuf::from(args.0); diff --git a/src/plugin/interface/mod.rs b/src/plugin/interface/mod.rs index 2ef1920fc..5ed2ed827 100644 --- a/src/plugin/interface/mod.rs +++ b/src/plugin/interface/mod.rs @@ -15,6 +15,8 @@ pub struct PluginInfo<'lua> { pub author: String, pub version: String, + pub inner: PluginInner, + pub on_init: Option>, pub build: PluginBuildInfo<'lua>, pub serve: PluginServeInfo<'lua>, @@ -28,6 +30,8 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { author: String::default(), version: String::from("0.1.0"), + inner: Default::default(), + on_init: None, build: Default::default(), serve: Default::default(), @@ -46,6 +50,10 @@ impl<'lua> FromLua<'lua> for PluginInfo<'lua> { res.version = v; } + if let Ok(v) = tab.get::<_, PluginInner>("inner") { + res.inner = v; + } + if let Ok(v) = tab.get::<_, Function>("on_init") { res.on_init = Some(v); } @@ -72,6 +80,8 @@ impl<'lua> ToLua<'lua> for PluginInfo<'lua> { res.set("author", self.author.to_string())?; res.set("version", self.version.to_string())?; + res.set("inner", self.inner)?; + if let Some(e) = self.on_init { res.set("on_init", e)?; } @@ -82,6 +92,42 @@ impl<'lua> ToLua<'lua> for PluginInfo<'lua> { } } +#[derive(Debug, Clone, Default)] +pub struct PluginInner { + pub plugin_dir: String, + pub from_loader: bool, +} + +impl<'lua> FromLua<'lua> for PluginInner { + fn from_lua(lua_value: mlua::Value<'lua>, _lua: &'lua mlua::Lua) -> mlua::Result { + let mut res = Self { + plugin_dir: String::new(), + from_loader: false, + }; + + if let mlua::Value::Table(t) = lua_value { + if let Ok(v) = t.get::<_, String>("plugin_dir") { + res.plugin_dir = v; + } + if let Ok(v) = t.get::<_, bool>("from_loader") { + res.from_loader = v; + } + } + Ok(res) + } +} + +impl<'lua> ToLua<'lua> for PluginInner { + fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { + let res = lua.create_table()?; + + res.set("plugin_dir", self.plugin_dir)?; + res.set("from_loader", self.from_loader)?; + + Ok(mlua::Value::Table(res)) + } +} + #[derive(Debug, Clone, Default)] pub struct PluginBuildInfo<'lua> { pub on_start: Option>, diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index 673f2ad5b..c3d7f43ab 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -4,7 +4,7 @@ use std::{ sync::Mutex, }; -use mlua::{AsChunk, Lua, Table}; +use mlua::{Lua, Table}; use serde_json::json; use crate::{ @@ -32,9 +32,17 @@ pub struct PluginManager; impl PluginManager { pub fn init(config: toml::Value) -> anyhow::Result<()> { + let config = PluginConfig::from_toml_value(config); + + if !config.available { + return Ok(()); + } + let lua = LUA.lock().unwrap(); let manager = lua.create_table().unwrap(); + let name_index = lua.create_table().unwrap(); + let plugin_dir = Self::init_plugin_dir(); let api = lua.create_table().unwrap(); @@ -51,18 +59,27 @@ impl PluginManager { lua.globals() .set("library_dir", plugin_dir.to_str().unwrap()) .unwrap(); - let config = PluginConfig::from_toml_value(config); - lua.globals().set("config_info", config)?; + lua.globals().set("config_info", config.clone())?; let mut index: u32 = 1; - let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); let dirs = std::fs::read_dir(&plugin_dir)?; - for entry in dirs { - if entry.is_err() { - continue; + + let mut path_list = dirs + .filter(|v| v.is_ok()) + .map(|v| (v.unwrap().path(), false)) + .collect::>(); + for i in &config.loader { + let path = PathBuf::from(i); + if !path.is_dir() { + // for loader dir, we need check first, because we need give a error log. + log::error!("Plugin loader: {:?} path is not a exists directory.", path); } - let entry = entry.unwrap(); - let plugin_dir = entry.path().to_path_buf(); + path_list.push((path, true)); + } + + for entry in path_list { + let plugin_dir = entry.0.to_path_buf(); + if plugin_dir.is_dir() { let init_file = plugin_dir.join("init.lua"); if init_file.is_file() { @@ -70,21 +87,78 @@ impl PluginManager { let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); + let current_plugin_dir = plugin_dir.to_str().unwrap().to_string(); + let from_loader = entry.1; + + lua.globals() + .set("_temp_plugin_dir", current_plugin_dir.clone())?; + lua.globals().set("_temp_from_loader", from_loader)?; + let info = lua.load(&buffer).eval::(); match info { - Ok(info) => { - let _ = manager.set(index, info.clone()); - - let dir_name_str = plugin_dir.name().unwrap().to_string(); - lua.globals().set("current_dir_name", dir_name_str).unwrap(); + Ok(mut info) => { + if name_index.contains_key(info.name.clone()).unwrap_or(false) + && !from_loader + { + // found same name plugin, intercept load + log::warn!( + "Plugin {} has been intercepted. [mulit-load]", + info.name + ); + continue; + } + info.inner.plugin_dir = current_plugin_dir; + info.inner.from_loader = from_loader; // call `on_init` if file "dcp.json" not exists let dcp_file = plugin_dir.join("dcp.json"); if !dcp_file.is_file() { - init_list.push((index, dcp_file, info)); - } + if let Some(func) = info.clone().on_init { + let result = func.call::<_, bool>(()); + match result { + Ok(true) => { + // plugin init success, create `dcp.json` file. + let mut file = std::fs::File::create(dcp_file).unwrap(); + let value = json!({ + "name": info.name, + "author": info.author, + "repository": info.repository, + "version": info.version, + "generate_time": chrono::Local::now().timestamp(), + }); + let buffer = + serde_json::to_string_pretty(&value).unwrap(); + let buffer = buffer.as_bytes(); + file.write_all(buffer).unwrap(); - index += 1; + // insert plugin-info into plugin-manager + if let Ok(index) = + name_index.get::<_, u32>(info.name.clone()) + { + let _ = manager.set(index, info.clone()); + } else { + let _ = manager.set(index, info.clone()); + index += 1; + let _ = name_index.set(info.name, index); + } + } + Ok(false) => { + log::warn!("Plugin init function result is `false`, init failed."); + } + Err(e) => { + log::warn!("Plugin init failed: {e}"); + } + } + } + } else { + if let Ok(index) = name_index.get::<_, u32>(info.name.clone()) { + let _ = manager.set(index, info.clone()); + } else { + let _ = manager.set(index, info.clone()); + index += 1; + let _ = name_index.set(info.name, index); + } + } } Err(_e) => { let dir_name = plugin_dir.file_name().unwrap().to_str().unwrap(); @@ -97,46 +171,6 @@ impl PluginManager { lua.globals().set("manager", manager).unwrap(); - for (idx, path, info) in init_list { - let res = lua - .load(mlua::chunk! { - manager[$idx].on_init() - }) - .eval::(); - match res { - Ok(true) => { - // plugin init success, create `dcp.json` file. - let mut file = std::fs::File::create(path).unwrap(); - let value = json!({ - "name": info.name, - "author": info.author, - "repository": info.repository, - "version": info.version, - "generate_time": chrono::Local::now().timestamp(), - }); - let buffer = serde_json::to_string_pretty(&value).unwrap(); - let buffer = buffer.as_bytes(); - file.write_all(buffer).unwrap(); - } - Ok(false) => { - log::warn!("Plugin init function result is `false`, init failed."); - let _ = lua - .load(mlua::chunk! { - table.remove(manager, $idx) - }) - .exec(); - } - Err(e) => { - // plugin init failed - log::warn!("Plugin init failed: {e}"); - let _ = lua - .load(mlua::chunk! { - table.remove(manager, $idx) - }) - .exec(); - } - } - } return Ok(()); } @@ -264,7 +298,7 @@ impl PluginManager { plugin_path } - pub fn plugin_list() -> Vec { + pub fn plugin_list_from_dir() -> Vec { let mut res = vec![]; let app_path = app_path(); @@ -280,6 +314,35 @@ impl PluginManager { } } } + res + } + + pub fn plugin_list() -> Vec { + let mut res = vec![]; + + if let Ok(lua) = LUA.lock() { + let list = lua + .load(mlua::chunk!( + local list = {} + for key, value in ipairs(manager) do + table.insert(list, {name = value.name, loader = value.inner.from_loader}) + end + return list + )) + .eval::>() + .unwrap_or_default(); + for i in list { + let name = i.get::<_, String>("name").unwrap(); + let loader = i.get::<_, bool>("loader").unwrap(); + + let text = if loader { + format!("{name} [:loader]") + } else { + name + }; + res.push(text); + } + } res } diff --git a/src/plugin/types.rs b/src/plugin/types.rs index a73a09bf0..d22c1423c 100644 --- a/src/plugin/types.rs +++ b/src/plugin/types.rs @@ -4,8 +4,9 @@ use mlua::ToLua; #[derive(Debug, Clone)] pub struct PluginConfig { - available: bool, - config_info: HashMap>, + pub available: bool, + pub loader: Vec, + pub config_info: HashMap>, } impl<'lua> ToLua<'lua> for PluginConfig { @@ -13,6 +14,7 @@ impl<'lua> ToLua<'lua> for PluginConfig { let table = lua.create_table()?; table.set("available", self.available)?; + table.set("loader", self.loader)?; let config_info = lua.create_table()?; @@ -34,9 +36,21 @@ impl PluginConfig { .unwrap_or(&toml::Value::Boolean(true)); let available = available.as_bool().unwrap_or(true); + let mut loader = vec![]; + if let Some(origin) = tab.get("loader") { + if origin.is_array() { + for i in origin.as_array().unwrap() { + loader.push(i.as_str().unwrap_or_default().to_string()); + } + } + } + let mut config_info = HashMap::new(); for (name, value) in tab { + if name == "available" || name == "loader" { + continue; + } if let toml::Value::Table(value) = value { let mut map = HashMap::new(); for (item, info) in value { @@ -48,11 +62,13 @@ impl PluginConfig { Self { available, + loader, config_info, } } else { Self { available: false, + loader: vec![], config_info: HashMap::new(), } } @@ -84,41 +100,39 @@ impl Value { v.push(Value::from_toml(i)); } Value::Array(v) - }, + } cargo_toml::Value::Table(t) => { let mut h = HashMap::new(); for (n, v) in t { h.insert(n, Value::from_toml(v)); } Value::Table(h) - }, + } } } } impl<'lua> ToLua<'lua> for Value { fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result> { - Ok( - match self { - Value::String(s) => mlua::Value::String(lua.create_string(&s)?), - Value::Integer(i) => mlua::Value::Integer(i), - Value::Float(f) => mlua::Value::Number(f), - Value::Boolean(b) => mlua::Value::Boolean(b), - Value::Array(a) => { - let table = lua.create_table()?; - for (i, v) in a.iter().enumerate() { - table.set(i, v.clone())?; - } - mlua::Value::Table(table) - }, - Value::Table(t) => { - let table = lua.create_table()?; - for (i, v) in t.iter() { - table.set(i.clone(), v.clone())?; - } - mlua::Value::Table(table) - }, + Ok(match self { + Value::String(s) => mlua::Value::String(lua.create_string(&s)?), + Value::Integer(i) => mlua::Value::Integer(i), + Value::Float(f) => mlua::Value::Number(f), + Value::Boolean(b) => mlua::Value::Boolean(b), + Value::Array(a) => { + let table = lua.create_table()?; + for (i, v) in a.iter().enumerate() { + table.set(i, v.clone())?; + } + mlua::Value::Table(table) } - ) + Value::Table(t) => { + let table = lua.create_table()?; + for (i, v) in t.iter() { + table.set(i.clone(), v.clone())?; + } + mlua::Value::Table(table) + } + }) } -} \ No newline at end of file +} From 39e38917d6d5795065903705a354cb15634f6b68 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Wed, 12 Oct 2022 16:37:26 -0700 Subject: [PATCH 47/48] feat: add api function --- Cargo.toml | 2 +- src/plugin/interface/network.rs | 6 +++--- src/plugin/interface/path.rs | 14 ++++++++------ src/plugin/mod.rs | 19 ------------------- 4 files changed, 12 insertions(+), 29 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b18c90a9e..4fe9eeb7f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,7 @@ walkdir = "2" # tools download dirs = "4.0.0" -reqwest = { version = "0.11", features = ["rustls-tls", "stream", "trust-dns"] } +reqwest = { version = "0.11", features = ["rustls-tls", "stream", "trust-dns", "blocking"] } flate2 = "1.0.22" tar = "0.4.38" zip = "0.6.2" diff --git a/src/plugin/interface/network.rs b/src/plugin/interface/network.rs index af6b6ae12..8d940ddc4 100644 --- a/src/plugin/interface/network.rs +++ b/src/plugin/interface/network.rs @@ -5,13 +5,13 @@ use mlua::UserData; pub struct PluginNetwork; impl UserData for PluginNetwork { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { - methods.add_async_function("download_file", |_, args: (String, String)| async move { + methods.add_function("download_file", |_, args: (String, String)| { let url = args.0; let path = args.1; - let resp = reqwest::get(url).await; + let resp = reqwest::blocking::get(url); if let Ok(resp) = resp { - let mut content = Cursor::new(resp.bytes().await.unwrap()); + let mut content = Cursor::new(resp.bytes().unwrap()); let file = std::fs::File::create(PathBuf::from(path)); if file.is_err() { return Ok(false); diff --git a/src/plugin/interface/path.rs b/src/plugin/interface/path.rs index 1dd3997cf..f0d36bd78 100644 --- a/src/plugin/interface/path.rs +++ b/src/plugin/interface/path.rs @@ -1,16 +1,18 @@ use std::path::PathBuf; -use mlua::UserData; +use mlua::{UserData, Variadic}; pub struct PluginPath; impl UserData for PluginPath { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { // join function - methods.add_function("join", |_, args: (String, String)| { - let current_path = PathBuf::from(args.0); - let new_path = current_path.join(args.1); - Ok(new_path.to_str().unwrap().to_string()) - }); + methods.add_function("join", |_, args: Variadic| { + let mut path = PathBuf::new(); + for i in args { + path = path.join(i); + } + Ok(path.to_str().unwrap().to_string()) + }); // parent function methods.add_function("parent", |_, path: String| { diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index c3d7f43ab..c77764fd4 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -298,25 +298,6 @@ impl PluginManager { plugin_path } - pub fn plugin_list_from_dir() -> Vec { - let mut res = vec![]; - - let app_path = app_path(); - let plugin_path = app_path.join("plugins"); - - let child_dirs = std::fs::read_dir(plugin_path).unwrap(); - for p in child_dirs { - if let Ok(p) = p { - if p.path().is_dir() && p.file_name() != "library" { - if p.path().join("init.lua").is_file() { - res.push(p.file_name().to_str().unwrap().to_string()); - } - } - } - } - res - } - pub fn plugin_list() -> Vec { let mut res = vec![]; From bbc9e1b3a2a92efcf3ee9be59e63e1123a291a89 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Thu, 3 Nov 2022 00:30:47 -0700 Subject: [PATCH 48/48] feat: default plugin info --- .fleet/settings.json | 0 src/config.rs | 10 ++++++++-- src/server/mod.rs | 1 - 3 files changed, 8 insertions(+), 3 deletions(-) create mode 100644 .fleet/settings.json diff --git a/.fleet/settings.json b/.fleet/settings.json new file mode 100644 index 000000000..e69de29bb diff --git a/src/config.rs b/src/config.rs index 309dcd9c0..5170f8756 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,9 +6,15 @@ use std::{collections::HashMap, fs::File, io::Read, path::PathBuf}; pub struct DioxusConfig { pub application: ApplicationConfig, pub web: WebConfig, + + #[serde(default = "default_plugin")] pub plugin: toml::Value, } +fn default_plugin() -> toml::Value { + toml::Value::Boolean(true) +} + impl DioxusConfig { pub fn load() -> crate::error::Result { let crate_dir = crate::cargo::crate_root()?; @@ -23,7 +29,7 @@ impl DioxusConfig { dioxus_conf_file.read_to_string(&mut meta_str)?; toml::from_str::(&meta_str) - .map_err(|_| crate::Error::Unique("Dioxus.toml parse failed".into())) + .map_err(|_| crate::Error::Unique("Dioxus.toml parse failed".into())) } } @@ -59,7 +65,7 @@ impl Default for DioxusConfig { script: Some(vec![]), }, }, - plugin: toml::Value::Table(toml::map::Map::new()) + plugin: toml::Value::Table(toml::map::Map::new()), } } } diff --git a/src/server/mod.rs b/src/server/mod.rs index 3e5f19e48..8bf7f3cb8 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -108,7 +108,6 @@ pub async fn startup_hot_reload(port: u16, config: CrateConfig) -> Result<()> { .clone() .unwrap_or_else(|| vec![PathBuf::from("src")]); - let watcher_config = config.clone(); let watcher_config = config.clone(); let mut watcher = RecommendedWatcher::new( move |evt: notify::Result| {