beet_cli/commands/
run_watch.rs

1use crate::prelude::*;
2use anyhow::Result;
3use beet::prelude::*;
4use clap::Parser;
5use sweet::prelude::Server;
6
7/// Watch the beet project and rebuild on changes
8#[derive(Debug, Parser)]
9pub struct RunWatch {
10	#[command(flatten)]
11	build_args: BuildArgs,
12	#[command(flatten)]
13	build_template_map: BuildTemplateMap,
14	#[command(flatten)]
15	build_cmd: CargoBuildCmd,
16}
17
18impl RunWatch {
19	pub async fn run(self) -> Result<()> {
20		if self.build_args.as_static {
21			self.watch_and_serve().await
22		} else {
23			self.watch().await
24		}
25	}
26
27	/// Run in static mode, building the site and serving it via cli
28	async fn watch_and_serve(self) -> Result<()> {
29		let watch_args = self.build_args.clone();
30		let watch_handle = tokio::spawn(async move {
31			self.watch().await.map_err(|e| {
32				// watcher errors are fatal, print the error and exit
33				eprintln!("{:#?}", e);
34				std::process::exit(1);
35			})
36		});
37		// run a simple file server with live-reload on change
38		Server {
39			dir: watch_args.html_dir,
40			no_clear: true,
41			..Default::default()
42		}
43		.run()
44		.await?;
45		watch_handle.abort();
46		Ok(())
47	}
48
49	/// Create a template watcher that will
50	/// 1. rebuild templates on any file change
51	/// 2. recompile on code changes
52	/// 3. run the process
53	async fn watch(self) -> Result<()> {
54		let Self {
55			build_args: watch_args,
56			build_template_map,
57			build_cmd,
58		} = self;
59
60
61		let templates_root_dir = build_template_map.templates_root_dir.clone();
62
63		let recompile = RunBuild {
64			build_cmd: build_cmd.clone(),
65			build_args: watch_args.clone(),
66			build_template_map: build_template_map.clone(),
67			server: true,
68		}
69		.into_group()?;
70
71		let reload = BuildStepGroup::default()
72			.with(build_template_map.clone())
73			.with(ExportStatic::new(&watch_args, &build_cmd.exe_path()));
74
75		TemplateWatcher::new(
76			templates_root_dir,
77			|| reload.run(),
78			|| recompile.run(),
79		)?
80		.run_once_and_watch()
81		.await
82	}
83}