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:?}");
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.to_string())?
142 .is_none()
143 {
144 return Ok(());
145 }
146 let packages = self
147 .build_cmd
148 .list_packages(metadata)?
149 .into_iter()
150 .map(|package| {
151 package
152 .manifest_path
153 .parent()
154 .unwrap()
155 .to_path_buf()
156 .into_std_path_buf()
157 })
158 .collect::<Vec<_>>();
159
160 let watcher = Watcher::new(env_toml_dir, &packages);
161
162 for package_path in watcher.packages.iter() {
163 printer.infoln(format!("Watching {}", package_path.display()));
164 }
165
166 let mut notify_watcher =
167 notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
168 if let Ok(event) = res {
169 watcher.handle_event(&event, &tx);
170 }
171 })
172 .unwrap();
173
174 notify_watcher.watch(
175 &canonicalize_path(env_toml_dir),
176 RecursiveMode::NonRecursive,
177 )?;
178 for package_path in packages {
179 notify_watcher.watch(&canonicalize_path(&package_path), RecursiveMode::Recursive)?;
180 }
181
182 let build_command = self.cloned_build_command(global_args);
183 if let Err(e) = build_command.0.run(&build_command.1).await {
184 printer.errorln(format!("Build error: {e}"));
185 }
186 printer.infoln("Watching for changes. Press Ctrl+C to stop.");
187
188 let rebuild_state_clone = rebuild_state.clone();
189 let printer_clone = printer.clone();
190 loop {
191 tokio::select! {
192 _ = rx.recv() => {
193 let mut state = rebuild_state_clone.lock().await;
194 let build_command_inner = build_command.clone();
195 if !*state {
196 *state = true;
197 tokio::spawn(Self::debounced_rebuild(build_command_inner, Arc::clone(&rebuild_state_clone), printer_clone.clone()));
198 }
199 }
200 _ = tokio::signal::ctrl_c() => {
201 printer.infoln("Stopping dev mode.");
202 break;
203 }
204 }
205 }
206 Ok(())
207 }
208
209 async fn debounced_rebuild(
210 build_command: Arc<(build::Command, stellar_cli::commands::global::Args)>,
211 rebuild_state: Arc<Mutex<bool>>,
212 printer: Print,
213 ) {
214 time::sleep(std::time::Duration::from_secs(1)).await;
216
217 printer.infoln("Changes detected. Rebuilding...");
218 if let Err(e) = build_command.0.run(&build_command.1).await {
219 printer.errorln(format!("Build error: {e}"));
220 }
221 printer.infoln("Watching for changes. Press Ctrl+C to stop.");
222
223 let mut state = rebuild_state.lock().await;
224 *state = false;
225 }
226
227 fn cloned_build_command(
228 &mut self,
229 global_args: &stellar_cli::commands::global::Args,
230 ) -> Arc<(build::Command, stellar_cli::commands::global::Args)> {
231 self.build_cmd
232 .build_clients_args
233 .env
234 .get_or_insert(ScaffoldEnv::Development);
235 Arc::new((self.build_cmd.clone(), global_args.clone()))
236 }
237}