mortise-core 1.1.0

Reads Laravel apps that use nwidart/laravel-modules. No interface.
Documentation
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! An app that is kept fresh: read on a worker thread, and read again when its files change.

use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use notify::{RecommendedWatcher, RecursiveMode};
use notify_debouncer_full::{DebounceEventResult, Debouncer, RecommendedCache, new_debouncer};

use crate::app::{AppSnapshot, ReadError, ReadOptions, read_app_cached};
use crate::modules::module::{Progress, ReadCache};

/// How long file changes are collected before the app is read again.
const QUIET: Duration = Duration::from_millis(300);

/// What a [`LiveApp`] holds at this moment.
#[derive(Debug, Clone)]
pub enum LiveState {
    /// The first read has not ended.
    Reading,
    /// The last read. It stays until a later read ends.
    Ready(Arc<AppSnapshot>),
    /// The last read failed.
    Failed(Arc<ReadError>),
}

enum Command {
    /// Read everything again now, also the files that did not change.
    Refresh,
    /// Files changed: read again, but only the files that changed.
    Changed,
    /// Watch the files of the app, or stop watching.
    Watch(bool),
    /// Read with other options from now on, and read again.
    Options(ReadOptions),
    Stop,
}

/// An app folder with a worker thread that reads it.
///
/// The interface never changes a snapshot: it asks for the current one with
/// [`LiveApp::state`] and is told through `on_change` that a newer one is there.
pub struct LiveApp {
    state: Arc<Mutex<LiveState>>,
    watching: Arc<AtomicBool>,
    commands: Sender<Command>,
    progress: Arc<Progress>,
}

impl LiveApp {
    /// Starts reading the app in `root`. `codes` are the codes its modules already
    /// have. `on_change` is called from the worker thread after every read.
    pub fn open(
        root: PathBuf,
        codes: BTreeMap<String, String>,
        options: ReadOptions,
        on_change: impl Fn() + Send + 'static,
    ) -> Self {
        let state = Arc::new(Mutex::new(LiveState::Reading));
        let watching = Arc::new(AtomicBool::new(false));
        let (commands, inbox) = channel();
        let cache = ReadCache::default();
        let progress = cache.progress();
        let worker = Worker {
            root,
            codes,
            options,
            cache,
            state: Arc::clone(&state),
            inbox,
            // The watcher reports into the same inbox.
            outbox: commands.clone(),
            on_change: Box::new(on_change),
            watcher: None,
            watched: Plan::default(),
            watching: Arc::clone(&watching),
        };
        std::thread::Builder::new()
            .name("mortise-app-reader".to_owned())
            .spawn(move || worker.run())
            .expect("a thread can be started");
        Self {
            state,
            watching,
            commands,
            progress,
        }
    }

    /// How far the read that is going on is: the PHP files read, and how many there are.
    pub fn progress(&self) -> (usize, usize) {
        self.progress.get()
    }

    /// True once the watcher that [`LiveApp::watch`] asked for is in place.
    pub fn is_watching(&self) -> bool {
        self.watching.load(Ordering::Relaxed)
    }

    /// The current state. Cheap: a snapshot is shared, not copied.
    pub fn state(&self) -> LiveState {
        self.state
            .lock()
            .expect("the state is never poisoned")
            .clone()
    }

    /// Reads the app again, now, also the files that did not change.
    pub fn refresh(&self) {
        let _ = self.commands.send(Command::Refresh);
    }

    /// Changes what the user set for the app, and reads it again.
    pub fn set_options(&self, options: ReadOptions) {
        let _ = self.commands.send(Command::Options(options));
    }

    /// Starts or stops reading the app again when its files change.
    pub fn watch(&self, on: bool) {
        let _ = self.commands.send(Command::Watch(on));
    }
}

impl Drop for LiveApp {
    fn drop(&mut self) {
        let _ = self.commands.send(Command::Stop);
    }
}

/// A folder to watch, and whether the folders inside it are watched too.
type Watched = (PathBuf, RecursiveMode);

/// What the watcher is set to watch.
#[derive(Debug, Default, PartialEq)]
struct Plan {
    /// The folders that are watched. Each one is there.
    folders: Vec<Watched>,
    /// The wanted folders that are not there yet, each with the folder above it that
    /// is watched in its place.
    missing: Vec<(PathBuf, PathBuf)>,
    /// The statuses file the config names.
    statuses: PathBuf,
}

struct Worker {
    root: PathBuf,
    codes: BTreeMap<String, String>,
    options: ReadOptions,
    cache: ReadCache,
    state: Arc<Mutex<LiveState>>,
    inbox: Receiver<Command>,
    outbox: Sender<Command>,
    on_change: Box<dyn Fn() + Send>,
    watcher: Option<Debouncer<RecommendedWatcher, RecommendedCache>>,
    /// What the watcher watches. Empty while it is off.
    watched: Plan,
    watching: Arc<AtomicBool>,
}

impl Worker {
    fn run(mut self) {
        self.read();
        while let Ok(command) = self.inbox.recv() {
            match command {
                Command::Refresh => {
                    self.cache.clear();
                    self.read();
                }
                Command::Changed => self.read(),
                Command::Options(options) => {
                    self.options = options;
                    self.read();
                }
                Command::Watch(true) => self.start_watching(),
                Command::Watch(false) => {
                    self.watcher = None;
                    self.watched = Plan::default();
                    self.watching.store(false, Ordering::Relaxed);
                }
                Command::Stop => break,
            }
        }
    }

    fn read(&mut self) {
        let state = match read_app_cached(&self.root, &self.codes, &self.options, &mut self.cache) {
            Ok(app) => {
                // A code is kept once given, also for a module that is gone for a while.
                self.codes.extend(app.codes());
                LiveState::Ready(Arc::new(app))
            }
            Err(error) => LiveState::Failed(Arc::new(error)),
        };
        *self.state.lock().expect("the state is never poisoned") = state;
        // The modules folder, the statuses file or the coverage report can move when a
        // config changes, and a wanted folder can appear.
        if self.watcher.is_some() && self.plan() != self.watched {
            self.start_watching();
        }
        (self.on_change)();
    }

    /// The statuses file the config names, or the default one before the first read.
    fn statuses_file(&self) -> PathBuf {
        match &*self.state.lock().expect("the state is never poisoned") {
            LiveState::Ready(app) => app.layout.statuses_file.clone(),
            _ => self.root.join("modules_statuses.json"),
        }
    }

    /// What should be watched: the app folder and its config folder for the few files
    /// Mortise reads there, the whole modules folder, the folders of the statuses file
    /// and of the coverage report, and git's folder for a new commit or another branch.
    fn wanted(&self) -> Vec<Watched> {
        let (modules_dir, report) = match &*self.state.lock().expect("the state is never poisoned")
        {
            LiveState::Ready(app) => (
                app.layout.modules_dir.clone(),
                app.coverage_report
                    .as_ref()
                    .map(|report| report.path.clone()),
            ),
            _ => (self.root.join("Modules"), None),
        };
        let mut wanted = vec![
            (self.root.clone(), RecursiveMode::NonRecursive),
            (self.root.join("config"), RecursiveMode::NonRecursive),
            (self.root.join(".git"), RecursiveMode::NonRecursive),
            // A tool that uses libgit2 changes only the refs and this log on a commit.
            // When `.git` is a file, as in a worktree, this folder is not there and
            // is not watched.
            (
                self.root.join(".git").join("logs"),
                RecursiveMode::NonRecursive,
            ),
            (modules_dir, RecursiveMode::Recursive),
        ];
        let statuses = self.statuses_file();
        if let Some(folder) = statuses.parent() {
            let covered = wanted.iter().any(|(watched, mode)| {
                watched == folder
                    || (*mode == RecursiveMode::Recursive && folder.starts_with(watched))
            });
            if !covered {
                wanted.push((folder.to_owned(), RecursiveMode::NonRecursive));
            }
        }
        if let Some(folder) = report.as_deref().and_then(Path::parent) {
            wanted.push((folder.to_owned(), RecursiveMode::NonRecursive));
        }
        wanted
    }

    /// What to watch now. A wanted folder that is not there is watched through the
    /// nearest folder above it, so that its creation is seen.
    fn plan(&self) -> Plan {
        let mut plan = Plan {
            statuses: self.statuses_file(),
            ..Plan::default()
        };
        for (folder, mode) in self.wanted() {
            let watched = if folder.is_dir() {
                (folder, mode)
            } else if folder.exists() {
                // Not a folder, such as `.git` in a worktree.
                continue;
            } else {
                // When the nearest path above is a file, the folder cannot appear.
                let Some(above) = folder
                    .ancestors()
                    .find(|path| path.exists())
                    .filter(|path| path.is_dir())
                else {
                    continue;
                };
                plan.missing.push((folder.clone(), above.to_owned()));
                (above.to_owned(), RecursiveMode::NonRecursive)
            };
            // A folder wanted twice, such as a modules folder set to `config`, is
            // watched once, with its subfolders when either wants them.
            match plan
                .folders
                .iter_mut()
                .find(|(folder, _)| *folder == watched.0)
            {
                Some((_, mode)) if watched.1 == RecursiveMode::Recursive => *mode = watched.1,
                Some(_) => {}
                None => plan.folders.push(watched),
            }
        }
        plan
    }

    fn start_watching(&mut self) {
        self.watcher = None;
        let mut plan = self.plan();

        let outbox = self.outbox.clone();
        let root = self.root.clone();
        // The statuses file counts wherever it is, also in `storage`. On macOS the
        // watcher reports paths without symbolic links, so that form counts too.
        let real_statuses = plan
            .statuses
            .parent()
            .and_then(real)
            .zip(plan.statuses.file_name())
            .map(|(folder, name)| folder.join(name));
        let statuses: Vec<PathBuf> = std::iter::once(plan.statuses.clone())
            .chain(real_statuses)
            .collect();
        // A missing folder counts when it, or a folder on the way to it, appears.
        let missing: Vec<(PathBuf, PathBuf)> = plan
            .missing
            .iter()
            .cloned()
            .chain(
                plan.missing
                    .iter()
                    .filter_map(|(folder, above)| Some((real(folder)?, real(above)?))),
            )
            .collect();
        let appears = move |path: &Path| {
            missing
                .iter()
                .any(|(folder, above)| folder.starts_with(path) && path != above)
        };
        let handler = move |result: DebounceEventResult| {
            let relevant = result.is_ok_and(|events| {
                events.iter().any(|event| {
                    event.paths.iter().any(|path| {
                        statuses.contains(path) || is_relevant(&root, path) || appears(path)
                    })
                })
            });
            if relevant {
                let _ = outbox.send(Command::Changed);
            }
        };
        let Ok(mut watcher) = new_debouncer(QUIET, None, handler) else {
            return;
        };
        // Only the folders that are watched are kept, so that a read after a failure
        // tries again.
        plan.folders
            .retain(|(folder, mode)| watcher.watch(folder, *mode).is_ok());
        self.watched = plan;
        self.watcher = Some(watcher);
        self.watching.store(true, Ordering::Relaxed);
    }
}

/// A path as the watcher reports it: without symbolic links, which macOS resolves.
/// The part that is not there yet is kept as it is.
fn real(path: &Path) -> Option<PathBuf> {
    let there = path.ancestors().find(|path| path.exists())?;
    let rest = path.strip_prefix(there).ok()?;
    Some(std::fs::canonicalize(there).ok()?.join(rest))
}

/// False for what Mortise never reads and what changes in bulk: installed packages,
/// logs and caches, and git's own files except the few that change with a commit or
/// a checkout. Only the part of the path inside the app counts.
fn is_relevant(root: &Path, path: &Path) -> bool {
    let inside = path.strip_prefix(root).unwrap_or(path);
    let mut parts = inside.components().filter_map(|part| match part {
        Component::Normal(name) => name.to_str(),
        _ => None,
    });
    if inside.starts_with(".git") {
        // The index is rewritten by every `git status` of every editor: not that.
        let git: Vec<&str> = parts.skip(1).collect();
        return matches!(
            git.as_slice(),
            ["HEAD" | "COMMIT_EDITMSG" | "ORIG_HEAD" | "packed-refs"] | ["logs", "HEAD"]
        );
    }
    // A coverage report is a file Mortise reads, wherever it is written.
    if inside
        .extension()
        .is_some_and(|extension| extension == "xml")
    {
        return true;
    }
    !parts.any(|name| matches!(name, "vendor" | "node_modules" | ".git" | "storage"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn installed_packages_logs_and_most_git_files_are_not_relevant() {
        let root = Path::new("/home/storage/shop-api");
        let relevant = |path: &str| is_relevant(root, &root.join(path));
        assert!(relevant("modules_statuses.json"));
        assert!(relevant("Modules/Blog/app/Models/Post.php"));
        assert!(relevant("build/coverage/clover.xml"));
        assert!(relevant("storage/coverage/clover.xml"));
        assert!(!relevant("vendor/composer/installed.json"));
        assert!(!relevant("Modules/Blog/node_modules/x/index.js"));
        assert!(!relevant("storage/logs/laravel.log"));

        assert!(relevant(".git/HEAD"));
        assert!(relevant(".git/COMMIT_EDITMSG"));
        assert!(relevant(".git/logs/HEAD"));
        assert!(!relevant(".git/logs/refs/heads/main"));
        assert!(!relevant(".git/index"));
        assert!(!relevant(".git/index.lock"));
        assert!(!relevant(".git/objects/ab/cdef"));
    }
}