1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22pub enum ModuleState {
23 On,
25 Off,
27 Unknown,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub enum Manifest {
34 Valid,
35 InvalidJson {
37 message: String,
38 line: usize,
39 },
40 NoName,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct KindCount {
47 pub kind: String,
49 pub files: u32,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Module {
55 pub name: String,
57 pub code: String,
59 pub dir: PathBuf,
61 pub state: ModuleState,
62 pub description: String,
63 pub priority: i64,
65 pub manifest: Manifest,
66 pub surface: Option<AcceptedSurface>,
69 pub namespace: String,
72 pub files: u64,
75 pub lines: u64,
77 pub kinds: Vec<KindCount>,
79 pub commands: Vec<String>,
81 pub tests: u32,
83 pub coverage: Option<Coverage>,
86 pub churn: Option<Churn>,
88 pub uncommitted: Option<u32>,
92}
93
94pub(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 pub(crate) namespace: String,
105 pub(crate) scan: Scan,
106}
107
108#[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 pub(crate) commands: BTreeSet<String>,
117 pub(crate) sources: Vec<Source>,
119}
120
121#[derive(Debug, Clone)]
123pub(crate) struct Source {
124 pub(crate) relative: String,
126 pub(crate) is_test: bool,
128 pub(crate) analysis: Arc<Analysis>,
130}
131
132#[derive(Debug, Clone)]
135struct Facts {
136 size: u64,
137 modified: Option<SystemTime>,
138 is_test: bool,
141 lines: u64,
142 tests: u32,
143 analysis: Arc<Analysis>,
144}
145
146#[derive(Debug, Default)]
148pub struct Progress {
149 read: AtomicUsize,
150 total: AtomicUsize,
151}
152
153impl Progress {
154 pub fn get(&self) -> (usize, usize) {
157 (
158 self.read.load(Ordering::Relaxed),
159 self.total.load(Ordering::Relaxed),
160 )
161 }
162}
163
164#[derive(Debug, Default)]
166pub struct ReadCache {
167 files: HashMap<PathBuf, Facts>,
168 progress: Arc<Progress>,
169}
170
171impl ReadCache {
172 pub fn clear(&mut self) {
174 self.files.clear();
175 }
176
177 pub fn progress(&self) -> Arc<Progress> {
179 Arc::clone(&self.progress)
180 }
181}
182
183pub(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 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 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 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
304fn 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
312fn 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
328struct Entry {
330 path: PathBuf,
331 relative: String,
333 folder: String,
335 is_test: bool,
336 size: u64,
337 modified: Option<SystemTime>,
338}
339
340pub(crate) fn files_of(dir: &Path) -> Vec<(PathBuf, String)> {
343 let walk = WalkBuilder::new(dir)
344 .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
367pub(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
379pub(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
398pub(crate) fn is_php(relative: &str) -> bool {
400 relative.ends_with(".php") && !relative.ends_with(".blade.php")
401}
402
403fn 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 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 scan.kinds
497 .sort_by(|a, b| b.files.cmp(&a.files).then_with(|| a.kind.cmp(&b.kind)));
498 scan
499}
500
501fn 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 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 assert_eq!(scan.lines, 12);
570 assert_eq!(scan.tests, 2);
571 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 cache.files.get_mut(&file).unwrap().lines = 99;
602 assert_eq!(scan(dir.path(), &kinds, &mut cache).lines, 99);
603
604 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 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}