move into feature

This commit is contained in:
Evan Almloff committed 2022-06-09 11:58:09 -05:00
1 parent 61e9f56816
commit f19958d766
3 files changed
+58 -29

No files matched your search

+6 -4
View File
@@ -46,10 +46,12 @@ flate2 = "1.0.22"
tar = "0.4.38" tar = "0.4.38"
tower = "0.4.12" tower = "0.4.12"
# hot reload syn = { version = "1.0", optional = true }
syn = "1.0" dioxus-rsx-interpreter = { path = "../dioxus/packages/rsx_interpreter", optional = true }
dioxus-rsx-interpreter = { path = "../dioxus/packages/rsx_interpreter" } proc-macro2 = { version = "1.0", features = ["span-locations"], optional = true }
proc-macro2 = { version = "1.0", features = ["span-locations"] }
[features]
hot_reload = ["dioxus-rsx-interpreter", "proc-macro2", "syn"]
[[bin]] [[bin]]
path = "src/main.rs" path = "src/main.rs"
+1 -1
View File
@@ -19,5 +19,5 @@ pub use error::*;
pub mod logging; pub mod logging;
pub use logging::*; pub use logging::*;
#[cfg(feature = "hot_reload")]
pub mod hot_reload; pub mod hot_reload;
pub use hot_reload::*;
+51 -24
View File
@@ -7,26 +7,34 @@ use axum::{
Router, Router,
}; };
use notify::{RecommendedWatcher, Watcher}; use notify::{RecommendedWatcher, Watcher};
use std::{fs::File, io::Read, sync::Mutex}; use std::{fs::File, io::Read};
use syn::__private::ToTokens;
use std::{path::PathBuf, sync::Arc}; use std::{path::PathBuf, sync::Arc};
use tower::ServiceBuilder; use tower::ServiceBuilder;
use tower_http::services::fs::{ServeDir, ServeFileSystemResponseBody}; use tower_http::services::fs::{ServeDir, ServeFileSystemResponseBody};
use crate::{builder, find_rsx, serve::Serve, CrateConfig, Result}; use crate::{builder, serve::Serve, CrateConfig, Result};
use tokio::sync::broadcast; use tokio::sync::broadcast;
use std::collections::HashMap; #[cfg(feature = "hot_reload")]
mod hot_reload_improts {
use dioxus_rsx_interpreter::{error::RecompileReason, CodeLocation, SetRsxMessage}; pub use crate::hot_reload::{find_rsx, DiffResult};
pub use dioxus_rsx_interpreter::{error::RecompileReason, CodeLocation, SetRsxMessage};
pub use std::collections::HashMap;
pub use std::sync::Mutex;
pub use syn::__private::ToTokens;
}
#[cfg(feature = "hot_reload")]
use hot_reload_improts::*;
struct WsReloadState { struct WsReloadState {
update: broadcast::Sender<String>, update: broadcast::Sender<String>,
#[cfg(feature = "hot_reload")]
last_file_rebuild: Arc<Mutex<HashMap<String, String>>>, last_file_rebuild: Arc<Mutex<HashMap<String, String>>>,
watcher_config: CrateConfig, watcher_config: CrateConfig,
} }
#[cfg(feature = "hot_reload")]
struct HotReloadState { struct HotReloadState {
messages: broadcast::Sender<SetRsxMessage>, messages: broadcast::Sender<SetRsxMessage>,
update: broadcast::Sender<String>, update: broadcast::Sender<String>,
@@ -39,19 +47,24 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
let (reload_tx, _) = broadcast::channel(100); let (reload_tx, _) = broadcast::channel(100);
#[cfg(feature = "hot_reload")]
let last_file_rebuild = Arc::new(Mutex::new(HashMap::new())); let last_file_rebuild = Arc::new(Mutex::new(HashMap::new()));
#[cfg(feature = "hot_reload")]
let ws_reload_state = Arc::new(WsReloadState {
update: reload_tx.clone(),
last_file_rebuild: last_file_rebuild.clone(),
watcher_config: config.clone(),
});
let hot_reload_tx = broadcast::channel(100).0; let hot_reload_tx = broadcast::channel(100).0;
#[cfg(feature = "hot_reload")]
let hot_reload_state = Arc::new(HotReloadState { let hot_reload_state = Arc::new(HotReloadState {
messages: hot_reload_tx.clone(), messages: hot_reload_tx.clone(),
update: reload_tx.clone(), update: reload_tx.clone(),
}); });
#[cfg(feature = "hot_reload")]
let crate_dir = config.crate_dir.clone();
let ws_reload_state = Arc::new(WsReloadState {
update: reload_tx.clone(),
#[cfg(feature = "hot_reload")]
last_file_rebuild: last_file_rebuild.clone(),
watcher_config: config.clone(),
});
let mut last_update_time = chrono::Local::now().timestamp(); let mut last_update_time = chrono::Local::now().timestamp();
@@ -64,8 +77,6 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
.clone() .clone()
.unwrap_or_else(|| vec![PathBuf::from("src")]); .unwrap_or_else(|| vec![PathBuf::from("src")]);
let crate_dir = config.crate_dir.clone();
let mut watcher = RecommendedWatcher::new(move |evt: notify::Result<notify::Event>| { let mut watcher = RecommendedWatcher::new(move |evt: notify::Result<notify::Event>| {
if let Ok(evt) = evt { if let Ok(evt) = evt {
if let notify::EventKind::Modify(_) = evt.kind { if let notify::EventKind::Modify(_) = evt.kind {
@@ -76,19 +87,21 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
if src.is_empty() { if src.is_empty() {
continue; continue;
} }
#[cfg(feature = "hot_reload")]
{
if let Ok(syntax) = syn::parse_file(&src) { if let Ok(syntax) = syn::parse_file(&src) {
let mut last_file_rebuild = last_file_rebuild.lock().unwrap(); let mut last_file_rebuild = last_file_rebuild.lock().unwrap();
if let Some(old_str) = last_file_rebuild.get(path.to_str().unwrap()) { if let Some(old_str) = last_file_rebuild.get(path.to_str().unwrap()) {
if let Ok(old) = syn::parse_file(&old_str) { if let Ok(old) = syn::parse_file(&old_str) {
match find_rsx(&syntax, &old) { match find_rsx(&syntax, &old) {
crate::DiffResult::CodeChanged => { DiffResult::CodeChanged => {
log::info!("reload required"); log::info!("reload required");
if chrono::Local::now().timestamp() > last_update_time { if chrono::Local::now().timestamp() > last_update_time {
let _ = reload_tx.send("reload".into()); let _ = reload_tx.send("reload".into());
last_update_time = chrono::Local::now().timestamp(); last_update_time = chrono::Local::now().timestamp();
} }
} }
crate::DiffResult::RsxChanged(changed) => { DiffResult::RsxChanged(changed) => {
log::info!("reloading rsx"); log::info!("reloading rsx");
for (old, new) in changed.into_iter() { for (old, new) in changed.into_iter() {
if let Some(hr) = old if let Some(hr) = old
@@ -128,6 +141,15 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
} }
} }
} }
#[cfg(not(feature = "hot_reload"))]
{
log::info!("reload required");
if chrono::Local::now().timestamp() > last_update_time {
let _ = reload_tx.send("reload".into());
last_update_time = chrono::Local::now().timestamp();
}
}
}
} }
} }
}) })
@@ -185,7 +207,6 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
let router = Router::new() let router = Router::new()
.route("/_dioxus/ws", get(ws_handler)) .route("/_dioxus/ws", get(ws_handler))
.route("/_dioxus/hot_reload", get(hot_reload_handler))
.fallback( .fallback(
get_service(file_service).handle_error(|error: std::io::Error| async move { get_service(file_service).handle_error(|error: std::io::Error| async move {
( (
@@ -194,14 +215,16 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
) )
}), }),
); );
#[cfg(feature = "hot_reload")]
let router = router.route("/_dioxus/hot_reload", get(hot_reload_handler));
let router = router.layer(Extension(ws_reload_state));
#[cfg(feature = "hot_reload")]
let router = router.layer(Extension(hot_reload_state));
axum::Server::bind(&format!("0.0.0.0:{}", port).parse().unwrap()) axum::Server::bind(&format!("0.0.0.0:{}", port).parse().unwrap())
.serve( .serve(router.into_make_service())
router
.layer(Extension(ws_reload_state))
.layer(Extension(hot_reload_state))
.into_make_service(),
)
.await?; .await?;
Ok(()) Ok(())
@@ -232,8 +255,11 @@ async fn ws_handler(
{ {
let _ = Serve::regen_dev_page(&state.watcher_config); let _ = Serve::regen_dev_page(&state.watcher_config);
} }
#[cfg(feature = "hot_reload")]
{
*state.last_file_rebuild.lock().unwrap() = HashMap::new(); *state.last_file_rebuild.lock().unwrap() = HashMap::new();
} }
}
// ignore the error // ignore the error
if socket if socket
.send(Message::Text(String::from("reload"))) .send(Message::Text(String::from("reload")))
@@ -250,6 +276,7 @@ async fn ws_handler(
}) })
} }
#[cfg(feature = "hot_reload")]
async fn hot_reload_handler( async fn hot_reload_handler(
ws: WebSocketUpgrade, ws: WebSocketUpgrade,
_: Option<TypedHeader<headers::UserAgent>>, _: Option<TypedHeader<headers::UserAgent>>,