1use std::path::{Path, PathBuf};
20
21use crate::core_group::depgraph::DepGraph;
22use crate::server_group::event_watch::{ChangeBatch, EventWatcher};
23use crate::server_group::hmr::{HmrBroadcaster, HmrMessage};
24use crate::server_group::watch::{classify_change, ChangeKind};
25
26#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct BatchOutcome {
31 pub frame: Option<HmrMessage>,
35 pub invalidated_outputs: Vec<PathBuf>,
38}
39
40#[must_use]
67pub fn process_batch(
68 batch: &ChangeBatch,
69 graph: &DepGraph,
70 output_dir: &Path,
71) -> BatchOutcome {
72 if batch.is_empty() {
73 return BatchOutcome {
74 frame: None,
75 invalidated_outputs: Vec::new(),
76 };
77 }
78
79 let mut css_paths: Vec<String> = Vec::new();
80 let mut content_or_template = false;
81 let mut other = false;
82
83 for path in &batch.paths {
84 match classify_change(path) {
85 ChangeKind::Css => {
86 css_paths.push(path.to_string_lossy().into_owned());
87 }
88 ChangeKind::Content | ChangeKind::Template => {
89 content_or_template = true;
90 }
91 ChangeKind::Other => {
92 other = true;
93 }
94 }
95 }
96
97 let outputs = graph.invalidated_outputs(&batch.paths);
98 let url_paths: Vec<String> = outputs
99 .iter()
100 .map(|p| output_to_url(p, output_dir))
101 .collect();
102
103 let frame = match (!css_paths.is_empty(), content_or_template, other) {
104 (true, false, false) => Some(HmrMessage::css(css_paths)),
106 (false, true, false) => {
110 if url_paths.is_empty() {
111 Some(HmrMessage::reload())
112 } else {
113 Some(HmrMessage::html(url_paths))
114 }
115 }
116 _ => Some(HmrMessage::reload()),
118 };
119
120 BatchOutcome {
121 frame,
122 invalidated_outputs: outputs,
123 }
124}
125
126#[must_use]
142pub fn output_to_url(output: &Path, output_dir: &Path) -> String {
143 let rel = output.strip_prefix(output_dir).unwrap_or(output);
144 let mut s = rel.to_string_lossy().replace('\\', "/");
145 for trailing in ["index.html", "index.htm"] {
147 if let Some(stripped) = s.strip_suffix(trailing) {
148 s = stripped.to_string();
149 break;
150 }
151 }
152 if !s.starts_with('/') {
153 s.insert(0, '/');
154 }
155 s
156}
157
158pub fn run_dev_loop<F: FnMut(&[PathBuf])>(
175 watcher: &EventWatcher,
176 graph: &DepGraph,
177 broadcaster: &HmrBroadcaster,
178 output_dir: &Path,
179 mut rebuild: F,
180) -> usize {
181 let mut processed = 0usize;
182 while let Some(batch) = watcher.recv() {
183 let outcome = process_batch(&batch, graph, output_dir);
184 rebuild(&outcome.invalidated_outputs);
185 if let Some(frame) = outcome.frame {
186 let _ = broadcaster.broadcast(&frame);
187 }
188 processed += 1;
189 }
190 processed
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 fn pb(s: &str) -> PathBuf {
198 PathBuf::from(s)
199 }
200
201 #[test]
202 fn empty_batch_yields_no_frame() {
203 let batch = ChangeBatch { paths: vec![] };
204 let graph = DepGraph::new();
205 let out = process_batch(&batch, &graph, Path::new("build"));
206 assert!(out.frame.is_none());
207 assert!(out.invalidated_outputs.is_empty());
208 }
209
210 #[test]
211 fn pure_css_batch_yields_hmr_css_frame() {
212 let batch = ChangeBatch {
213 paths: vec![pb("assets/style.css")],
214 };
215 let graph = DepGraph::new();
216 let out = process_batch(&batch, &graph, Path::new("build"));
217 let frame = out.frame.expect("frame");
218 let json = frame.to_json();
219 assert!(json.contains("hmr-css"));
220 assert!(json.contains("assets/style.css"));
221 }
222
223 #[test]
224 fn pure_content_batch_without_graph_falls_back_to_reload() {
225 let batch = ChangeBatch {
227 paths: vec![pb("content/blog/foo.md")],
228 };
229 let graph = DepGraph::new();
230 let out = process_batch(&batch, &graph, Path::new("build"));
231 let json = out.frame.unwrap().to_json();
232 assert!(json.contains("\"type\":\"reload\""));
233 }
234
235 #[test]
236 fn mixed_css_and_content_batch_yields_reload() {
237 let batch = ChangeBatch {
238 paths: vec![pb("assets/style.css"), pb("content/foo.md")],
239 };
240 let graph = DepGraph::new();
241 let out = process_batch(&batch, &graph, Path::new("build"));
242 assert!(out.frame.unwrap().to_json().contains("reload"));
243 }
244
245 #[test]
246 fn other_only_batch_yields_reload() {
247 let batch = ChangeBatch {
248 paths: vec![pb("data/config.json")],
249 };
250 let graph = DepGraph::new();
251 let out = process_batch(&batch, &graph, Path::new("build"));
252 assert!(out.frame.unwrap().to_json().contains("reload"));
253 }
254
255 #[test]
256 fn output_to_url_strips_index_html_and_prefix() {
257 let out = pb("build/blog/foo/index.html");
258 let url = output_to_url(&out, Path::new("build"));
259 assert_eq!(url, "/blog/foo/");
260 }
261
262 #[test]
263 fn output_to_url_keeps_non_index_files() {
264 let out = pb("build/feed.xml");
265 let url = output_to_url(&out, Path::new("build"));
266 assert_eq!(url, "/feed.xml");
267 }
268
269 #[test]
270 fn output_to_url_handles_root_index() {
271 let out = pb("build/index.html");
272 let url = output_to_url(&out, Path::new("build"));
273 assert_eq!(url, "/");
274 }
275
276 #[test]
277 fn output_to_url_normalises_backslashes() {
278 let out = pb("build\\blog\\index.html");
279 let url = output_to_url(&out, Path::new("build"));
282 assert!(url.starts_with('/'));
284 assert!(!url.contains('\\'));
285 }
286
287 #[test]
288 fn output_to_url_strips_index_htm_suffix() {
289 let out = pb("build/blog/index.htm");
295 let url = output_to_url(&out, Path::new("build"));
296 assert_eq!(url, "/blog/");
297 }
298
299 #[test]
300 fn output_to_url_keeps_leading_slash_when_prefix_strip_fails() {
301 let out = pb("/abs/feed.xml");
304 let url = output_to_url(&out, Path::new("build"));
305 assert_eq!(url, "/abs/feed.xml");
306 }
307
308 #[test]
309 fn run_dev_loop_processes_live_batches_until_watcher_closes() {
310 use std::sync::atomic::{AtomicUsize, Ordering};
311 use std::time::{Duration, Instant};
312
313 let dir = tempfile::tempdir().expect("tempdir");
314 let watcher =
315 EventWatcher::with_debounce(dir.path(), Duration::from_millis(30))
316 .expect("watcher");
317 let graph = DepGraph::new();
318 let broadcaster = HmrBroadcaster::new();
319
320 let frames = std::sync::Arc::new(AtomicUsize::new(0));
321 let frames_sink = std::sync::Arc::clone(&frames);
322 broadcaster.subscribe(Box::new(move |_| {
323 let _ = frames_sink.fetch_add(1, Ordering::SeqCst);
324 Ok(())
325 }));
326
327 let deadline = Instant::now() + Duration::from_secs(3);
331 while watcher
332 .recv_timeout(Duration::from_millis(0))
333 .batch()
334 .is_none()
335 {
336 if Instant::now() >= deadline {
337 break;
338 }
339 std::fs::write(dir.path().join("page.md"), b"x").expect("write");
340 std::thread::sleep(Duration::from_millis(50));
341 }
342
343 std::fs::write(dir.path().join("late.md"), b"y").expect("write");
347 std::thread::sleep(Duration::from_millis(80));
348 watcher.close_backend_for_test();
349
350 let rebuilds = AtomicUsize::new(0);
351 let processed = run_dev_loop(
352 &watcher,
353 &graph,
354 &broadcaster,
355 Path::new("build"),
356 |_outputs| {
357 let _ = rebuilds.fetch_add(1, Ordering::SeqCst);
358 },
359 );
360
361 assert_eq!(processed, rebuilds.load(Ordering::SeqCst));
364 assert_eq!(processed, frames.load(Ordering::SeqCst));
365 }
366
367 #[test]
368 fn pure_content_with_graph_edges_yields_hmr_html() {
369 let mut graph = DepGraph::new();
373 graph.add_output(
375 Path::new("content/blog/foo.md"),
376 Path::new("build/blog/foo/index.html"),
377 );
378 let batch = ChangeBatch {
379 paths: vec![pb("content/blog/foo.md")],
380 };
381 let out = process_batch(&batch, &graph, Path::new("build"));
382 let json = out.frame.unwrap().to_json();
383 assert!(json.contains("hmr-html"), "expected hmr-html, got: {json}");
384 assert!(
385 json.contains("/blog/foo/"),
386 "expected URL list to carry the page, got: {json}"
387 );
388 }
389}