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
+100 -71

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::*;
+93 -66
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,55 +87,66 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
if src.is_empty() { if src.is_empty() {
continue; continue;
} }
if let Ok(syntax) = syn::parse_file(&src) { #[cfg(feature = "hot_reload")]
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 Ok(syntax) = syn::parse_file(&src) {
if let Ok(old) = syn::parse_file(&old_str) { let mut last_file_rebuild = last_file_rebuild.lock().unwrap();
match find_rsx(&syntax, &old) { if let Some(old_str) = last_file_rebuild.get(path.to_str().unwrap()) {
crate::DiffResult::CodeChanged => { if let Ok(old) = syn::parse_file(&old_str) {
log::info!("reload required"); match find_rsx(&syntax, &old) {
if chrono::Local::now().timestamp() > last_update_time { DiffResult::CodeChanged => {
let _ = reload_tx.send("reload".into()); log::info!("reload required");
last_update_time = chrono::Local::now().timestamp(); if chrono::Local::now().timestamp() > last_update_time {
let _ = reload_tx.send("reload".into());
last_update_time = chrono::Local::now().timestamp();
}
} }
} DiffResult::RsxChanged(changed) => {
crate::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 .to_token_stream()
.to_token_stream() .into_iter()
.into_iter() .map(|tree| {
.map(|tree| { let location = tree.span();
let location = tree.span(); let start = location.start();
let start = location.start(); CodeLocation {
CodeLocation { file: path
file: path .strip_prefix(&crate_dir)
.strip_prefix(&crate_dir) .unwrap()
.unwrap() .display()
.display() .to_string(),
.to_string(), line: start.line as u32,
line: start.line as u32, column: start.column as u32 + 1,
column: start.column as u32 + 1, }
} })
}) .min_by(|cl1, cl2| {
.min_by(|cl1, cl2| { cl1.line
cl1.line .cmp(&cl2.line)
.cmp(&cl2.line) .then(cl1.column.cmp(&cl2.column))
.then(cl1.column.cmp(&cl2.column)) })
}) {
{ let rsx = new.to_string();
let rsx = new.to_string(); let _ = hot_reload_tx.send(SetRsxMessage {
let _ = hot_reload_tx.send(SetRsxMessage { location: hr,
location: hr, new_text: rsx,
new_text: rsx, });
}); }
} }
} }
} }
} }
} else {
last_file_rebuild.insert(path.to_str().unwrap().to_string(), src);
} }
} else { }
last_file_rebuild.insert(path.to_str().unwrap().to_string(), src); }
#[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,7 +255,10 @@ async fn ws_handler(
{ {
let _ = Serve::regen_dev_page(&state.watcher_config); let _ = Serve::regen_dev_page(&state.watcher_config);
} }
*state.last_file_rebuild.lock().unwrap() = HashMap::new(); #[cfg(feature = "hot_reload")]
{
*state.last_file_rebuild.lock().unwrap() = HashMap::new();
}
} }
// ignore the error // ignore the error
if socket if socket
@@ -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>>,