feat: support some event

This commit is contained in:
YuKun Liu 2022-09-21 16:56:36 -07:00
parent 59b8a84530
commit 37ef7c3ff9
7 changed files with 51 additions and 44 deletions

1
Cargo.lock generated
View file

@ -621,6 +621,7 @@ dependencies = [
"html_parser", "html_parser",
"hyper", "hyper",
"indicatif", "indicatif",
"lazy_static",
"log", "log",
"mlua", "mlua",
"notify", "notify",

View file

@ -61,6 +61,7 @@ proc-macro2 = { version = "1.0", features = ["span-locations"] }
# plugin packages # plugin packages
mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "send"] } mlua = { version = "0.8.1", features = ["lua54", "vendored", "async", "send"] }
lazy_static = "1.4.0"
[[bin]] [[bin]]
path = "src/main.rs" path = "src/main.rs"

View file

@ -11,7 +11,7 @@ pub struct Build {
} }
impl Build { impl Build {
pub fn build(self, plugin_manager: PluginManager) -> Result<()> { pub fn build(self) -> Result<()> {
let mut crate_config = crate::CrateConfig::new()?; let mut crate_config = crate::CrateConfig::new()?;
// change the release state. // change the release state.
@ -34,7 +34,7 @@ impl Build {
.clone() .clone()
}); });
let _ = plugin_manager.on_build_start(&crate_config, &platform); let _ = PluginManager::on_build_start(&crate_config, &platform);
match platform.as_str() { match platform.as_str() {
"web" => { "web" => {
@ -65,7 +65,7 @@ impl Build {
)?; )?;
file.write_all(temp.as_bytes())?; file.write_all(temp.as_bytes())?;
let _ = plugin_manager.on_build_finish(&crate_config, &platform); let _ = PluginManager::on_build_finish(&crate_config, &platform);
Ok(()) Ok(())
} }

View file

@ -1,5 +1,3 @@
use crate::plugin::PluginManager;
use super::*; use super::*;
use std::{ use std::{
io::Write, io::Write,
@ -16,7 +14,7 @@ pub struct Serve {
} }
impl 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()?; let mut crate_config = crate::CrateConfig::new()?;
// change the relase state. // change the relase state.
@ -65,7 +63,7 @@ impl Serve {
Serve::regen_dev_page(&crate_config)?; Serve::regen_dev_page(&crate_config)?;
// start the develop server // 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(()) Ok(())
} }

View file

@ -7,10 +7,10 @@ async fn main() -> Result<()> {
let args = Cli::parse(); let args = Cli::parse();
set_up_logging(); set_up_logging();
let plugin_manager = PluginManager::init(&PluginConfig { let _ = PluginManager::init(&PluginConfig {
available: true, available: true,
required: vec![], required: vec![],
}).unwrap(); });
match args.action { match args.action {
Commands::Translate(opts) => { Commands::Translate(opts) => {
@ -21,7 +21,7 @@ async fn main() -> Result<()> {
} }
Commands::Build(opts) => { Commands::Build(opts) => {
if let Err(e) = opts.build(plugin_manager) { if let Err(e) = opts.build() {
log::error!("🚫 Build project failed: {}", e); log::error!("🚫 Build project failed: {}", e);
exit(1); exit(1);
} }
@ -35,7 +35,7 @@ async fn main() -> Result<()> {
} }
Commands::Serve(opts) => { 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); log::error!("🚫 Serve startup failed: {}", e);
exit(1); exit(1);
} }

View file

@ -1,6 +1,7 @@
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
path::PathBuf, path::PathBuf,
sync::Mutex,
}; };
use mlua::{AsChunk, Lua, Table}; use mlua::{AsChunk, Lua, Table};
@ -23,23 +24,29 @@ use self::{
pub mod argument; pub mod argument;
pub mod interface; pub mod interface;
lazy_static::lazy_static! {
static ref LUA: Mutex<Lua> = Mutex::new(Lua::new());
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfig { pub struct PluginConfig {
pub available: bool, pub available: bool,
pub required: Vec<String>, pub required: Vec<String>,
} }
pub struct PluginManager { pub struct PluginManager;
lua: Lua,
}
impl PluginManager { impl PluginManager {
pub fn init(config: &PluginConfig) -> Option<Self> { pub fn init(config: &PluginConfig) -> bool {
if !config.available { 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 manager = lua.create_table().unwrap();
let plugin_dir = Self::init_plugin_dir(); let plugin_dir = Self::init_plugin_dir();
@ -61,7 +68,12 @@ impl PluginManager {
let mut index: u32 = 1; let mut index: u32 = 1;
let mut init_list: Vec<(u32, PathBuf, PluginInfo)> = Vec::new(); 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() { if entry.is_err() {
continue; continue;
} }
@ -117,12 +129,12 @@ impl PluginManager {
file.write_all(buffer).unwrap(); file.write_all(buffer).unwrap();
} }
} }
true
Some(Self { lua })
} }
pub fn on_build_start(&self, crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> { pub fn on_build_start(crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> {
let lua = &self.lua;
let lua = LUA.lock().unwrap();
let manager = lua.globals().get::<_, Table>("manager")?; let manager = lua.globals().get::<_, Table>("manager")?;
@ -142,12 +154,8 @@ impl PluginManager {
Ok(()) Ok(())
} }
pub fn on_build_finish( pub fn on_build_finish(crate_config: &CrateConfig, platform: &str) -> anyhow::Result<()> {
&self, let lua = LUA.lock().unwrap();
crate_config: &CrateConfig,
platform: &str,
) -> anyhow::Result<()> {
let lua = &self.lua;
let manager = lua.globals().get::<_, Table>("manager")?; let manager = lua.globals().get::<_, Table>("manager")?;
@ -167,8 +175,8 @@ impl PluginManager {
Ok(()) Ok(())
} }
pub fn on_serve_start(&self, crate_config: &CrateConfig) -> anyhow::Result<()> { pub fn on_serve_start(crate_config: &CrateConfig) -> anyhow::Result<()> {
let lua = &self.lua; let lua = LUA.lock().unwrap();
let manager = lua.globals().get::<_, Table>("manager")?; let manager = lua.globals().get::<_, Table>("manager")?;
@ -185,8 +193,8 @@ impl PluginManager {
Ok(()) Ok(())
} }
pub fn on_serve_rebuild(&self, timestamp: i64, files: Vec<PathBuf>) -> anyhow::Result<()> { pub fn on_serve_rebuild(timestamp: i64, files: Vec<PathBuf>) -> anyhow::Result<()> {
let lua = &self.lua; let lua = LUA.lock().unwrap();
let manager = lua.globals().get::<_, Table>("manager")?; let manager = lua.globals().get::<_, Table>("manager")?;
@ -208,8 +216,8 @@ impl PluginManager {
Ok(()) Ok(())
} }
pub fn on_serve_shutdown(&self, crate_config: &CrateConfig) -> anyhow::Result<()> { pub fn on_serve_shutdown(crate_config: &CrateConfig) -> anyhow::Result<()> {
let lua = &self.lua; let lua = LUA.lock().unwrap();
let manager = lua.globals().get::<_, Table>("manager")?; let manager = lua.globals().get::<_, Table>("manager")?;

View file

@ -52,11 +52,11 @@ struct WsReloadState {
update: broadcast::Sender<()>, 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 { if config.hot_reload {
startup_hot_reload(port, config, plugin_manager).await? startup_hot_reload(port, config).await?
} else { } else {
startup_default(port, config, plugin_manager).await? startup_default(port, config).await?
} }
Ok(()) Ok(())
} }
@ -64,13 +64,12 @@ pub async fn startup(port: u16, config: CrateConfig, plugin_manager: PluginManag
pub async fn startup_hot_reload( pub async fn startup_hot_reload(
port: u16, port: u16,
config: CrateConfig, config: CrateConfig,
plugin_manager: PluginManager,
) -> Result<()> { ) -> Result<()> {
let first_build_result = crate::builder::build(&config, false)?; let first_build_result = crate::builder::build(&config, false)?;
log::info!("🚀 Starting development server..."); log::info!("🚀 Starting development server...");
plugin_manager.on_serve_start(&config)?; PluginManager::on_serve_start(&config)?;
let dist_path = config.out_dir.clone(); let dist_path = config.out_dir.clone();
let (reload_tx, _) = broadcast::channel(100); let (reload_tx, _) = broadcast::channel(100);
@ -283,7 +282,6 @@ pub async fn startup_hot_reload(
pub async fn startup_default( pub async fn startup_default(
port: u16, port: u16,
config: CrateConfig, config: CrateConfig,
plugin_manager: PluginManager,
) -> Result<()> { ) -> Result<()> {
let first_build_result = crate::builder::build(&config, false)?; 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")]); .unwrap_or_else(|| vec![PathBuf::from("src")]);
let watcher_config = config.clone(); let watcher_config = config.clone();
let wacher_plugin_manager = plugin_manager;
let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| { let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| {
let config = watcher_config.clone(); let config = watcher_config.clone();
if let Ok(e) = info { if let Ok(e) = info {
@ -331,8 +328,10 @@ pub async fn startup_default(
elapsed_time: res.elapsed_time, elapsed_time: res.elapsed_time,
}, },
); );
let _ = plugin_manager let _ = PluginManager::on_serve_rebuild(
.on_serve_rebuild(chrono::Local::now().timestamp(), e.paths); chrono::Local::now().timestamp(),
e.paths,
);
} }
Err(e) => log::error!("{}", e), 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_config = config.clone();
let file_service = ServiceBuilder::new() let file_service = ServiceBuilder::new()