1use 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
17pub const DEFAULT_COVERAGE_LIMIT: u8 = 50;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
21pub enum Severity {
22 Problem,
24 Warning,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
30pub enum Check {
31 NoCircularUse,
32 PublicSurfaceOnly,
33 AllowedUse,
35 ValidManifest,
36 NamespaceMatchesFolder,
37 NoStaleStatus,
38 CoverageLimit,
39 TranslationsComplete,
41}
42
43impl Check {
44 pub fn is_rule(self) -> bool {
46 matches!(
47 self,
48 Check::NoCircularUse | Check::PublicSurfaceOnly | Check::AllowedUse
49 )
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub enum Detail {
56 CircularUse { files: Vec<(String, usize)> },
59 ReadsInternals {
62 of: String,
63 files: usize,
64 classes: Vec<String>,
65 },
66 OutsideAllowedUse { of: String, files: usize },
68 UnknownAllowedModule { entry: String },
71 InvalidManifest {
73 file: String,
74 message: String,
75 line: usize,
76 },
77 NoManifestName { file: String },
79 NamespaceMismatch { namespace: String, folder: String },
81 StaleStatus { entry: String, file: String },
83 LowCoverage { percent: u8, limit: u8 },
85 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 pub module: Option<String>,
101 pub detail: Detail,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106pub struct CheckResult {
107 pub check: Check,
108 pub checked: usize,
110 pub findings: usize,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Todo {
116 pub module: String,
117 pub waiting: usize,
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
123pub enum FindingState {
124 Problems(usize),
126 Warning,
127 Good,
128}
129
130#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
132pub struct Findings {
133 pub list: Vec<Finding>,
135 pub checks: Vec<CheckResult>,
137 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 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 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 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
189pub(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 pub(crate) status_entries: &'a [String],
198 pub(crate) statuses_file: &'a str,
199 pub(crate) has_coverage_report: bool,
201 pub(crate) coverage_limit: u8,
202 pub(crate) package: &'a PackageData,
204}
205
206pub(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 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 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 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 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 if checked > 0 {
421 ran(Check::TranslationsComplete, checked, found);
422 }
423 }
424
425 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 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}