Skip to main content

mortise_core/modules/
module.rs

1//! The modules of an app: found on disk the way the package finds them.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::atomic::{AtomicUsize, Ordering};
7use std::time::SystemTime;
8
9use ignore::WalkBuilder;
10use rayon::prelude::*;
11use serde::{Deserialize, Serialize};
12
13use crate::modules::clover::Coverage;
14use crate::modules::git::Churn;
15use crate::modules::kind::{COMMANDS, Kinds, TESTS};
16use crate::modules::layout::Layout;
17use crate::php::{Analysis, Declared, analyze, count_tests};
18use crate::surface::AcceptedSurface;
19
20/// Whether a module is turned on.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22pub enum ModuleState {
23    /// The statuses file has the JSON value `true` for the module.
24    On,
25    /// Anything else, including no entry: the package treats a missing entry as off.
26    Off,
27    /// The app does not use the file activator, so the state is not in a file.
28    Unknown,
29}
30
31/// What reading a module's `module.json` gave.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub enum Manifest {
34    Valid,
35    /// Not valid JSON. The message is the parser's, without the position.
36    InvalidJson {
37        message: String,
38        line: usize,
39    },
40    /// Valid JSON without a `name` that is a string. The package needs one.
41    NoName,
42}
43
44/// How many files of one kind a module has.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct KindCount {
47    /// `Models`, `Controllers`, `Tests`, or `Other`.
48    pub kind: String,
49    pub files: u32,
50}
51
52/// One module of an app.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Module {
55    /// The `name` of `module.json`. The folder name when the file gives none.
56    pub name: String,
57    /// The three letter code on the module's stamp.
58    pub code: String,
59    /// The module's folder. Absolute.
60    pub dir: PathBuf,
61    pub state: ModuleState,
62    pub description: String,
63    /// The load order the package uses, lowest first.
64    pub priority: i64,
65    pub manifest: Manifest,
66    /// The accepted public surface: the `surface` key of `module.json`. `None` when
67    /// the module has none, or it cannot be read as one.
68    pub surface: Option<AcceptedSurface>,
69    /// The namespace the module's classes share: `Modules\Billing`. From the
70    /// module's `composer.json`, else from the config and the module's name.
71    pub namespace: String,
72    /// Files in the module's folder. Hidden files, `vendor`, `node_modules` and
73    /// whatever `.gitignore` excludes are not counted.
74    pub files: u64,
75    /// Lines in the module's PHP files. Blade views are not PHP files.
76    pub lines: u64,
77    /// The files by kind, most files first. The kind comes from the folder a file is in.
78    pub kinds: Vec<KindCount>,
79    /// The names of the console commands the module declares outside its tests, sorted.
80    pub commands: Vec<String>,
81    /// Tests in the module's test files.
82    pub tests: u32,
83    /// Statements covered by tests, from the coverage report. `None` when there
84    /// is no report or it has none of the module's files.
85    pub coverage: Option<Coverage>,
86    /// Commits in git. `None` when the app is not in a repository.
87    pub churn: Option<Churn>,
88    /// Files of the module that git cannot restore: changed, staged, added,
89    /// deleted or untracked. `None` when the app is not in a repository, git is
90    /// missing, or git failed.
91    pub uncommitted: Option<u32>,
92}
93
94/// A module as read from disk, before it has a code, coverage and git data.
95pub(crate) struct FoundModule {
96    pub(crate) name: String,
97    pub(crate) dir: PathBuf,
98    pub(crate) state: ModuleState,
99    pub(crate) description: String,
100    pub(crate) priority: i64,
101    pub(crate) manifest: Manifest,
102    pub(crate) surface: Option<AcceptedSurface>,
103    /// The namespace the module's classes share: `Modules\Billing`.
104    pub(crate) namespace: String,
105    pub(crate) scan: Scan,
106}
107
108/// What walking a module's folder gave.
109#[derive(Debug, Default, Clone)]
110pub(crate) struct Scan {
111    pub(crate) files: u64,
112    pub(crate) lines: u64,
113    pub(crate) kinds: Vec<KindCount>,
114    pub(crate) tests: u32,
115    /// The names of the console commands of the module's files outside its tests.
116    pub(crate) commands: BTreeSet<String>,
117    /// The module's PHP files, by path.
118    pub(crate) sources: Vec<Source>,
119}
120
121/// A PHP file of a module.
122#[derive(Debug, Clone)]
123pub(crate) struct Source {
124    /// The path inside the module, with `/` between the parts.
125    pub(crate) relative: String,
126    /// True when the file is in a folder of tests.
127    pub(crate) is_test: bool,
128    /// What the file names and declares.
129    pub(crate) analysis: Arc<Analysis>,
130}
131
132/// What was worked out from the content of a file, kept so that a file that did
133/// not change is not read again.
134#[derive(Debug, Clone)]
135struct Facts {
136    size: u64,
137    modified: Option<SystemTime>,
138    /// Whether the file counted as a test file when it was read. Its tests are
139    /// counted only then.
140    is_test: bool,
141    lines: u64,
142    tests: u32,
143    analysis: Arc<Analysis>,
144}
145
146/// How far a read of an app is: how many of its PHP files are read.
147#[derive(Debug, Default)]
148pub struct Progress {
149    read: AtomicUsize,
150    total: AtomicUsize,
151}
152
153impl Progress {
154    /// The files read so far, and the files there are. Both are 0 before a read
155    /// has found the modules.
156    pub fn get(&self) -> (usize, usize) {
157        (
158            self.read.load(Ordering::Relaxed),
159            self.total.load(Ordering::Relaxed),
160        )
161    }
162}
163
164/// The facts of the files read so far, by path.
165#[derive(Debug, Default)]
166pub struct ReadCache {
167    files: HashMap<PathBuf, Facts>,
168    progress: Arc<Progress>,
169}
170
171impl ReadCache {
172    /// Forgets everything, so that the next read reads every file.
173    pub fn clear(&mut self) {
174        self.files.clear();
175    }
176
177    /// How far the read that uses this cache is. Another thread can watch it.
178    pub fn progress(&self) -> Arc<Progress> {
179        Arc::clone(&self.progress)
180    }
181}
182
183/// Finds the modules of an app: every folder directly under the modules folder
184/// that holds a `module.json`. Sorted by name.
185///
186/// Also gives the names the statuses file lists, for the check on entries without a module.
187pub(crate) fn find_modules(
188    layout: &Layout,
189    kinds: &Kinds,
190    cache: &mut ReadCache,
191) -> (Vec<FoundModule>, Vec<String>) {
192    let statuses = read_statuses(&layout.statuses_file);
193    let listed: Vec<String> = statuses.keys().cloned().collect();
194
195    let Ok(entries) = std::fs::read_dir(&layout.modules_dir) else {
196        return (Vec::new(), listed);
197    };
198    let dirs: Vec<PathBuf> = entries
199        .filter_map(Result::ok)
200        .map(|entry| entry.path())
201        .filter(|dir| dir.join("module.json").is_file())
202        .collect();
203    // How many PHP files there are, so that a watcher can say how far the read is.
204    let total: usize = dirs
205        .iter()
206        .map(|dir| {
207            files_of(dir)
208                .iter()
209                .filter(|(_, relative)| is_php(relative))
210                .count()
211        })
212        .sum();
213    cache.progress.read.store(0, Ordering::Relaxed);
214    cache.progress.total.store(total, Ordering::Relaxed);
215    let mut modules: Vec<FoundModule> = dirs
216        .into_iter()
217        .filter_map(|dir| {
218            let folder = dir.file_name()?.to_str()?.to_owned();
219            // The package's glob does not match folders that start with a dot.
220            if folder.starts_with('.') {
221                return None;
222            }
223            let (manifest, fields) = read_manifest(&dir.join("module.json"));
224            let name = fields.name.unwrap_or(folder);
225            let state = if !layout.uses_file_activator() {
226                ModuleState::Unknown
227            } else if statuses.get(&name) == Some(&serde_json::Value::Bool(true)) {
228                ModuleState::On
229            } else {
230                ModuleState::Off
231            };
232            Some(FoundModule {
233                scan: scan(&dir, kinds, cache),
234                namespace: read_namespace(&dir, layout, &name),
235                name,
236                dir,
237                state,
238                description: fields.description,
239                priority: fields.priority,
240                surface: fields.surface,
241                manifest,
242            })
243        })
244        .collect();
245
246    modules.sort_by(|a, b| {
247        a.name
248            .to_lowercase()
249            .cmp(&b.name.to_lowercase())
250            .then_with(|| a.name.cmp(&b.name))
251            .then_with(|| a.dir.cmp(&b.dir))
252    });
253    (modules, listed)
254}
255
256#[derive(Default)]
257struct ManifestFields {
258    name: Option<String>,
259    description: String,
260    priority: i64,
261    surface: Option<AcceptedSurface>,
262}
263
264fn read_manifest(path: &Path) -> (Manifest, ManifestFields) {
265    let json = std::fs::read(path).unwrap_or_default();
266    let value: serde_json::Value = match serde_json::from_slice(&json) {
267        Ok(value) => value,
268        Err(error) => {
269            // serde_json prints "<message> at line L column C". Keep the message.
270            let text = error.to_string();
271            let message = text.split(" at line ").next().unwrap_or(&text).to_owned();
272            let invalid = Manifest::InvalidJson {
273                message,
274                line: error.line(),
275            };
276            return (invalid, ManifestFields::default());
277        }
278    };
279
280    let fields = ManifestFields {
281        name: value
282            .get("name")
283            .and_then(|name| name.as_str())
284            .map(str::to_owned),
285        description: value
286            .get("description")
287            .and_then(|description| description.as_str())
288            .unwrap_or_default()
289            .to_owned(),
290        priority: value
291            .get("priority")
292            .and_then(serde_json::Value::as_i64)
293            .unwrap_or(0),
294        surface: AcceptedSurface::of_manifest(&value),
295    };
296    let manifest = if fields.name.is_some() {
297        Manifest::Valid
298    } else {
299        Manifest::NoName
300    };
301    (manifest, fields)
302}
303
304/// The entries of the statuses file. Empty when the file is missing or is not a JSON object.
305fn read_statuses(path: &Path) -> BTreeMap<String, serde_json::Value> {
306    std::fs::read(path)
307        .ok()
308        .and_then(|json| serde_json::from_slice(&json).ok())
309        .unwrap_or_default()
310}
311
312/// The namespace of a module: the shortest PSR-4 prefix of its `composer.json`,
313/// which is the one that maps to its app folder. Without one, the namespace of
314/// the config and the name of the module.
315fn read_namespace(dir: &Path, layout: &Layout, name: &str) -> String {
316    let from_composer = std::fs::read(dir.join("composer.json"))
317        .ok()
318        .and_then(|json| serde_json::from_slice::<serde_json::Value>(&json).ok())
319        .and_then(|composer| {
320            let prefixes = composer.get("autoload")?.get("psr-4")?.as_object()?;
321            prefixes.keys().min_by_key(|prefix| prefix.len()).cloned()
322        })
323        .map(|prefix| prefix.trim_matches('\\').to_owned())
324        .filter(|prefix| !prefix.is_empty());
325    from_composer.unwrap_or_else(|| format!("{}\\{name}", layout.namespace.trim_matches('\\')))
326}
327
328/// A file of a module, before its content is read.
329struct Entry {
330    path: PathBuf,
331    /// The path inside the module, with `/` between the parts.
332    relative: String,
333    /// The kind of the folder the file is in.
334    folder: String,
335    is_test: bool,
336    size: u64,
337    modified: Option<SystemTime>,
338}
339
340/// The files of a module, each with its path inside the module, `/` between the
341/// parts. Hidden files, ignored files and installed packages are left out.
342pub(crate) fn files_of(dir: &Path) -> Vec<(PathBuf, String)> {
343    let walk = WalkBuilder::new(dir)
344        // Apply .gitignore files also when the app is not a git repository.
345        .require_git(false)
346        .filter_entry(|entry| {
347            let is_dir = entry.file_type().is_some_and(|kind| kind.is_dir());
348            !(is_dir && matches!(entry.file_name().to_str(), Some("vendor" | "node_modules")))
349        })
350        .build();
351    walk.filter_map(Result::ok)
352        .filter(|entry| entry.file_type().is_some_and(|kind| kind.is_file()))
353        .map(|entry| {
354            let path = entry.path();
355            let relative = path
356                .strip_prefix(dir)
357                .unwrap_or(path)
358                .components()
359                .map(|part| part.as_os_str().to_string_lossy())
360                .collect::<Vec<_>>()
361                .join("/");
362            (path.to_owned(), relative)
363        })
364        .collect()
365}
366
367/// The name of the console command a class declares: from its signature or its
368/// command attribute, else from its `$name` property when its file is in the
369/// commands folder. `folder` is the kind of the folder the file is in.
370pub(crate) fn command_of(declared: &Declared, folder: &str) -> Option<String> {
371    declared.command.clone().or_else(|| {
372        declared
373            .name_property
374            .clone()
375            .filter(|_| folder == COMMANDS)
376    })
377}
378
379/// The command a scheduled task runs when its target is `php artisan <name> ...`,
380/// the form the actuator writes for a task of `$schedule->command()`. An app that
381/// sets `ARTISAN_BINARY` gives its path in place of `artisan`, such as `./artisan`.
382///
383/// The actuator writes a task's description in the same place, so a description
384/// written in this form is read as the command it names.
385pub(crate) fn artisan_command(target: &str) -> Option<&str> {
386    let mut words = target.split_whitespace();
387    let php = words.next() == Some("php");
388    let artisan = words
389        .next()
390        .and_then(|word| word.rsplit(['/', '\\']).next())
391        == Some("artisan");
392    if !(php && artisan) {
393        return None;
394    }
395    words.next().map(|name| name.trim_matches(['\'', '"']))
396}
397
398/// True for a PHP file that is not a Blade view: those end in `.php` but are templates.
399pub(crate) fn is_php(relative: &str) -> bool {
400    relative.ends_with(".php") && !relative.ends_with(".blade.php")
401}
402
403/// Walks a module's folder: counts its files by kind, the lines of its PHP files
404/// and the tests in its test files, and reads which classes each PHP file names.
405fn scan(dir: &Path, kinds: &Kinds, cache: &mut ReadCache) -> Scan {
406    let mut scan = Scan::default();
407    let mut by_kind: BTreeMap<String, u32> = BTreeMap::new();
408    let mut php: Vec<Entry> = Vec::new();
409
410    for (path, relative) in files_of(dir) {
411        let path = path.as_path();
412        let kind = kinds.of(&relative);
413        let is_test = kind == TESTS;
414        scan.files += 1;
415        *by_kind.entry(kind.clone()).or_default() += 1;
416
417        if is_php(&relative) {
418            let metadata = std::fs::metadata(path).ok();
419            php.push(Entry {
420                path: path.to_owned(),
421                relative,
422                folder: kind,
423                is_test,
424                size: metadata.as_ref().map_or(0, std::fs::Metadata::len),
425                modified: metadata.and_then(|metadata| metadata.modified().ok()),
426            });
427        }
428    }
429
430    // Read the files that are new or changed, on all cores.
431    let changed: Vec<&Entry> = php
432        .iter()
433        .filter(|entry| {
434            !cache.files.get(&entry.path).is_some_and(|facts| {
435                facts.size == entry.size
436                    && facts.modified == entry.modified
437                    && entry.modified.is_some()
438                    && facts.is_test == entry.is_test
439            })
440        })
441        .collect();
442    let progress = Arc::clone(&cache.progress);
443    progress
444        .read
445        .fetch_add(php.len() - changed.len(), Ordering::Relaxed);
446    let read: Vec<(PathBuf, Facts)> = changed
447        .par_iter()
448        .map(|entry| {
449            let source = std::fs::read(&entry.path).unwrap_or_default();
450            progress.read.fetch_add(1, Ordering::Relaxed);
451            let facts = Facts {
452                size: entry.size,
453                modified: entry.modified,
454                is_test: entry.is_test,
455                lines: count_lines(&source),
456                tests: if entry.is_test {
457                    count_tests(&source)
458                } else {
459                    0
460                },
461                analysis: Arc::new(analyze(&source)),
462            };
463            (entry.path.clone(), facts)
464        })
465        .collect();
466    cache.files.extend(read);
467
468    for entry in php {
469        let Some(facts) = cache.files.get(&entry.path) else {
470            continue;
471        };
472        scan.lines += facts.lines;
473        scan.tests += facts.tests;
474        if !entry.is_test {
475            scan.commands.extend(
476                facts
477                    .analysis
478                    .declares
479                    .iter()
480                    .filter_map(|declared| command_of(declared, &entry.folder)),
481            );
482        }
483        scan.sources.push(Source {
484            relative: entry.relative,
485            is_test: entry.is_test,
486            analysis: Arc::clone(&facts.analysis),
487        });
488    }
489    scan.sources.sort_by(|a, b| a.relative.cmp(&b.relative));
490
491    scan.kinds = by_kind
492        .into_iter()
493        .map(|(kind, files)| KindCount { kind, files })
494        .collect();
495    // Most files first; kinds with the same number of files by name.
496    scan.kinds
497        .sort_by(|a, b| b.files.cmp(&a.files).then_with(|| a.kind.cmp(&b.kind)));
498    scan
499}
500
501/// Lines of a file: line ends, plus a last line that has no line end.
502fn count_lines(source: &[u8]) -> u64 {
503    let ends = source.iter().filter(|byte| **byte == b'\n').count() as u64;
504    match source.last() {
505        Some(b'\n') | None => ends,
506        Some(_) => ends + 1,
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513
514    fn write(path: &Path, content: &str) {
515        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
516        std::fs::write(path, content).unwrap();
517    }
518
519    fn scan_dir(dir: &Path) -> Scan {
520        scan(dir, &Kinds::new(None, "app/"), &mut ReadCache::default())
521    }
522
523    #[test]
524    fn counts_files_but_not_hidden_ignored_or_installed_ones() {
525        let dir = tempfile::tempdir().unwrap();
526        let module = dir.path();
527        write(&module.join("module.json"), "{}");
528        write(&module.join("app/Models/Post.php"), "<?php");
529        write(&module.join("resources/views/index.blade.php"), "");
530        write(&module.join("tests/Unit/.gitkeep"), "");
531        write(&module.join("node_modules/left-pad/index.js"), "");
532        write(&module.join("vendor/autoload.php"), "<?php");
533        write(&module.join(".gitignore"), "/build\n");
534        write(&module.join("build/app.js"), "");
535        assert_eq!(scan_dir(module).files, 3);
536    }
537
538    #[test]
539    fn counts_lines_of_php_kinds_and_tests() {
540        let dir = tempfile::tempdir().unwrap();
541        let module = dir.path();
542        write(&module.join("module.json"), "{\n}\n");
543        write(
544            &module.join("app/Models/Post.php"),
545            "<?php\n\nclass Post {}\n",
546        );
547        write(&module.join("app/Models/Tag.php"), "<?php\nclass Tag {}");
548        write(
549            &module.join("app/Http/Controllers/PostController.php"),
550            "<?php\n",
551        );
552        write(
553            &module.join("resources/views/index.blade.php"),
554            "<p>\n</p>\n<?php echo 1; ?>\n",
555        );
556        write(
557            &module.join("tests/Unit/PostTest.php"),
558            "<?php\nclass PostTest { protected $signature = 'post:test';\n  function testTitle() {}\n  function testSlug() {}\n}\n",
559        );
560        // Not in a tests folder: its methods are not counted as tests.
561        write(
562            &module.join("app/Support/Check.php"),
563            "<?php class Check { protected $signature = 'check:run {--all}'; function testThis() {} }",
564        );
565
566        let scan = scan_dir(module);
567        assert_eq!(scan.files, 7);
568        // 3 + 2 + 1 + 5 + 1. The Blade view and module.json are not PHP.
569        assert_eq!(scan.lines, 12);
570        assert_eq!(scan.tests, 2);
571        // The command of the test file is not one of the module.
572        assert_eq!(scan.commands, BTreeSet::from(["check:run".to_owned()]));
573        let kinds: Vec<_> = scan
574            .kinds
575            .iter()
576            .map(|kind| (kind.kind.as_str(), kind.files))
577            .collect();
578        assert_eq!(
579            kinds,
580            [
581                ("Models", 2),
582                ("Controllers", 1),
583                ("Other", 1),
584                ("Support", 1),
585                ("Tests", 1),
586                ("Views", 1)
587            ]
588        );
589    }
590
591    #[test]
592    fn a_file_that_did_not_change_is_not_read_again() {
593        let dir = tempfile::tempdir().unwrap();
594        let file = dir.path().join("app/Models/Post.php");
595        write(&file, "<?php\nclass Post {}\n");
596        let kinds = Kinds::new(None, "app/");
597        let mut cache = ReadCache::default();
598        assert_eq!(scan(dir.path(), &kinds, &mut cache).lines, 2);
599
600        // Same size and time: the cached facts are used even if the cache is wrong.
601        cache.files.get_mut(&file).unwrap().lines = 99;
602        assert_eq!(scan(dir.path(), &kinds, &mut cache).lines, 99);
603
604        // Another size: read again.
605        write(&file, "<?php\nclass Post {}\n// more\n");
606        assert_eq!(scan(dir.path(), &kinds, &mut cache).lines, 3);
607
608        cache.clear();
609        assert_eq!(scan(dir.path(), &kinds, &mut cache).lines, 3);
610
611        // The config makes a folder hold tests: its files are read again.
612        write(
613            &dir.path().join("spec/Unit/PostTest.php"),
614            "<?php class PostTest { function testTitle() {} }",
615        );
616        assert_eq!(scan(dir.path(), &kinds, &mut cache).tests, 0);
617        let config = crate::php::read_config(
618            br#"<?php return ['paths' => ['generator' => ['test-unit' => 'spec/Unit']]];"#,
619        )
620        .unwrap();
621        let moved = Kinds::new(Some(&config), "app/");
622        assert_eq!(scan(dir.path(), &moved, &mut cache).tests, 1);
623    }
624
625    #[test]
626    fn counts_a_last_line_without_a_line_end() {
627        assert_eq!(count_lines(b""), 0);
628        assert_eq!(count_lines(b"a"), 1);
629        assert_eq!(count_lines(b"a\n"), 1);
630        assert_eq!(count_lines(b"a\nb"), 2);
631        assert_eq!(count_lines(b"a\r\nb\r\n"), 2);
632    }
633
634    #[test]
635    fn reads_the_fields_the_package_reads() {
636        let dir = tempfile::tempdir().unwrap();
637        let path = dir.path().join("module.json");
638
639        write(
640            &path,
641            r#"{"name": "Blog", "description": "Posts", "priority": 5}"#,
642        );
643        let (manifest, fields) = read_manifest(&path);
644        assert_eq!(manifest, Manifest::Valid);
645        assert_eq!(fields.name.as_deref(), Some("Blog"));
646        assert_eq!((fields.description.as_str(), fields.priority), ("Posts", 5));
647
648        write(&path, r#"{"alias": "blog"}"#);
649        assert_eq!(read_manifest(&path).0, Manifest::NoName);
650
651        write(&path, "{\n  \"name\": \"Blog\",\n");
652        let (manifest, fields) = read_manifest(&path);
653        assert_eq!(
654            manifest,
655            Manifest::InvalidJson {
656                message: "EOF while parsing a value".into(),
657                line: 3
658            }
659        );
660        assert_eq!(fields.name, None);
661    }
662
663    #[test]
664    fn a_statuses_file_that_is_missing_or_not_an_object_has_no_entries() {
665        let dir = tempfile::tempdir().unwrap();
666        let path = dir.path().join("modules_statuses.json");
667        assert!(read_statuses(&path).is_empty());
668        for content in ["", "[]", "[true]", "not json", "null"] {
669            write(&path, content);
670            assert!(read_statuses(&path).is_empty(), "{content:?}");
671        }
672        write(&path, r#"{"Blog": true}"#);
673        assert_eq!(read_statuses(&path).len(), 1);
674    }
675}