stellar_scaffold_cli/commands/watch/
mod.rs1use clap::Parser;
2use ignore::gitignore::{Gitignore, GitignoreBuilder};
3use notify::{self, RecursiveMode, Watcher as _};
4use std::{
5 env, fs,
6 path::{Path, PathBuf},
7 sync::Arc,
8};
9use stellar_cli::print::Print;
10use tokio::sync::mpsc;
11use tokio::sync::Mutex;
12use tokio::time;
13
14use crate::commands::build::{self, env_toml};
15
16use super::build::clients::ScaffoldEnv;
17use super::build::env_toml::ENV_FILE;
18
19pub enum Message {
20 FileChanged,
21}
22
23#[derive(Parser, Debug, Clone)]
24#[group(skip)]
25pub struct Cmd {
26 #[command(flatten)]
27 pub build_cmd: build::Command,
28}
29
30#[derive(thiserror::Error, Debug)]
31pub enum Error {
32 #[error(transparent)]
33 Watcher(#[from] notify::Error),
34 #[error(transparent)]
35 Build(#[from] build::Error),
36 #[error("IO error: {0}")]
37 Io(#[from] std::io::Error),
38 #[error(transparent)]
39 Env(#[from] env_toml::Error),
40 #[error("Failed to start docker container")]
41 DockerStart,
42 #[error(transparent)]
43 Manifest(#[from] cargo_metadata::Error),
44}
45
46fn canonicalize_path(path: &Path) -> PathBuf {
47 if path.as_os_str().is_empty() {
48 env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
49 } else if path.components().count() == 1 {
50 env::current_dir()
52 .unwrap_or_else(|_| PathBuf::from("."))
53 .join(path)
54 } else {
55 fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
56 }
57}
58
59#[derive(Clone)]
60pub struct Watcher {
61 env_toml_dir: Arc<PathBuf>,
62 packages: Arc<Vec<PathBuf>>,
63 ignores: Arc<Gitignore>,
64}
65
66impl Watcher {
67 pub fn new(env_toml_dir: &Path, packages: &[PathBuf]) -> Self {
68 let env_toml_dir: Arc<PathBuf> = Arc::new(canonicalize_path(env_toml_dir));
69 let packages: Arc<Vec<PathBuf>> =
70 Arc::new(packages.iter().map(|p| canonicalize_path(p)).collect());
71
72 let mut builder = GitignoreBuilder::new(&*env_toml_dir);
73 for package in packages.iter() {
74 builder.add(package);
75 }
76
77 let ignores = Arc::new(builder.build().expect("Failed to build GitIgnore"));
78
79 Self {
80 env_toml_dir,
81 packages,
82 ignores,
83 }
84 }
85
86 pub fn is_watched(&self, path: &Path) -> bool {
87 let path = canonicalize_path(path);
88 !self.ignores.matched(&path, path.is_dir()).is_ignore()
89 }
90
91 pub fn is_env_toml(&self, path: &Path) -> bool {
92 path == self.env_toml_dir.join(ENV_FILE)
93 }
94
95 pub fn handle_event(&self, event: ¬ify::Event, tx: &mpsc::Sender<Message>) {
96 if matches!(
97 event.kind,
98 notify::EventKind::Create(notify::event::CreateKind::File)
99 | notify::EventKind::Modify(notify::event::ModifyKind::Data(_))
100 | notify::EventKind::Remove(notify::event::RemoveKind::File)
101 ) {
102 let watched_file = event.paths.iter().find(|path| {
103 let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
104 return false;
105 };
106 if ext.eq_ignore_ascii_case("toml") {
107 let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
108 return false;
109 };
110 if stem.eq_ignore_ascii_case("environments")
111 || stem.eq_ignore_ascii_case("cargo")
112 {
113 return self.is_watched(path);
114 }
115 } else if ext.eq_ignore_ascii_case("rs") {
116 return self.is_watched(path);
117 }
118 false
119 });
120
121 if let Some(path) = watched_file {
122 eprintln!("File changed: {}", path.display());
123 if let Err(e) = tx.blocking_send(Message::FileChanged) {
124 eprintln!("Error sending through channel: {e:?}");
125 }
126 }
127 }
128 }
129}
130
131impl Cmd {
132 pub async fn run(
133 &mut self,
134 global_args: &stellar_cli::commands::global::Args,
135 ) -> Result<(), Error> {
136 let printer = Print::new(global_args.quiet);
137 let (tx, mut rx) = mpsc::channel::<Message>(100);
138 let rebuild_state = Arc::new(Mutex::new(false));
139 let metadata = &self.build_cmd.metadata()?;
140 let env_toml_dir = metadata.workspace_root.as_std_path();
141 if env_toml::Environment::get(env_toml_dir, &ScaffoldEnv::Development)?.is_none() {
142 return Ok(());
143 }
144 let packages = self
145 .build_cmd
146 .list_packages(metadata)?
147 .into_iter()
148 .map(|package| {
149 package
150 .manifest_path
151 .parent()
152 .unwrap()
153 .to_path_buf()
154 .into_std_path_buf()
155 })
156 .collect::<Vec<_>>();
157
158 let watcher = Watcher::new(env_toml_dir, &packages);
159
160 for package_path in watcher.packages.iter() {
161 printer.infoln(format!("Watching {}", package_path.display()));
162 }
163
164 let mut notify_watcher =
165 notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
166 if let Ok(event) = res {
167 watcher.handle_event(&event, &tx);
168 }
169 })
170 .unwrap();
171
172 notify_watcher.watch(
173 &canonicalize_path(env_toml_dir),
174 RecursiveMode::NonRecursive,
175 )?;
176 for package_path in packages {
177 notify_watcher.watch(&canonicalize_path(&package_path), RecursiveMode::Recursive)?;
178 }
179
180 let build_command = self.cloned_build_command(global_args);
181 if let Err(e) = build_command.0.run(&build_command.1).await {
182 printer.errorln(format!("Build error: {e}"));
183 }
184 printer.infoln("Watching for changes. Press Ctrl+C to stop.");
185
186 let rebuild_state_clone = rebuild_state.clone();
187 let printer_clone = printer.clone();
188 loop {
189 tokio::select! {
190 _ = rx.recv() => {
191 let mut state = rebuild_state_clone.lock().await;
192 let build_command_inner = build_command.clone();
193 if !*state {
194 *state = true;
195 tokio::spawn(Self::debounced_rebuild(build_command_inner, Arc::clone(&rebuild_state_clone), printer_clone.clone()));
196 }
197 }
198 _ = tokio::signal::ctrl_c() => {
199 printer.infoln("Stopping dev mode.");
200 break;
201 }
202 }
203 }
204 Ok(())
205 }
206
207 async fn debounced_rebuild(
208 build_command: Arc<(build::Command, stellar_cli::commands::global::Args)>,
209 rebuild_state: Arc<Mutex<bool>>,
210 printer: Print,
211 ) {
212 time::sleep(std::time::Duration::from_secs(1)).await;
214
215 printer.infoln("Changes detected. Rebuilding...");
216 if let Err(e) = build_command.0.run(&build_command.1).await {
217 printer.errorln(format!("Build error: {e}"));
218 }
219 printer.infoln("Watching for changes. Press Ctrl+C to stop.");
220
221 let mut state = rebuild_state.lock().await;
222 *state = false;
223 }
224
225 fn cloned_build_command(
226 &mut self,
227 global_args: &stellar_cli::commands::global::Args,
228 ) -> Arc<(build::Command, stellar_cli::commands::global::Args)> {
229 self.build_cmd
230 .build_clients_args
231 .env
232 .get_or_insert(ScaffoldEnv::Development);
233 Arc::new((self.build_cmd.clone(), global_args.clone()))
234 }
235}