1use std::path::{Path, PathBuf};
4
5use fallow_config::{AuthoredRule, LogicalGroup, LogicalGroupStatus, ResolvedBoundaryConfig};
6use fallow_output::{ListEntryPointOutput, WorkspaceInfo as WorkspaceOutputInfo, WorkspacesOutput};
7use fallow_types::discover::{DiscoveredFile, EntryPoint};
8use fallow_types::path_util::display_relative;
9use rustc_hash::FxHashMap;
10
11use crate::{
12 AnalysisOptions, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
13 BoundariesListing, ListJsonEnvelope, ListJsonOutputInput, ProgrammaticError,
14 analysis_context::{changed_files_for_run, validate_workspace_selection},
15 resolve_programmatic_analysis_context, serialize_list_json_output,
16};
17
18type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
19
20#[derive(Debug, Clone, Default)]
22pub struct ProjectInfoOptions {
23 pub analysis: AnalysisOptions,
25 pub entry_points: bool,
27 pub files: bool,
29 pub plugins: bool,
31 pub boundaries: bool,
33}
34
35#[derive(Debug, Clone, Default)]
37pub struct ListBoundariesOptions {
38 pub analysis: AnalysisOptions,
40}
41
42#[derive(Debug, Clone)]
44pub struct ProjectInfoProgrammaticOutput {
45 pub plugins: Option<Vec<String>>,
47 pub files: Option<Vec<String>>,
49 pub entry_points: Option<Vec<ListEntryPointOutput>>,
51 pub boundaries: Option<BoundariesListing>,
53 pub workspaces: Option<WorkspacesOutput<fallow_config::WorkspaceDiagnostic>>,
55 pub plugin_diagnostics: Vec<fallow_config::WorkspaceDiagnostic>,
58 pub envelope: ListJsonEnvelope,
60}
61
62pub fn serialize_project_info_programmatic_json(
68 output: ProjectInfoProgrammaticOutput,
69) -> ProgrammaticResult<serde_json::Value> {
70 serialize_list_json_output(
71 ListJsonOutputInput {
72 plugins: output.plugins,
73 files: output.files,
74 entry_points: output.entry_points,
75 boundaries: output.boundaries,
76 entry_weight: None,
77 workspaces: output.workspaces,
78 plugin_diagnostics: output.plugin_diagnostics,
79 },
80 output.envelope,
81 )
82 .map_err(|err| {
83 ProgrammaticError::new(format!("failed to serialize project info output: {err}"), 2)
84 .with_code("FALLOW_PROJECT_INFO_SERIALIZE_FAILED")
85 .with_context("project_info")
86 })
87}
88
89#[derive(Debug, Clone)]
91pub struct ListBoundariesProgrammaticOutput {
92 pub boundaries: BoundariesListing,
94}
95
96pub fn serialize_list_boundaries_programmatic_json(
102 output: ListBoundariesProgrammaticOutput,
103) -> ProgrammaticResult<serde_json::Value> {
104 serialize_list_json_output(
105 ListJsonOutputInput::<BoundariesListing, serde_json::Value> {
106 plugins: None,
107 files: None,
108 entry_points: None,
109 boundaries: Some(output.boundaries),
110 entry_weight: None,
111 workspaces: None,
112 plugin_diagnostics: Vec::new(),
113 },
114 ListJsonEnvelope::Boundaries,
115 )
116 .map_err(|err| {
117 ProgrammaticError::new(
118 format!("failed to serialize list boundaries output: {err}"),
119 2,
120 )
121 .with_code("FALLOW_LIST_BOUNDARIES_SERIALIZE_FAILED")
122 .with_context("list_boundaries")
123 })
124}
125
126#[derive(Debug, Clone)]
128pub struct BoundaryData {
129 pub zones: Vec<ZoneInfo>,
131 pub rules: Vec<RuleInfo>,
133 pub logical_groups: Vec<LogicalGroupInfo>,
135 pub is_empty: bool,
137}
138
139#[derive(Debug, Clone)]
141pub struct ZoneInfo {
142 pub name: String,
144 pub patterns: Vec<String>,
146 pub file_count: usize,
148 pub public_files: Vec<String>,
150}
151
152#[derive(Debug, Clone)]
154pub struct RuleInfo {
155 pub from: String,
157 pub allow: Vec<String>,
159}
160
161#[derive(Debug, Clone)]
163pub struct LogicalGroupInfo {
164 pub name: String,
166 pub children: Vec<String>,
168 pub auto_discover: Vec<String>,
170 pub authored_rule: Option<AuthoredRule>,
172 pub fallback_zone: Option<String>,
174 pub source_zone_index: usize,
176 pub status: LogicalGroupStatus,
178 pub file_count: usize,
180 pub child_file_count: usize,
182 pub fallback_file_count: usize,
184 pub merged_from: Option<Vec<usize>>,
186 pub original_zone_root: Option<String>,
188 pub child_source_indices: Vec<usize>,
190}
191
192pub fn run_list_boundaries(
202 options: &ListBoundariesOptions,
203) -> ProgrammaticResult<ListBoundariesProgrammaticOutput> {
204 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
205 resolved.install(|| {
206 resolved.ensure_not_cancelled("config load and file discovery")?;
207 let session = load_list_session(&options.analysis)?;
208 validate_workspace_selection(&resolved, session.workspaces())?;
209 resolved.ensure_not_cancelled("the boundary listing")?;
210 let changed_files = changed_files_for_run(&resolved)?;
211 let discovered = scoped_discovered_files(session.files(), changed_files.as_ref());
212 let data = compute_boundary_data(session.config(), Some(&discovered));
213
214 Ok(ListBoundariesProgrammaticOutput {
215 boundaries: boundary_data_to_output(&data),
216 })
217 })
218}
219
220pub fn run_project_info(
230 options: &ProjectInfoOptions,
231) -> ProgrammaticResult<ProjectInfoProgrammaticOutput> {
232 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
233 resolved.install(|| {
234 resolved.ensure_not_cancelled("config load and file discovery")?;
235 let session = load_list_session(&options.analysis)?;
236 validate_workspace_selection(&resolved, session.workspaces())?;
237 resolved.ensure_not_cancelled("the project listing")?;
238 let config = session.config();
239 let workspaces = session.workspaces();
240 let show_all = project_info_should_show_all(options);
241 let changed_files = changed_files_for_run(&resolved)?;
242 let discovered =
243 project_info_discovered_files(options, show_all, &session, changed_files.as_ref());
244 let discovered_ref = discovered.as_deref();
245
246 let inventory = collect_inventory(&session, options, show_all)?;
247 let (plugin_result, entry_points) = match inventory {
248 Some(inventory) => (
249 Some(inventory.plugins),
250 inventory
251 .entry_points
252 .map(|entries| scoped_entry_points(entries, changed_files.as_ref())),
253 ),
254 None => (None, None),
255 };
256 let plugin_diagnostics = plugin_result
257 .as_ref()
258 .map(|result| {
259 result
260 .plugin_diagnostics(&config.root)
261 .into_iter()
262 .map(|diagnostic| diagnostic.into_root_relative(&config.root))
263 .collect()
264 })
265 .unwrap_or_default();
266 let boundaries = options
267 .boundaries
268 .then(|| boundary_data_to_output(&compute_boundary_data(config, discovered_ref)));
269 let workspaces = if show_all {
270 Some(collect_workspace_output(
271 resolved.root(),
272 workspaces,
273 session.workspace_diagnostics(),
274 ))
275 } else {
276 None
277 };
278 let envelope = if boundaries.is_some() {
279 ListJsonEnvelope::Boundaries
280 } else {
281 ListJsonEnvelope::Plain
282 };
283
284 Ok(ProjectInfoProgrammaticOutput {
285 plugins: collect_plugins(options, show_all, plugin_result.as_ref()),
286 files: collect_files(options, show_all, discovered_ref, resolved.root()),
287 entry_points: entry_points
288 .map(|entries| entry_points_to_output(&entries, resolved.root())),
289 boundaries,
290 workspaces,
291 plugin_diagnostics,
292 envelope,
293 })
294 })
295}
296
297fn project_info_discovered_files(
298 options: &ProjectInfoOptions,
299 show_all: bool,
300 session: &fallow_engine::session::AnalysisSession,
301 changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
302) -> Option<Vec<DiscoveredFile>> {
303 let needs_discovery =
304 options.files || options.entry_points || options.boundaries || options.plugins || show_all;
305 needs_discovery.then(|| scoped_discovered_files(session.files(), changed_files))
306}
307
308fn scoped_discovered_files(
309 files: &[DiscoveredFile],
310 changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
311) -> Vec<DiscoveredFile> {
312 let Some(changed_files) = changed_files else {
313 return files.to_vec();
314 };
315 files
316 .iter()
317 .filter(|file| changed_files.contains(&file.path))
318 .cloned()
319 .collect()
320}
321
322fn load_list_session(
325 analysis: &crate::AnalysisOptions,
326) -> ProgrammaticResult<fallow_engine::session::AnalysisSession> {
327 let run = crate::run::resolve_programmatic_run(analysis, &crate::run::ProgrammaticEntry::List)?;
328 Ok(crate::run::runnable(&run, fallow_config::PlannedAnalysis::DeadCode)?.open_session())
329}
330
331const fn project_info_should_show_all(options: &ProjectInfoOptions) -> bool {
332 !options.entry_points && !options.files && !options.plugins && !options.boundaries
333}
334
335fn collect_plugins(
336 options: &ProjectInfoOptions,
337 show_all: bool,
338 plugin_result: Option<&fallow_engine::plugins::AggregatedPluginResult>,
339) -> Option<Vec<String>> {
340 if options.plugins || show_all {
341 plugin_result.map(|plugin_result| plugin_result.active_plugins().to_vec())
342 } else {
343 None
344 }
345}
346
347fn collect_files(
348 options: &ProjectInfoOptions,
349 show_all: bool,
350 discovered: Option<&[DiscoveredFile]>,
351 root: &Path,
352) -> Option<Vec<String>> {
353 if options.files || show_all {
354 discovered.map(|files| {
355 files
356 .iter()
357 .map(|file| display_relative(root, &file.path))
358 .collect()
359 })
360 } else {
361 None
362 }
363}
364
365fn collect_inventory(
369 session: &fallow_engine::session::AnalysisSession,
370 options: &ProjectInfoOptions,
371 show_all: bool,
372) -> ProgrammaticResult<Option<fallow_engine::list_inventory::ListingInventory>> {
373 if !(options.plugins || options.entry_points || show_all) {
374 return Ok(None);
375 }
376 fallow_engine::list_inventory::collect_listing_inventory(
377 session,
378 options.entry_points || show_all,
379 )
380 .map(Some)
381 .map_err(|err| {
382 ProgrammaticError::new(err.message(), 2)
383 .with_code("FALLOW_PLUGIN_REGEX_FAILED")
384 .with_context("project_info.plugins")
385 })
386}
387
388fn scoped_entry_points(
391 entry_points: Vec<EntryPoint>,
392 changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
393) -> Vec<EntryPoint> {
394 let Some(changed_files) = changed_files else {
395 return entry_points;
396 };
397 entry_points
398 .into_iter()
399 .filter(|entry| changed_files.contains(&entry.path))
400 .collect()
401}
402
403fn entry_points_to_output(entries: &[EntryPoint], root: &Path) -> Vec<ListEntryPointOutput> {
404 entries
405 .iter()
406 .map(|entry| ListEntryPointOutput {
407 path: display_relative(root, &entry.path),
408 source: entry.source.to_string(),
409 script: entry.source.script().map(str::to_string),
410 })
411 .collect()
412}
413
414fn collect_workspace_output(
415 root: &Path,
416 workspaces: &[fallow_config::WorkspaceInfo],
417 diagnostics: &[fallow_config::WorkspaceDiagnostic],
418) -> WorkspacesOutput<fallow_config::WorkspaceDiagnostic> {
419 let workspaces = workspaces
420 .iter()
421 .map(|workspace| {
422 let relative = workspace.root.strip_prefix(root).unwrap_or(&workspace.root);
423 WorkspaceOutputInfo {
424 name: workspace.name.clone(),
425 path: relative.display().to_string().replace('\\', "/"),
426 is_internal_dependency: workspace.is_internal_dependency,
427 }
428 })
429 .collect::<Vec<_>>();
430 WorkspacesOutput {
431 workspace_count: workspaces.len(),
432 workspaces,
433 workspace_diagnostics: diagnostics
437 .iter()
438 .map(|diagnostic| diagnostic.clone().into_root_relative(root))
439 .collect(),
440 }
441}
442
443#[must_use]
445pub fn compute_boundary_data(
446 config: &fallow_config::ResolvedConfig,
447 discovered: Option<&[DiscoveredFile]>,
448) -> BoundaryData {
449 let boundaries = &config.boundaries;
450
451 if boundaries.is_empty() {
452 return BoundaryData {
453 zones: vec![],
454 rules: vec![],
455 logical_groups: vec![],
456 is_empty: true,
457 };
458 }
459
460 let zones = build_boundary_zones(&config.root, boundaries, discovered);
461 let rules = build_boundary_rules(boundaries);
462 let logical_groups = build_logical_groups(boundaries, &zones);
463
464 BoundaryData {
465 zones,
466 rules,
467 logical_groups,
468 is_empty: false,
469 }
470}
471
472fn build_boundary_zones(
473 root: &Path,
474 boundaries: &ResolvedBoundaryConfig,
475 discovered: Option<&[DiscoveredFile]>,
476) -> Vec<ZoneInfo> {
477 let file_counts = count_boundary_files_by_zone(root, boundaries, discovered);
478
479 boundaries
480 .zones
481 .iter()
482 .map(|zone| ZoneInfo {
483 name: zone.name.clone(),
484 patterns: zone.matchers.iter().map(|m| m.glob().to_string()).collect(),
485 file_count: file_counts.get(zone.name.as_str()).copied().unwrap_or(0),
486 public_files: zone.public_files.clone(),
487 })
488 .collect()
489}
490
491fn count_boundary_files_by_zone<'a>(
492 root: &Path,
493 boundaries: &'a ResolvedBoundaryConfig,
494 discovered: Option<&[DiscoveredFile]>,
495) -> FxHashMap<&'a str, usize> {
496 let mut file_counts = FxHashMap::default();
497 let Some(files) = discovered else {
498 return file_counts;
499 };
500
501 for file in files {
502 let Ok(relative_path) = file.path.strip_prefix(root) else {
503 continue;
504 };
505 let relative_path = relative_path.to_string_lossy().replace('\\', "/");
506 if let Some(zone_name) = boundaries.classify_zone(&relative_path) {
507 *file_counts.entry(zone_name).or_default() += 1;
508 }
509 }
510
511 file_counts
512}
513
514fn build_boundary_rules(boundaries: &ResolvedBoundaryConfig) -> Vec<RuleInfo> {
515 boundaries
516 .rules
517 .iter()
518 .map(|rule| RuleInfo {
519 from: rule.from_zone.clone(),
520 allow: rule.allowed_zones.clone(),
521 })
522 .collect()
523}
524
525fn build_logical_groups(
526 boundaries: &ResolvedBoundaryConfig,
527 zones: &[ZoneInfo],
528) -> Vec<LogicalGroupInfo> {
529 let zone_count_by_name: FxHashMap<&str, usize> = zones
530 .iter()
531 .map(|zone| (zone.name.as_str(), zone.file_count))
532 .collect();
533
534 boundaries
535 .logical_groups
536 .iter()
537 .map(|group| logical_group_info(group, &zone_count_by_name))
538 .collect()
539}
540
541fn logical_group_info(
542 group: &LogicalGroup,
543 zone_count_by_name: &FxHashMap<&str, usize>,
544) -> LogicalGroupInfo {
545 let child_file_count: usize = group
546 .children
547 .iter()
548 .filter_map(|child| zone_count_by_name.get(child.as_str()).copied())
549 .sum();
550 let fallback_file_count = group
551 .fallback_zone
552 .as_deref()
553 .and_then(|fallback| zone_count_by_name.get(fallback).copied())
554 .unwrap_or(0);
555
556 LogicalGroupInfo {
557 name: group.name.clone(),
558 children: group.children.clone(),
559 auto_discover: group.auto_discover.clone(),
560 authored_rule: group.authored_rule.clone(),
561 fallback_zone: group.fallback_zone.clone(),
562 source_zone_index: group.source_zone_index,
563 status: group.status,
564 file_count: child_file_count + fallback_file_count,
565 child_file_count,
566 fallback_file_count,
567 merged_from: group.merged_from.clone(),
568 original_zone_root: group.original_zone_root.clone(),
569 child_source_indices: group.child_source_indices.clone(),
570 }
571}
572
573#[must_use]
575pub fn boundary_data_to_output(data: &BoundaryData) -> BoundariesListing {
576 if data.is_empty {
577 return BoundariesListing {
578 configured: false,
579 zone_count: 0,
580 zones: Vec::new(),
581 rule_count: 0,
582 rules: Vec::new(),
583 logical_group_count: 0,
584 logical_groups: Vec::new(),
585 };
586 }
587
588 BoundariesListing {
589 configured: true,
590 zone_count: data.zones.len(),
591 zones: data
592 .zones
593 .iter()
594 .map(|zone| BoundariesListZone {
595 name: zone.name.clone(),
596 patterns: zone.patterns.clone(),
597 file_count: zone.file_count,
598 public_files: zone.public_files.clone(),
599 })
600 .collect(),
601 rule_count: data.rules.len(),
602 rules: data
603 .rules
604 .iter()
605 .map(|rule| BoundariesListRule {
606 from: rule.from.clone(),
607 allow: rule.allow.clone(),
608 })
609 .collect(),
610 logical_group_count: data.logical_groups.len(),
611 logical_groups: data
612 .logical_groups
613 .iter()
614 .map(logical_group_info_to_output)
615 .collect(),
616 }
617}
618
619fn logical_group_info_to_output(group: &LogicalGroupInfo) -> BoundariesListLogicalGroup {
620 BoundariesListLogicalGroup {
621 name: group.name.clone(),
622 children: group.children.clone(),
623 auto_discover: group.auto_discover.clone(),
624 status: group.status,
625 source_zone_index: group.source_zone_index,
626 file_count: group.file_count,
627 authored_rule: group.authored_rule.clone(),
628 fallback_zone: group.fallback_zone.clone(),
629 merged_from: group.merged_from.clone(),
630 original_zone_root: group.original_zone_root.clone(),
631 child_source_indices: group.child_source_indices.clone(),
632 }
633}
634
635#[cfg(test)]
636mod tests {
637 use std::process::Command;
638
639 use fallow_config::ResolvedZone;
640 use fallow_types::discover::FileId;
641 use globset::Glob;
642 use serde_json::json;
643
644 use super::*;
645
646 #[test]
651 fn workspace_output_emits_project_relative_diagnostic_paths() {
652 let root = Path::new("/project");
653 let output = collect_workspace_output(
654 root,
655 &[],
656 &[fallow_config::WorkspaceDiagnostic::new(
657 root,
658 root.join("packages/inner"),
659 fallow_config::WorkspaceDiagnosticKind::UndeclaredWorkspace,
660 )],
661 );
662
663 let value = serde_json::to_value(&output).expect("workspaces output serializes");
664 assert_eq!(value["workspace_diagnostics"][0]["path"], "packages/inner");
665 }
666
667 fn empty_boundary_data() -> BoundaryData {
668 BoundaryData {
669 zones: vec![],
670 rules: vec![],
671 logical_groups: vec![],
672 is_empty: true,
673 }
674 }
675
676 fn boundary_data_to_json(data: &BoundaryData) -> serde_json::Value {
677 serde_json::to_value(boundary_data_to_output(data))
678 .expect("boundary list output should serialize")
679 }
680
681 fn resolved_zone(name: &str, patterns: &[&str]) -> ResolvedZone {
682 ResolvedZone {
683 name: name.to_string(),
684 patterns: patterns
685 .iter()
686 .map(|pattern| (*pattern).to_string())
687 .collect(),
688 matchers: patterns
689 .iter()
690 .map(|pattern| {
691 Glob::new(pattern)
692 .expect("valid test glob")
693 .compile_matcher()
694 })
695 .collect(),
696 root: None,
697 public_files: vec![],
698 public_file_matchers: vec![],
699 }
700 }
701
702 fn discovered_files(root: &Path, relative_paths: &[&str]) -> Vec<DiscoveredFile> {
703 relative_paths
704 .iter()
705 .enumerate()
706 .map(|(index, relative_path)| DiscoveredFile {
707 id: FileId(u32::try_from(index).expect("test file count fits in u32")),
708 path: root.join(relative_path),
709 size_bytes: 0,
710 })
711 .collect()
712 }
713
714 fn git(project: &Path, args: &[&str]) {
715 let status = fallow_engine::changed_files::clear_ambient_git_env(&mut Command::new("git"))
716 .args(args)
717 .current_dir(project)
718 .status()
719 .expect("git command should run");
720 assert!(status.success(), "git {args:?} failed");
721 }
722
723 fn setup_changed_boundary_project() -> tempfile::TempDir {
724 let project = tempfile::tempdir().expect("project");
725 std::fs::write(
726 project.path().join("package.json"),
727 r#"{"name":"changed-list-api","main":"src/app/index.ts"}"#,
728 )
729 .expect("write package");
730 std::fs::write(
731 project.path().join(".fallowrc.json"),
732 r#"{
733 "boundaries": {
734 "zones": [
735 { "name": "app", "patterns": ["src/app/**"] },
736 { "name": "shared", "patterns": ["src/shared/**"] }
737 ]
738 }
739 }"#,
740 )
741 .expect("write config");
742 std::fs::create_dir_all(project.path().join("src/app")).expect("create app");
743 std::fs::create_dir_all(project.path().join("src/shared")).expect("create shared");
744 std::fs::write(
745 project.path().join("src/app/index.ts"),
746 "export const app = 1;\n",
747 )
748 .expect("write app");
749 std::fs::write(
750 project.path().join("src/shared/index.ts"),
751 "export const shared = 1;\n",
752 )
753 .expect("write shared");
754
755 git(project.path(), &["init", "-q"]);
756 git(
757 project.path(),
758 &["config", "user.email", "test@example.com"],
759 );
760 git(project.path(), &["config", "user.name", "Test User"]);
761 git(project.path(), &["config", "commit.gpgsign", "false"]);
762 git(project.path(), &["add", "."]);
763 git(project.path(), &["commit", "-qm", "initial"]);
764 std::fs::write(
765 project.path().join("src/app/index.ts"),
766 "export const app = 2;\n",
767 )
768 .expect("modify app");
769 project
770 }
771
772 #[test]
773 fn project_info_default_sections_match_plain_list_contract() {
774 let project = tempfile::tempdir().expect("project");
775 std::fs::write(
776 project.path().join("package.json"),
777 r#"{"name":"project-info-api","main":"src/index.ts"}"#,
778 )
779 .expect("write package");
780 std::fs::create_dir_all(project.path().join("src")).expect("create src");
781 std::fs::write(
782 project.path().join("src/index.ts"),
783 "export const value = 1;\n",
784 )
785 .expect("write source");
786
787 let output = serialize_project_info_programmatic_json(
788 run_project_info(&ProjectInfoOptions {
789 analysis: AnalysisOptions {
790 root: Some(project.path().to_path_buf()),
791 no_cache: true,
792 ..AnalysisOptions::default()
793 },
794 ..ProjectInfoOptions::default()
795 })
796 .expect("project info should run"),
797 )
798 .expect("project info should serialize");
799
800 assert_eq!(output["file_count"], 1);
801 assert_eq!(output["files"][0], "src/index.ts");
802 assert_eq!(output["entry_point_count"], 1);
803 assert_eq!(output["workspace_count"], 0);
804 assert!(output.get("kind").is_none());
805 }
806
807 #[test]
808 fn project_info_surfaces_malformed_root_package_json() {
809 let project = tempfile::tempdir().expect("project");
810 std::fs::write(project.path().join("package.json"), "{").expect("write package");
811
812 let err = run_project_info(&ProjectInfoOptions {
813 analysis: AnalysisOptions {
814 root: Some(project.path().to_path_buf()),
815 no_cache: true,
816 ..AnalysisOptions::default()
817 },
818 ..ProjectInfoOptions::default()
819 })
820 .expect_err("malformed root package.json must fail project info");
821
822 assert_eq!(err.exit_code, 2);
823 assert_eq!(err.code.as_deref(), Some("FALLOW_CONFIG_LOAD_FAILED"));
824 assert!(
825 err.message.contains("package.json"),
826 "error should name the malformed root package.json"
827 );
828 }
829
830 #[test]
831 fn project_info_default_sections_include_undeclared_workspace_diagnostic() {
832 let project = tempfile::tempdir().expect("project");
833 std::fs::write(
834 project.path().join("package.json"),
835 r#"{"name":"project-info-api","workspaces":["packages/*"]}"#,
836 )
837 .expect("write package");
838 std::fs::create_dir_all(project.path().join("packages/app")).expect("workspace dir");
839 std::fs::write(
840 project.path().join("packages/app/package.json"),
841 r#"{"name":"app","main":"src/index.ts"}"#,
842 )
843 .expect("write workspace package");
844 std::fs::create_dir_all(project.path().join("tools/extra")).expect("extra package dir");
845 std::fs::write(
846 project.path().join("tools/extra/package.json"),
847 r#"{"name":"extra"}"#,
848 )
849 .expect("write extra package");
850
851 let output = serialize_project_info_programmatic_json(
852 run_project_info(&ProjectInfoOptions {
853 analysis: AnalysisOptions {
854 root: Some(project.path().to_path_buf()),
855 no_cache: true,
856 ..AnalysisOptions::default()
857 },
858 ..ProjectInfoOptions::default()
859 })
860 .expect("project info should run"),
861 )
862 .expect("project info should serialize");
863
864 let diagnostics = output["workspace_diagnostics"]
865 .as_array()
866 .expect("project info should include workspace_diagnostics");
867 assert!(
868 diagnostics.iter().any(|diagnostic| {
869 diagnostic["kind"].as_str() == Some("undeclared-workspace")
870 && diagnostic["path"].as_str() == Some("tools/extra")
873 }),
874 "project info must include undeclared workspace diagnostics from the reused session, got {diagnostics:#?}"
875 );
876 }
877
878 #[test]
883 fn project_info_reports_one_entry_per_directory_for_a_glob_in_two_manifests() {
884 let project = tempfile::tempdir().expect("project");
885 let root = project.path();
886 std::fs::create_dir_all(root.join("pkgs/aaa")).expect("first package-less dir");
887 std::fs::create_dir_all(root.join("pkgs/bbb")).expect("second package-less dir");
888 std::fs::create_dir_all(root.join("src")).expect("source dir");
889 std::fs::write(
890 root.join("package.json"),
891 r#"{"name":"two-manifest-root","private":true,"workspaces":["./pkgs/*"]}"#,
892 )
893 .expect("write root manifest");
894 std::fs::write(
895 root.join("pnpm-workspace.yaml"),
896 "packages:\n - \"pkgs/*\"\n",
897 )
898 .expect("write pnpm workspace manifest");
899 std::fs::write(root.join("src/index.ts"), "export const value = 1;\n")
900 .expect("write source");
901
902 let output = serialize_project_info_programmatic_json(
903 run_project_info(&ProjectInfoOptions {
904 analysis: AnalysisOptions {
905 root: Some(root.to_path_buf()),
906 no_cache: true,
907 ..AnalysisOptions::default()
908 },
909 ..ProjectInfoOptions::default()
910 })
911 .expect("project info should run"),
912 )
913 .expect("project info should serialize");
914
915 let reported: Vec<(&str, &str)> = output["workspace_diagnostics"]
916 .as_array()
917 .expect("project info should include workspace_diagnostics")
918 .iter()
919 .filter(|diagnostic| diagnostic["kind"] == "glob-matched-no-package-json")
920 .map(|diagnostic| {
921 (
922 diagnostic["pattern"].as_str().unwrap_or_default(),
923 diagnostic["path"].as_str().unwrap_or_default(),
924 )
925 })
926 .collect();
927
928 assert_eq!(
929 reported,
930 vec![("pkgs/*", "pkgs/aaa"), ("pkgs/*", "pkgs/bbb")],
931 "project_info agrees with the CLI envelopes: {}",
932 output["workspace_diagnostics"]
933 );
934 }
935
936 #[test]
937 fn list_runtimes_scope_files_and_boundary_counts_to_changed_since() {
938 let project = setup_changed_boundary_project();
939 let analysis = AnalysisOptions {
940 root: Some(project.path().to_path_buf()),
941 changed_since: Some("HEAD".to_string()),
942 no_cache: true,
943 ..AnalysisOptions::default()
944 };
945
946 let project_info = serialize_project_info_programmatic_json(
947 run_project_info(&ProjectInfoOptions {
948 analysis: analysis.clone(),
949 files: true,
950 boundaries: true,
951 ..ProjectInfoOptions::default()
952 })
953 .expect("project info should run"),
954 )
955 .expect("project info should serialize");
956 let files = project_info["files"].as_array().expect("files array");
957 assert_eq!(files, &[json!("src/app/index.ts")]);
958 assert_eq!(project_info["boundaries"]["zones"][0]["file_count"], 1);
959 assert_eq!(project_info["boundaries"]["zones"][1]["file_count"], 0);
960
961 let boundaries = serialize_list_boundaries_programmatic_json(
962 run_list_boundaries(&ListBoundariesOptions { analysis })
963 .expect("list boundaries should run"),
964 )
965 .expect("list boundaries should serialize");
966 assert_eq!(boundaries["boundaries"]["zones"][0]["file_count"], 1);
967 assert_eq!(boundaries["boundaries"]["zones"][1]["file_count"], 0);
968 }
969
970 #[test]
971 fn boundary_zone_counts_preserve_first_match_for_overlapping_zones() {
972 let root = Path::new("project");
973 let boundaries = ResolvedBoundaryConfig {
974 zones: vec![
975 resolved_zone("source", &["src/**"]),
976 resolved_zone("shared", &["src/shared/**"]),
977 ],
978 ..ResolvedBoundaryConfig::default()
979 };
980 let files = discovered_files(root, &["src/app.ts", "src/shared/index.ts"]);
981
982 let zones = build_boundary_zones(root, &boundaries, Some(&files));
983
984 assert_eq!(zones[0].name, "source");
985 assert_eq!(zones[0].file_count, 2);
986 assert_eq!(zones[1].name, "shared");
987 assert_eq!(zones[1].file_count, 0);
988 }
989
990 #[test]
991 fn boundary_zone_counts_ignore_unmatched_and_out_of_root_files() {
992 let root = Path::new("project");
993 let boundaries = ResolvedBoundaryConfig {
994 zones: vec![resolved_zone("matched", &["src/matched/**"])],
995 ..ResolvedBoundaryConfig::default()
996 };
997 let mut files = discovered_files(root, &["src/matched/index.ts", "src/unmatched/index.ts"]);
998 files.push(DiscoveredFile {
999 id: FileId(2),
1000 path: PathBuf::from("outside/index.ts"),
1001 size_bytes: 0,
1002 });
1003
1004 let zones = build_boundary_zones(root, &boundaries, Some(&files));
1005
1006 assert_eq!(zones[0].file_count, 1);
1007 }
1008
1009 #[test]
1010 fn boundary_zone_counts_preserve_duplicate_name_semantics() {
1011 let root = Path::new("project");
1012 let boundaries = ResolvedBoundaryConfig {
1013 zones: vec![
1014 resolved_zone("shared", &["src/first/**"]),
1015 resolved_zone("shared", &["src/second/**"]),
1016 ],
1017 ..ResolvedBoundaryConfig::default()
1018 };
1019 let files = discovered_files(root, &["src/first/index.ts", "src/second/index.ts"]);
1020
1021 let zones = build_boundary_zones(root, &boundaries, Some(&files));
1022
1023 assert_eq!(zones[0].patterns, ["src/first/**"]);
1024 assert_eq!(zones[1].patterns, ["src/second/**"]);
1025 assert_eq!(zones[0].file_count, 2);
1026 assert_eq!(zones[1].file_count, 2);
1027 }
1028
1029 #[test]
1030 fn boundary_zone_output_is_deterministic_and_keeps_config_order() {
1031 let root = Path::new("project");
1032 let boundaries = ResolvedBoundaryConfig {
1033 zones: vec![
1034 resolved_zone("zeta", &["src/zeta/**"]),
1035 resolved_zone("alpha", &["src/alpha/**"]),
1036 resolved_zone("middle", &["src/middle/**"]),
1037 ],
1038 ..ResolvedBoundaryConfig::default()
1039 };
1040 let files = discovered_files(
1041 root,
1042 &[
1043 "src/middle/two.ts",
1044 "src/zeta/one.ts",
1045 "src/alpha/one.ts",
1046 "src/middle/one.ts",
1047 ],
1048 );
1049
1050 let first = build_boundary_zones(root, &boundaries, Some(&files));
1051 let second = build_boundary_zones(root, &boundaries, Some(&files));
1052 let signature = |zones: &[ZoneInfo]| {
1053 zones
1054 .iter()
1055 .map(|zone| (zone.name.clone(), zone.file_count))
1056 .collect::<Vec<_>>()
1057 };
1058
1059 assert_eq!(signature(&first), signature(&second));
1060 assert_eq!(
1061 signature(&first),
1062 vec![
1063 ("zeta".to_string(), 1),
1064 ("alpha".to_string(), 1),
1065 ("middle".to_string(), 2),
1066 ]
1067 );
1068 }
1069
1070 #[test]
1071 fn boundary_json_empty_includes_logical_groups_key() {
1072 let value = boundary_data_to_json(&empty_boundary_data());
1073
1074 assert_eq!(value["configured"], false);
1075 assert_eq!(value["zone_count"], 0);
1076 assert_eq!(value["rule_count"], 0);
1077 assert_eq!(value["logical_group_count"], 0);
1078 assert_eq!(value["logical_groups"], json!([]));
1079 }
1080
1081 #[test]
1082 fn boundary_json_logical_group_carries_all_fields() {
1083 let data = BoundaryData {
1084 zones: vec![ZoneInfo {
1085 name: "features/auth".to_string(),
1086 patterns: vec!["src/features/auth/**".to_string()],
1087 file_count: 3,
1088 public_files: vec![],
1089 }],
1090 rules: vec![],
1091 logical_groups: vec![LogicalGroupInfo {
1092 name: "features".to_string(),
1093 children: vec!["features/auth".to_string()],
1094 auto_discover: vec!["./src/features/".to_string()],
1095 authored_rule: Some(AuthoredRule {
1096 allow: vec!["shared".to_string()],
1097 allow_type_only: vec!["types".to_string()],
1098 }),
1099 fallback_zone: None,
1100 source_zone_index: 1,
1101 status: LogicalGroupStatus::Ok,
1102 file_count: 3,
1103 child_file_count: 3,
1104 fallback_file_count: 0,
1105 merged_from: None,
1106 original_zone_root: None,
1107 child_source_indices: vec![],
1108 }],
1109 is_empty: false,
1110 };
1111
1112 let value = boundary_data_to_json(&data);
1113 let group = &value["logical_groups"][0];
1114
1115 assert_eq!(value["logical_group_count"], 1);
1116 assert_eq!(group["name"], "features");
1117 assert_eq!(group["children"][0], "features/auth");
1118 assert_eq!(group["auto_discover"][0], "./src/features/");
1119 assert_eq!(group["status"], "ok");
1120 assert_eq!(group["source_zone_index"], 1);
1121 assert_eq!(group["file_count"], 3);
1122 assert_eq!(group["authored_rule"]["allow"][0], "shared");
1123 assert_eq!(group["authored_rule"]["allow_type_only"][0], "types");
1124 assert!(group.get("fallback_zone").is_none());
1125 assert!(group.get("merged_from").is_none());
1126 assert!(group.get("original_zone_root").is_none());
1127 assert!(group.get("child_source_indices").is_none());
1128 }
1129
1130 #[test]
1131 fn boundary_json_logical_group_optional_fields_round_trip() {
1132 let data = BoundaryData {
1133 zones: vec![],
1134 rules: vec![],
1135 logical_groups: vec![LogicalGroupInfo {
1136 name: "features".to_string(),
1137 children: vec!["features/auth".to_string(), "features/billing".to_string()],
1138 auto_discover: vec!["src/features".to_string(), "src/modules".to_string()],
1139 authored_rule: None,
1140 fallback_zone: Some("features".to_string()),
1141 source_zone_index: 0,
1142 status: LogicalGroupStatus::Empty,
1143 file_count: 2,
1144 child_file_count: 0,
1145 fallback_file_count: 2,
1146 merged_from: Some(vec![0, 3]),
1147 original_zone_root: Some("packages/app/".to_string()),
1148 child_source_indices: vec![0, 1],
1149 }],
1150 is_empty: false,
1151 };
1152
1153 let group = &boundary_data_to_json(&data)["logical_groups"][0];
1154
1155 assert_eq!(group["status"], "empty");
1156 assert_eq!(group["fallback_zone"], "features");
1157 assert_eq!(group["merged_from"][1], 3);
1158 assert_eq!(group["original_zone_root"], "packages/app/");
1159 assert_eq!(group["child_source_indices"][1], 1);
1160 }
1161}