1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
use clap::Parser;
use notify::{self, RecursiveMode, Watcher as NotifyWatcher};
use std::{
    env, fs,
    path::{Path, PathBuf},
    sync::Arc,
};
use tokio::sync::mpsc;
use tokio::sync::Mutex;
use tokio::time;

use crate::commands::build;

use super::build::clients::LoamEnv;

enum Message {
    FileChanged,
}

#[derive(Parser, Debug, Clone)]
#[group(skip)]
pub struct Cmd {
    #[command(flatten)]
    pub build_cmd: build::Cmd,
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    Watcher(#[from] notify::Error),
    #[error(transparent)]
    Build(#[from] build::Error),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

fn canonicalize_path(path: &Path) -> PathBuf {
    if path.as_os_str().is_empty() {
        env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
    } else if path.components().count() == 1 {
        // Path is a single component, assuming it's a filename
        env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join(path)
    } else {
        fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
    }
}

#[derive(Clone)]
struct Watcher {
    root_env: Arc<PathBuf>,
    packages: Arc<Vec<PathBuf>>,
}

impl Watcher {
    pub fn new(root_env: &Path, packages: &[PathBuf]) -> Self {
        Self {
            root_env: Arc::new(canonicalize_path(root_env)),
            packages: Arc::new(
                packages
                    .iter()
                    .map(|p: &PathBuf| canonicalize_path(p))
                    .collect(),
            ),
        }
    }

    pub fn is_watched(&self, path: &Path) -> bool {
        let path = canonicalize_path(path);
        self.packages.iter().any(|p| path.starts_with(p))
    }

    pub fn is_env_toml(&self, path: &Path) -> bool {
        canonicalize_path(path) == *self.root_env
    }

    pub fn handle_event(&self, event: &notify::Event, tx: &mpsc::Sender<Message>) {
        if matches!(
            event.kind,
            notify::EventKind::Create(_)
                | notify::EventKind::Modify(_)
                | notify::EventKind::Remove(_)
        ) {
            if let Some(path) = event.paths.first() {
                if is_temporary_file(path) {
                    return;
                }
                if self.is_watched(path) || self.is_env_toml(path) {
                    eprintln!("File changed: {path:?}");
                    if let Err(e) = tx.blocking_send(Message::FileChanged) {
                        eprintln!("Error sending through channel: {e}");
                    }
                }
            }
        }
    }
}

fn is_temporary_file(path: &Path) -> bool {
    const IGNORED_EXTENSIONS: &[&str] = &["tmp", "swp", "swo"];
    let file_name = path
        .file_name()
        .expect("Path should have a file name")
        .to_str()
        .expect("File name should be valid UTF-8");

    // Vim and vscode temporary files
    if path
        .extension()
        .and_then(|ext| ext.to_str())
        .map_or(false, |ext| {
            IGNORED_EXTENSIONS
                .iter()
                .any(|&ignored| ext.eq_ignore_ascii_case(ignored))
        })
    {
        return true;
    }

    // Vim temporary files
    if file_name.ends_with('~') {
        return true;
    }

    // Emacs temporary files
    if file_name.starts_with('#') && file_name.ends_with('#') {
        return true;
    }

    // Add more patterns for other editors as needed

    false
}

impl Cmd {
    pub async fn run(&mut self) -> Result<(), Error> {
        let (tx, mut rx) = mpsc::channel::<Message>(100);
        let rebuild_state = Arc::new(Mutex::new(false));
        let workspace_root: &Path = self
            .build_cmd
            .manifest_path
            .parent()
            .unwrap_or_else(|| Path::new("."));
        let env_toml_path = workspace_root.join("environments.toml");

        let packages = self
            .build_cmd
            .list_packages()?
            .into_iter()
            .map(|package| PathBuf::from(package.manifest_path.parent().unwrap().as_str()))
            .collect::<Vec<_>>();

        let watcher = Watcher::new(&env_toml_path, &packages);

        for package_path in watcher.packages.iter() {
            eprintln!("Watching {}", package_path.display());
        }

        let mut notify_watcher =
            notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
                if let Ok(event) = res {
                    watcher.handle_event(&event, &tx);
                }
            })
            .unwrap();

        notify_watcher.watch(
            &canonicalize_path(&env_toml_path),
            RecursiveMode::NonRecursive,
        )?;
        for package_path in packages {
            notify_watcher.watch(&canonicalize_path(&package_path), RecursiveMode::Recursive)?;
        }

        let build_command = self.cloned_build_command();
        let cmd = build_command.lock().await;
        if let Err(e) = cmd.run().await {
            eprintln!("Build error: {e}");
        }
        eprintln!("Watching for changes. Press Ctrl+C to stop.");

        let rebuild_state_clone = rebuild_state.clone();
        loop {
            tokio::select! {
                _ = rx.recv() => {
                    let mut state = rebuild_state_clone.lock().await;
                    let build_command_inner = build_command.clone();
                    if !*state {
                        *state= true;
                        tokio::spawn(Self::debounced_rebuild(build_command_inner, Arc::clone(&rebuild_state_clone)));
                    }
                }
                _ = tokio::signal::ctrl_c() => {
                    eprintln!("Stopping dev mode.");
                    break;
                }
            }
        }
        Ok(())
    }

    async fn debounced_rebuild(
        build_command: Arc<Mutex<build::Cmd>>,
        rebuild_state: Arc<Mutex<bool>>,
    ) {
        // Debounce to avoid multiple rapid rebuilds
        time::sleep(std::time::Duration::from_secs(1)).await;

        eprintln!("Changes detected. Rebuilding...");
        let cmd = build_command.lock().await;
        if let Err(e) = cmd.run().await {
            eprintln!("Build error: {e}");
        }
        eprintln!("Watching for changes. Press Ctrl+C to stop.");

        let mut state = rebuild_state.lock().await;
        *state = false;
    }

    fn cloned_build_command(&mut self) -> Arc<Mutex<build::Cmd>> {
        self.build_cmd
            .build_clients_args
            .env
            .get_or_insert(LoamEnv::Development);
        Arc::new(Mutex::new(self.build_cmd.clone()))
    }
}