Skip to main content

mortise_core/
findings.rs

1//! Findings: what Mortise works out from the files of an app.
2//!
3//! A finding is a problem (it breaks a rule or a check) or a warning (it is under a
4//! limit the app set). Findings are never called health: that word belongs to what
5//! the running app reports.
6
7use std::collections::BTreeSet;
8use std::path::Path;
9
10use serde::{Deserialize, Serialize};
11
12use crate::boundary::links::{Cycle, Link};
13use crate::boundary::rules::Rules;
14use crate::modules::module::{Manifest, Module, ModuleState};
15use crate::package::PackageData;
16
17/// The coverage limit of an app until it is changed: a module under it is a warning.
18pub const DEFAULT_COVERAGE_LIMIT: u8 = 50;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
21pub enum Severity {
22    /// Breaks a rule or a check.
23    Problem,
24    /// Under a limit the app set, or a name in the rules that is no module of the app.
25    Warning,
26}
27
28/// What Mortise checks. The first three are the boundary rules of the app.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
30pub enum Check {
31    NoCircularUse,
32    PublicSurfaceOnly,
33    /// Each module with a list in `allowed-use` uses only the modules of its list.
34    AllowedUse,
35    ValidManifest,
36    NamespaceMatchesFolder,
37    NoStaleStatus,
38    CoverageLimit,
39    /// From the report of `module:lang`. It runs only once the user checked translations.
40    TranslationsComplete,
41}
42
43impl Check {
44    /// True for the boundary rules, false for the checks on files.
45    pub fn is_rule(self) -> bool {
46        matches!(
47            self,
48            Check::NoCircularUse | Check::PublicSurfaceOnly | Check::AllowedUse
49        )
50    }
51}
52
53/// What exactly was found.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub enum Detail {
56    /// Modules use each other. `files` has, for each module of the circle, how
57    /// many of its files use another module of it.
58    CircularUse { files: Vec<(String, usize)> },
59    /// Files of the module read classes of another module that are not part of
60    /// its public surface.
61    ReadsInternals {
62        of: String,
63        files: usize,
64        classes: Vec<String>,
65    },
66    /// Files of the module use a module that its list in `allowed-use` does not name.
67    OutsideAllowedUse { of: String, files: usize },
68    /// `allowed-use` names a module that the app does not have: as a module with a
69    /// list, or in a list.
70    UnknownAllowedModule { entry: String },
71    /// `module.json` is not valid JSON. The message is the parser's.
72    InvalidManifest {
73        file: String,
74        message: String,
75        line: usize,
76    },
77    /// `module.json` has no `name`.
78    NoManifestName { file: String },
79    /// The namespace the module declares does not end in the name of its folder.
80    NamespaceMismatch { namespace: String, folder: String },
81    /// The statuses file lists a module that has no folder.
82    StaleStatus { entry: String, file: String },
83    /// The module is covered less than the limit of the app.
84    LowCoverage { percent: u8, limit: u8 },
85    /// A locale of the module lacks keys or files that its other locales have.
86    /// `from` is the other locale when the module has exactly two.
87    MissingTranslations {
88        locale: String,
89        keys: usize,
90        files: usize,
91        from: Option<String>,
92    },
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub struct Finding {
97    pub severity: Severity,
98    pub check: Check,
99    /// The module the finding is counted on. `None` for a finding of the app itself.
100    pub module: Option<String>,
101    pub detail: Detail,
102}
103
104/// A check that ran, with how many things it looked at and how many findings it gave.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106pub struct CheckResult {
107    pub check: Check,
108    /// Modules for most checks; entries for the statuses file.
109    pub checked: usize,
110    pub findings: usize,
111}
112
113/// Work in progress on a module. It is not a finding: it changes no mark and no count.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Todo {
116    pub module: String,
117    /// How many of its migrations wait to run, from the last migration state read.
118    pub waiting: usize,
119}
120
121/// The finding state of a module: its worst finding.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
123pub enum FindingState {
124    /// At least one problem, with how many.
125    Problems(usize),
126    Warning,
127    Good,
128}
129
130/// The findings of an app and the checks they came from.
131#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
132pub struct Findings {
133    /// Problems first, then warnings; within each by module.
134    pub list: Vec<Finding>,
135    /// Every check that ran, in the order of [`Check`].
136    pub checks: Vec<CheckResult>,
137    /// The modules with migrations waiting, by module. Never counted as findings.
138    pub todo: Vec<Todo>,
139}
140
141impl Findings {
142    pub fn problems(&self) -> usize {
143        self.list
144            .iter()
145            .filter(|finding| finding.severity == Severity::Problem)
146            .count()
147    }
148
149    pub fn warnings(&self) -> usize {
150        self.list
151            .iter()
152            .filter(|finding| finding.severity == Severity::Warning)
153            .count()
154    }
155
156    /// The findings counted on one module.
157    pub fn of<'a>(&'a self, module: &'a str) -> impl Iterator<Item = &'a Finding> {
158        self.list
159            .iter()
160            .filter(move |finding| finding.module.as_deref() == Some(module))
161    }
162
163    /// The worst finding of one module.
164    pub fn state_of(&self, module: &str) -> FindingState {
165        let problems = self
166            .of(module)
167            .filter(|finding| finding.severity == Severity::Problem)
168            .count();
169        if problems > 0 {
170            FindingState::Problems(problems)
171        } else if self.of(module).next().is_some() {
172            FindingState::Warning
173        } else {
174            FindingState::Good
175        }
176    }
177
178    /// How many rules and how many checks ran.
179    pub fn rules_and_checks(&self) -> (usize, usize) {
180        let rules = self
181            .checks
182            .iter()
183            .filter(|result| result.check.is_rule())
184            .count();
185        (rules, self.checks.len() - rules)
186    }
187}
188
189/// What the checks look at.
190pub(crate) struct Subject<'a> {
191    pub(crate) root: &'a Path,
192    pub(crate) modules: &'a [Module],
193    pub(crate) links: &'a [Link],
194    pub(crate) cycles: &'a [Cycle],
195    pub(crate) rules: &'a Rules,
196    /// The names in the statuses file, and the file as the user writes it.
197    pub(crate) status_entries: &'a [String],
198    pub(crate) statuses_file: &'a str,
199    /// Without a coverage report the coverage limit is not checked.
200    pub(crate) has_coverage_report: bool,
201    pub(crate) coverage_limit: u8,
202    /// What the package said in the reads the user started.
203    pub(crate) package: &'a PackageData,
204}
205
206/// Runs every check.
207pub(crate) fn find(subject: &Subject<'_>) -> Findings {
208    let mut list: Vec<Finding> = Vec::new();
209    let mut checks: Vec<CheckResult> = Vec::new();
210    let modules = subject.modules;
211    let shown = |path: &Path| crate::app::shown(subject.root, path);
212    let mut ran = |check: Check, checked: usize, found: Vec<Finding>| {
213        checks.push(CheckResult {
214            check,
215            checked,
216            findings: found.len(),
217        });
218        list.extend(found);
219    };
220
221    if subject.rules.no_circular_use {
222        // A circle is counted once, on the module with fewer files in it.
223        let found = subject
224            .cycles
225            .iter()
226            .map(|cycle| Finding {
227                severity: Severity::Problem,
228                check: Check::NoCircularUse,
229                module: Some(cycle.carrier.clone()),
230                detail: Detail::CircularUse {
231                    files: cycle.files.clone(),
232                },
233            })
234            .collect();
235        ran(Check::NoCircularUse, modules.len(), found);
236    }
237
238    if subject.rules.public_surface_only {
239        let found = subject
240            .links
241            .iter()
242            .filter(|link| link.internal_files() > 0)
243            .map(|link| {
244                let mut classes: Vec<String> = link
245                    .refs
246                    .iter()
247                    .filter(|reference| reference.internal)
248                    .map(|reference| reference.class.clone())
249                    .collect();
250                classes.sort();
251                classes.dedup();
252                Finding {
253                    severity: Severity::Problem,
254                    check: Check::PublicSurfaceOnly,
255                    module: Some(link.from.clone()),
256                    detail: Detail::ReadsInternals {
257                        of: link.to.clone(),
258                        files: link.internal_files(),
259                        classes,
260                    },
261                }
262            })
263            .collect();
264        ran(Check::PublicSurfaceOnly, modules.len(), found);
265    }
266
267    let in_app = |name: &str| modules.iter().any(|module| module.name == name);
268    let allowed_use = subject.rules.allowed_use.as_ref();
269    if let Some(allowed) = allowed_use.filter(|allowed| allowed.enabled) {
270        let mut found: Vec<Finding> = subject
271            .links
272            .iter()
273            .filter(|link| link.outside_allowed)
274            .map(|link| Finding {
275                severity: Severity::Problem,
276                check: Check::AllowedUse,
277                module: Some(link.from.clone()),
278                detail: Detail::OutsideAllowedUse {
279                    of: link.to.clone(),
280                    files: link.files(),
281                },
282            })
283            .collect();
284        // A name that is no module, so that a typing mistake does not pass in silence.
285        let unknown: BTreeSet<&str> = allowed
286            .modules
287            .iter()
288            .flat_map(|(module, list)| std::iter::once(module).chain(list))
289            .map(String::as_str)
290            .filter(|name| !in_app(name))
291            .collect();
292        found.extend(unknown.into_iter().map(|entry| Finding {
293            severity: Severity::Warning,
294            check: Check::AllowedUse,
295            module: None,
296            detail: Detail::UnknownAllowedModule {
297                entry: entry.to_owned(),
298            },
299        }));
300        let checked = modules
301            .iter()
302            .filter(|module| allowed.modules.contains_key(&module.name))
303            .count();
304        ran(Check::AllowedUse, checked, found);
305    }
306
307    let found = modules
308        .iter()
309        .filter_map(|module| {
310            let file = shown(&module.dir.join("module.json"));
311            let detail = match &module.manifest {
312                Manifest::Valid => return None,
313                Manifest::InvalidJson { message, line } => Detail::InvalidManifest {
314                    file,
315                    message: message.clone(),
316                    line: *line,
317                },
318                Manifest::NoName => Detail::NoManifestName { file },
319            };
320            Some(Finding {
321                severity: Severity::Problem,
322                check: Check::ValidManifest,
323                module: Some(module.name.clone()),
324                detail,
325            })
326        })
327        .collect();
328    ran(Check::ValidManifest, modules.len(), found);
329
330    let found = modules
331        .iter()
332        .filter(|module| module.manifest == Manifest::Valid)
333        .filter_map(|module| {
334            let folder = module.dir.file_name()?.to_str()?;
335            let last = module.namespace.rsplit('\\').next().unwrap_or_default();
336            (last != folder).then(|| Finding {
337                severity: Severity::Problem,
338                check: Check::NamespaceMatchesFolder,
339                module: Some(module.name.clone()),
340                detail: Detail::NamespaceMismatch {
341                    namespace: module.namespace.clone(),
342                    folder: shown(&module.dir),
343                },
344            })
345        })
346        .collect();
347    ran(Check::NamespaceMatchesFolder, modules.len(), found);
348
349    let found = subject
350        .status_entries
351        .iter()
352        .filter(|entry| !modules.iter().any(|module| &module.name == *entry))
353        .map(|entry| Finding {
354            severity: Severity::Problem,
355            check: Check::NoStaleStatus,
356            module: None,
357            detail: Detail::StaleStatus {
358                entry: entry.clone(),
359                file: subject.statuses_file.to_owned(),
360            },
361        })
362        .collect();
363    ran(Check::NoStaleStatus, subject.status_entries.len(), found);
364
365    // Without a report coverage is unknown, which is not a finding.
366    if subject.has_coverage_report {
367        let found = modules
368            .iter()
369            .filter(|module| module.state != ModuleState::Off)
370            .filter_map(|module| {
371                let percent = module.coverage?.percent()?;
372                (percent < subject.coverage_limit).then(|| Finding {
373                    severity: Severity::Warning,
374                    check: Check::CoverageLimit,
375                    module: Some(module.name.clone()),
376                    detail: Detail::LowCoverage {
377                        percent,
378                        limit: subject.coverage_limit,
379                    },
380                })
381            })
382            .collect();
383        ran(Check::CoverageLimit, modules.len(), found);
384    }
385
386    // Only a module of the app counts: the report can be older than a delete.
387    if let Some(report) = &subject.package.translations {
388        let checked = report
389            .modules
390            .iter()
391            .filter(|module| module.checked && in_app(&module.name))
392            .count();
393        let found = report
394            .modules
395            .iter()
396            .filter(|module| in_app(&module.name))
397            .flat_map(|module| {
398                module.locales.iter().filter_map(|(locale, missing)| {
399                    let keys = missing.missing_keys.values().map(Vec::len).sum::<usize>();
400                    let files = missing.missing_files.len();
401                    let from = match module.locales.keys().collect::<Vec<_>>()[..] {
402                        [a, b] => Some(if a == locale { b } else { a }.clone()),
403                        _ => None,
404                    };
405                    (keys + files > 0).then(|| Finding {
406                        severity: Severity::Warning,
407                        check: Check::TranslationsComplete,
408                        module: Some(module.name.clone()),
409                        detail: Detail::MissingTranslations {
410                            locale: locale.clone(),
411                            keys,
412                            files,
413                            from,
414                        },
415                    })
416                })
417            })
418            .collect();
419        // A report with no module of two locales checked nothing: no result.
420        if checked > 0 {
421            ran(Check::TranslationsComplete, checked, found);
422        }
423    }
424
425    // The to do list is of the default connection, the one the app migrates.
426    let todo = subject
427        .package
428        .migrations_for("")
429        .into_iter()
430        .flatten()
431        .filter(|(name, state)| !state.waiting.is_empty() && in_app(name))
432        .map(|(name, state)| Todo {
433            module: name.clone(),
434            waiting: state.waiting.len(),
435        })
436        .collect();
437
438    // Problems first, then warnings; within each by module, the app's own last.
439    list.sort_by(|a, b| {
440        a.severity
441            .cmp(&b.severity)
442            .then_with(|| a.module.is_none().cmp(&b.module.is_none()))
443            .then_with(|| a.module.cmp(&b.module))
444            .then_with(|| a.check.cmp(&b.check))
445    });
446    Findings { list, checks, todo }
447}