1use std::path::{Path, PathBuf};
4
5use fallow_config::{AuthoredRule, LogicalGroup, LogicalGroupStatus, ResolvedBoundaryConfig};
6use fallow_output::{
7 ListEntryPointOutput, RootEnvelopeMode, WorkspaceInfo as WorkspaceOutputInfo, WorkspacesOutput,
8};
9use fallow_types::discover::{DiscoveredFile, EntryPoint};
10use rustc_hash::FxHashMap;
11
12use crate::{
13 AnalysisOptions, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
14 BoundariesListing, ListJsonEnvelope, ListJsonOutputInput, ProgrammaticError,
15 analysis_context::changed_files_for_run, resolve_programmatic_analysis_context,
16 serialize_list_json_output,
17};
18
19type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
20
21#[derive(Debug, Clone, Default)]
23pub struct ProjectInfoOptions {
24 pub analysis: AnalysisOptions,
26 pub entry_points: bool,
28 pub files: bool,
30 pub plugins: bool,
32 pub boundaries: bool,
34}
35
36#[derive(Debug, Clone, Default)]
38pub struct ListBoundariesOptions {
39 pub analysis: AnalysisOptions,
41}
42
43#[derive(Debug, Clone)]
45pub struct ProjectInfoProgrammaticOutput {
46 pub plugins: Option<Vec<String>>,
48 pub files: Option<Vec<String>>,
50 pub entry_points: Option<Vec<ListEntryPointOutput>>,
52 pub boundaries: Option<BoundariesListing>,
54 pub workspaces: Option<WorkspacesOutput<fallow_config::WorkspaceDiagnostic>>,
56 pub envelope: ListJsonEnvelope,
58 pub envelope_mode: RootEnvelopeMode,
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 workspaces: output.workspaces,
77 },
78 output.envelope_mode,
79 output.envelope,
80 )
81 .map_err(|err| {
82 ProgrammaticError::new(format!("failed to serialize project info output: {err}"), 2)
83 .with_code("FALLOW_PROJECT_INFO_SERIALIZE_FAILED")
84 .with_context("project_info")
85 })
86}
87
88#[derive(Debug, Clone)]
90pub struct ListBoundariesProgrammaticOutput {
91 pub boundaries: BoundariesListing,
93 pub envelope_mode: RootEnvelopeMode,
95}
96
97pub fn serialize_list_boundaries_programmatic_json(
103 output: ListBoundariesProgrammaticOutput,
104) -> ProgrammaticResult<serde_json::Value> {
105 serialize_list_json_output(
106 ListJsonOutputInput::<BoundariesListing, serde_json::Value> {
107 plugins: None,
108 files: None,
109 entry_points: None,
110 boundaries: Some(output.boundaries),
111 workspaces: None,
112 },
113 output.envelope_mode,
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}
149
150#[derive(Debug, Clone)]
152pub struct RuleInfo {
153 pub from: String,
155 pub allow: Vec<String>,
157}
158
159#[derive(Debug, Clone)]
161pub struct LogicalGroupInfo {
162 pub name: String,
164 pub children: Vec<String>,
166 pub auto_discover: Vec<String>,
168 pub authored_rule: Option<AuthoredRule>,
170 pub fallback_zone: Option<String>,
172 pub source_zone_index: usize,
174 pub status: LogicalGroupStatus,
176 pub file_count: usize,
178 pub child_file_count: usize,
180 pub fallback_file_count: usize,
182 pub merged_from: Option<Vec<usize>>,
184 pub original_zone_root: Option<String>,
186 pub child_source_indices: Vec<usize>,
188}
189
190pub fn run_list_boundaries(
197 options: &ListBoundariesOptions,
198) -> ProgrammaticResult<ListBoundariesProgrammaticOutput> {
199 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
200 resolved.install(|| {
201 let project_config = load_list_project_config(&resolved)?;
202 let session = fallow_engine::session::AnalysisSession::from_config(project_config);
203 let changed_files = changed_files_for_run(&resolved)?;
204 let discovered = scoped_discovered_files(session.files(), changed_files.as_ref());
205 let data = compute_boundary_data(session.config(), Some(&discovered));
206
207 Ok(ListBoundariesProgrammaticOutput {
208 boundaries: boundary_data_to_output(&data),
209 envelope_mode: RootEnvelopeMode::Tagged,
210 })
211 })
212}
213
214pub fn run_project_info(
221 options: &ProjectInfoOptions,
222) -> ProgrammaticResult<ProjectInfoProgrammaticOutput> {
223 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
224 resolved.install(|| {
225 let project_config = load_list_project_config(&resolved)?;
226 let session = fallow_engine::session::AnalysisSession::from_config(project_config);
227 let config = session.config();
228 let workspaces = session.workspaces();
229 let show_all = project_info_should_show_all(options);
230 let changed_files = changed_files_for_run(&resolved)?;
231 let discovered =
232 project_info_discovered_files(options, show_all, &session, changed_files.as_ref());
233 let discovered_ref = discovered.as_deref();
234
235 let plugin_result = collect_plugin_result(
236 resolved.root(),
237 config,
238 options,
239 show_all,
240 discovered_ref,
241 workspaces,
242 )?;
243 let entry_points = collect_entry_points(
244 config,
245 options,
246 show_all,
247 discovered_ref,
248 workspaces,
249 plugin_result.as_ref(),
250 );
251 let boundaries = options
252 .boundaries
253 .then(|| boundary_data_to_output(&compute_boundary_data(config, discovered_ref)));
254 let workspaces = if show_all {
255 Some(collect_workspace_output(
256 resolved.root(),
257 workspaces,
258 &session.current_workspace_diagnostics(),
259 ))
260 } else {
261 None
262 };
263 let envelope = if boundaries.is_some() {
264 ListJsonEnvelope::Boundaries
265 } else {
266 ListJsonEnvelope::Plain
267 };
268
269 Ok(ProjectInfoProgrammaticOutput {
270 plugins: collect_plugins(options, show_all, plugin_result.as_ref()),
271 files: collect_files(options, show_all, discovered_ref, resolved.root()),
272 entry_points: entry_points
273 .map(|entries| entry_points_to_output(&entries, resolved.root())),
274 boundaries,
275 workspaces,
276 envelope,
277 envelope_mode: RootEnvelopeMode::Tagged,
278 })
279 })
280}
281
282fn project_info_discovered_files(
283 options: &ProjectInfoOptions,
284 show_all: bool,
285 session: &fallow_engine::session::AnalysisSession,
286 changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
287) -> Option<Vec<DiscoveredFile>> {
288 let needs_discovery =
289 options.files || options.entry_points || options.boundaries || options.plugins || show_all;
290 needs_discovery.then(|| scoped_discovered_files(session.files(), changed_files))
291}
292
293fn scoped_discovered_files(
294 files: &[DiscoveredFile],
295 changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
296) -> Vec<DiscoveredFile> {
297 let Some(changed_files) = changed_files else {
298 return files.to_vec();
299 };
300 files
301 .iter()
302 .filter(|file| changed_files.contains(&file.path))
303 .cloned()
304 .collect()
305}
306
307fn load_list_project_config(
308 resolved: &crate::ProgrammaticAnalysisContext,
309) -> ProgrammaticResult<fallow_engine::project_config::ProjectConfig> {
310 fallow_engine::project_config::config_for_project_analysis(
311 resolved.root(),
312 resolved.config_path().as_deref(),
313 fallow_engine::project_config::ProjectConfigOptions {
314 output: fallow_types::output_format::OutputFormat::Json,
315 no_cache: resolved.no_cache(),
316 threads: resolved.threads(),
317 production_override: resolved.production_override(),
318 quiet: true,
319 analysis: fallow_config::ProductionAnalysis::DeadCode,
320 allow_remote_extends: resolved.allow_remote_extends(),
321 },
322 )
323 .map_err(|err| {
324 ProgrammaticError::new(format!("failed to load config: {err}"), 2)
325 .with_code("FALLOW_CONFIG_LOAD_FAILED")
326 .with_context("analysis.configPath")
327 })
328}
329
330const fn project_info_should_show_all(options: &ProjectInfoOptions) -> bool {
331 !options.entry_points && !options.files && !options.plugins && !options.boundaries
332}
333
334fn collect_plugins(
335 options: &ProjectInfoOptions,
336 show_all: bool,
337 plugin_result: Option<&fallow_engine::plugins::AggregatedPluginResult>,
338) -> Option<Vec<String>> {
339 if options.plugins || show_all {
340 plugin_result.map(|plugin_result| plugin_result.active_plugins().to_vec())
341 } else {
342 None
343 }
344}
345
346fn collect_files(
347 options: &ProjectInfoOptions,
348 show_all: bool,
349 discovered: Option<&[DiscoveredFile]>,
350 root: &Path,
351) -> Option<Vec<String>> {
352 if options.files || show_all {
353 discovered.map(|files| {
354 files
355 .iter()
356 .map(|file| format_display_path(&file.path, root))
357 .collect()
358 })
359 } else {
360 None
361 }
362}
363
364fn collect_plugin_result(
365 root: &Path,
366 config: &fallow_config::ResolvedConfig,
367 options: &ProjectInfoOptions,
368 show_all: bool,
369 discovered: Option<&[DiscoveredFile]>,
370 workspaces: &[fallow_config::WorkspaceInfo],
371) -> ProgrammaticResult<Option<fallow_engine::plugins::AggregatedPluginResult>> {
372 if !(options.plugins || options.entry_points || show_all) {
373 return Ok(None);
374 }
375 let Some(files) = discovered else {
376 return Ok(None);
377 };
378 fallow_engine::list_inventory::collect_active_plugins(root, config, files, workspaces)
379 .map(Some)
380 .map_err(|err| match err {
381 fallow_engine::list_inventory::ListInventoryError::PluginRegex(errors) => {
382 ProgrammaticError::new(
383 fallow_engine::plugins::registry::format_plugin_regex_errors(&errors),
384 2,
385 )
386 .with_code("FALLOW_PLUGIN_REGEX_FAILED")
387 .with_context("project_info.plugins")
388 }
389 })
390}
391
392fn collect_entry_points(
393 config: &fallow_config::ResolvedConfig,
394 options: &ProjectInfoOptions,
395 show_all: bool,
396 discovered: Option<&[DiscoveredFile]>,
397 workspaces: &[fallow_config::WorkspaceInfo],
398 plugin_result: Option<&fallow_engine::plugins::AggregatedPluginResult>,
399) -> Option<Vec<EntryPoint>> {
400 if !(options.entry_points || show_all) {
401 return None;
402 }
403 let discovered = discovered?;
404 Some(fallow_engine::list_inventory::collect_entry_points(
405 config,
406 discovered,
407 workspaces,
408 plugin_result,
409 ))
410}
411
412fn entry_points_to_output(entries: &[EntryPoint], root: &Path) -> Vec<ListEntryPointOutput> {
413 entries
414 .iter()
415 .map(|entry| ListEntryPointOutput {
416 path: format_display_path(&entry.path, root),
417 source: entry.source.to_string(),
418 })
419 .collect()
420}
421
422fn collect_workspace_output(
423 root: &Path,
424 workspaces: &[fallow_config::WorkspaceInfo],
425 diagnostics: &[fallow_config::WorkspaceDiagnostic],
426) -> WorkspacesOutput<fallow_config::WorkspaceDiagnostic> {
427 let workspaces = workspaces
428 .iter()
429 .map(|workspace| {
430 let relative = workspace.root.strip_prefix(root).unwrap_or(&workspace.root);
431 WorkspaceOutputInfo {
432 name: workspace.name.clone(),
433 path: relative.display().to_string().replace('\\', "/"),
434 is_internal_dependency: workspace.is_internal_dependency,
435 }
436 })
437 .collect::<Vec<_>>();
438 WorkspacesOutput {
439 workspace_count: workspaces.len(),
440 workspaces,
441 workspace_diagnostics: diagnostics.to_vec(),
442 }
443}
444
445fn format_display_path(path: &Path, root: &Path) -> String {
446 path.strip_prefix(root)
447 .unwrap_or(path)
448 .display()
449 .to_string()
450 .replace('\\', "/")
451}
452
453#[must_use]
455pub fn compute_boundary_data(
456 config: &fallow_config::ResolvedConfig,
457 discovered: Option<&[DiscoveredFile]>,
458) -> BoundaryData {
459 let boundaries = &config.boundaries;
460
461 if boundaries.is_empty() {
462 return BoundaryData {
463 zones: vec![],
464 rules: vec![],
465 logical_groups: vec![],
466 is_empty: true,
467 };
468 }
469
470 let zones = build_boundary_zones(config, discovered);
471 let rules = build_boundary_rules(boundaries);
472 let logical_groups = build_logical_groups(boundaries, &zones);
473
474 BoundaryData {
475 zones,
476 rules,
477 logical_groups,
478 is_empty: false,
479 }
480}
481
482fn build_boundary_zones(
483 config: &fallow_config::ResolvedConfig,
484 discovered: Option<&[DiscoveredFile]>,
485) -> Vec<ZoneInfo> {
486 config
487 .boundaries
488 .zones
489 .iter()
490 .map(|zone| ZoneInfo {
491 name: zone.name.clone(),
492 patterns: zone.matchers.iter().map(|m| m.glob().to_string()).collect(),
493 file_count: count_boundary_zone_files(config, discovered, &zone.name),
494 })
495 .collect()
496}
497
498fn count_boundary_zone_files(
499 config: &fallow_config::ResolvedConfig,
500 discovered: Option<&[DiscoveredFile]>,
501 zone_name: &str,
502) -> usize {
503 discovered.map_or(0, |files| {
504 files
505 .iter()
506 .filter(|file| {
507 let rel = file
508 .path
509 .strip_prefix(&config.root)
510 .ok()
511 .map(|path| path.to_string_lossy().replace('\\', "/"));
512 rel.is_some_and(|path| config.boundaries.classify_zone(&path) == Some(zone_name))
513 })
514 .count()
515 })
516}
517
518fn build_boundary_rules(boundaries: &ResolvedBoundaryConfig) -> Vec<RuleInfo> {
519 boundaries
520 .rules
521 .iter()
522 .map(|rule| RuleInfo {
523 from: rule.from_zone.clone(),
524 allow: rule.allowed_zones.clone(),
525 })
526 .collect()
527}
528
529fn build_logical_groups(
530 boundaries: &ResolvedBoundaryConfig,
531 zones: &[ZoneInfo],
532) -> Vec<LogicalGroupInfo> {
533 let zone_count_by_name: FxHashMap<&str, usize> = zones
534 .iter()
535 .map(|zone| (zone.name.as_str(), zone.file_count))
536 .collect();
537
538 boundaries
539 .logical_groups
540 .iter()
541 .map(|group| logical_group_info(group, &zone_count_by_name))
542 .collect()
543}
544
545fn logical_group_info(
546 group: &LogicalGroup,
547 zone_count_by_name: &FxHashMap<&str, usize>,
548) -> LogicalGroupInfo {
549 let child_file_count: usize = group
550 .children
551 .iter()
552 .filter_map(|child| zone_count_by_name.get(child.as_str()).copied())
553 .sum();
554 let fallback_file_count = group
555 .fallback_zone
556 .as_deref()
557 .and_then(|fallback| zone_count_by_name.get(fallback).copied())
558 .unwrap_or(0);
559
560 LogicalGroupInfo {
561 name: group.name.clone(),
562 children: group.children.clone(),
563 auto_discover: group.auto_discover.clone(),
564 authored_rule: group.authored_rule.clone(),
565 fallback_zone: group.fallback_zone.clone(),
566 source_zone_index: group.source_zone_index,
567 status: group.status,
568 file_count: child_file_count + fallback_file_count,
569 child_file_count,
570 fallback_file_count,
571 merged_from: group.merged_from.clone(),
572 original_zone_root: group.original_zone_root.clone(),
573 child_source_indices: group.child_source_indices.clone(),
574 }
575}
576
577#[must_use]
579pub fn boundary_data_to_output(data: &BoundaryData) -> BoundariesListing {
580 if data.is_empty {
581 return BoundariesListing {
582 configured: false,
583 zone_count: 0,
584 zones: Vec::new(),
585 rule_count: 0,
586 rules: Vec::new(),
587 logical_group_count: 0,
588 logical_groups: Vec::new(),
589 };
590 }
591
592 BoundariesListing {
593 configured: true,
594 zone_count: data.zones.len(),
595 zones: data
596 .zones
597 .iter()
598 .map(|zone| BoundariesListZone {
599 name: zone.name.clone(),
600 patterns: zone.patterns.clone(),
601 file_count: zone.file_count,
602 })
603 .collect(),
604 rule_count: data.rules.len(),
605 rules: data
606 .rules
607 .iter()
608 .map(|rule| BoundariesListRule {
609 from: rule.from.clone(),
610 allow: rule.allow.clone(),
611 })
612 .collect(),
613 logical_group_count: data.logical_groups.len(),
614 logical_groups: data
615 .logical_groups
616 .iter()
617 .map(logical_group_info_to_output)
618 .collect(),
619 }
620}
621
622fn logical_group_info_to_output(group: &LogicalGroupInfo) -> BoundariesListLogicalGroup {
623 BoundariesListLogicalGroup {
624 name: group.name.clone(),
625 children: group.children.clone(),
626 auto_discover: group.auto_discover.clone(),
627 status: group.status,
628 source_zone_index: group.source_zone_index,
629 file_count: group.file_count,
630 authored_rule: group.authored_rule.clone(),
631 fallback_zone: group.fallback_zone.clone(),
632 merged_from: group.merged_from.clone(),
633 original_zone_root: group.original_zone_root.clone(),
634 child_source_indices: group.child_source_indices.clone(),
635 }
636}
637
638#[cfg(test)]
639mod tests {
640 use std::process::Command;
641
642 use serde_json::json;
643
644 use super::*;
645
646 fn empty_boundary_data() -> BoundaryData {
647 BoundaryData {
648 zones: vec![],
649 rules: vec![],
650 logical_groups: vec![],
651 is_empty: true,
652 }
653 }
654
655 fn boundary_data_to_json(data: &BoundaryData) -> serde_json::Value {
656 serde_json::to_value(boundary_data_to_output(data))
657 .expect("boundary list output should serialize")
658 }
659
660 fn git(project: &Path, args: &[&str]) {
661 let status = Command::new("git")
662 .args(args)
663 .current_dir(project)
664 .status()
665 .expect("git command should run");
666 assert!(status.success(), "git {args:?} failed");
667 }
668
669 fn setup_changed_boundary_project() -> tempfile::TempDir {
670 let project = tempfile::tempdir().expect("project");
671 std::fs::write(
672 project.path().join("package.json"),
673 r#"{"name":"changed-list-api","main":"src/app/index.ts"}"#,
674 )
675 .expect("write package");
676 std::fs::write(
677 project.path().join(".fallowrc.json"),
678 r#"{
679 "boundaries": {
680 "zones": [
681 { "name": "app", "patterns": ["src/app/**"] },
682 { "name": "shared", "patterns": ["src/shared/**"] }
683 ]
684 }
685 }"#,
686 )
687 .expect("write config");
688 std::fs::create_dir_all(project.path().join("src/app")).expect("create app");
689 std::fs::create_dir_all(project.path().join("src/shared")).expect("create shared");
690 std::fs::write(
691 project.path().join("src/app/index.ts"),
692 "export const app = 1;\n",
693 )
694 .expect("write app");
695 std::fs::write(
696 project.path().join("src/shared/index.ts"),
697 "export const shared = 1;\n",
698 )
699 .expect("write shared");
700
701 git(project.path(), &["init", "-q"]);
702 git(
703 project.path(),
704 &["config", "user.email", "test@example.com"],
705 );
706 git(project.path(), &["config", "user.name", "Test User"]);
707 git(project.path(), &["config", "commit.gpgsign", "false"]);
708 git(project.path(), &["add", "."]);
709 git(project.path(), &["commit", "-qm", "initial"]);
710 std::fs::write(
711 project.path().join("src/app/index.ts"),
712 "export const app = 2;\n",
713 )
714 .expect("modify app");
715 project
716 }
717
718 #[test]
719 fn project_info_default_sections_match_plain_list_contract() {
720 let project = tempfile::tempdir().expect("project");
721 std::fs::write(
722 project.path().join("package.json"),
723 r#"{"name":"project-info-api","main":"src/index.ts"}"#,
724 )
725 .expect("write package");
726 std::fs::create_dir_all(project.path().join("src")).expect("create src");
727 std::fs::write(
728 project.path().join("src/index.ts"),
729 "export const value = 1;\n",
730 )
731 .expect("write source");
732
733 let output = serialize_project_info_programmatic_json(
734 run_project_info(&ProjectInfoOptions {
735 analysis: AnalysisOptions {
736 root: Some(project.path().to_path_buf()),
737 no_cache: true,
738 ..AnalysisOptions::default()
739 },
740 ..ProjectInfoOptions::default()
741 })
742 .expect("project info should run"),
743 )
744 .expect("project info should serialize");
745
746 assert_eq!(output["file_count"], 1);
747 assert_eq!(output["files"][0], "src/index.ts");
748 assert_eq!(output["entry_point_count"], 1);
749 assert_eq!(output["workspace_count"], 0);
750 assert!(output.get("kind").is_none());
751 }
752
753 #[test]
754 fn project_info_surfaces_malformed_root_package_json() {
755 let project = tempfile::tempdir().expect("project");
756 std::fs::write(project.path().join("package.json"), "{").expect("write package");
757
758 let err = run_project_info(&ProjectInfoOptions {
759 analysis: AnalysisOptions {
760 root: Some(project.path().to_path_buf()),
761 no_cache: true,
762 ..AnalysisOptions::default()
763 },
764 ..ProjectInfoOptions::default()
765 })
766 .expect_err("malformed root package.json must fail project info");
767
768 assert_eq!(err.exit_code, 2);
769 assert_eq!(err.code.as_deref(), Some("FALLOW_CONFIG_LOAD_FAILED"));
770 assert!(
771 err.message.contains("package.json"),
772 "error should name the malformed root package.json"
773 );
774 }
775
776 #[test]
777 fn project_info_default_sections_include_undeclared_workspace_diagnostic() {
778 let project = tempfile::tempdir().expect("project");
779 std::fs::write(
780 project.path().join("package.json"),
781 r#"{"name":"project-info-api","workspaces":["packages/*"]}"#,
782 )
783 .expect("write package");
784 std::fs::create_dir_all(project.path().join("packages/app")).expect("workspace dir");
785 std::fs::write(
786 project.path().join("packages/app/package.json"),
787 r#"{"name":"app","main":"src/index.ts"}"#,
788 )
789 .expect("write workspace package");
790 std::fs::create_dir_all(project.path().join("tools/extra")).expect("extra package dir");
791 std::fs::write(
792 project.path().join("tools/extra/package.json"),
793 r#"{"name":"extra"}"#,
794 )
795 .expect("write extra package");
796
797 let output = serialize_project_info_programmatic_json(
798 run_project_info(&ProjectInfoOptions {
799 analysis: AnalysisOptions {
800 root: Some(project.path().to_path_buf()),
801 no_cache: true,
802 ..AnalysisOptions::default()
803 },
804 ..ProjectInfoOptions::default()
805 })
806 .expect("project info should run"),
807 )
808 .expect("project info should serialize");
809
810 let diagnostics = output["workspace_diagnostics"]
811 .as_array()
812 .expect("project info should include workspace_diagnostics");
813 assert!(
814 diagnostics.iter().any(|diagnostic| {
815 diagnostic["kind"].as_str() == Some("undeclared-workspace")
816 && diagnostic["path"]
817 .as_str()
818 .is_some_and(|path| path.replace('\\', "/").ends_with("/tools/extra"))
819 }),
820 "project info must include undeclared workspace diagnostics from the reused session, got {diagnostics:#?}"
821 );
822 }
823
824 #[test]
825 fn list_runtimes_scope_files_and_boundary_counts_to_changed_since() {
826 let project = setup_changed_boundary_project();
827 let analysis = AnalysisOptions {
828 root: Some(project.path().to_path_buf()),
829 changed_since: Some("HEAD".to_string()),
830 no_cache: true,
831 ..AnalysisOptions::default()
832 };
833
834 let project_info = serialize_project_info_programmatic_json(
835 run_project_info(&ProjectInfoOptions {
836 analysis: analysis.clone(),
837 files: true,
838 boundaries: true,
839 ..ProjectInfoOptions::default()
840 })
841 .expect("project info should run"),
842 )
843 .expect("project info should serialize");
844 let files = project_info["files"].as_array().expect("files array");
845 assert_eq!(files, &[json!("src/app/index.ts")]);
846 assert_eq!(project_info["boundaries"]["zones"][0]["file_count"], 1);
847 assert_eq!(project_info["boundaries"]["zones"][1]["file_count"], 0);
848
849 let boundaries = serialize_list_boundaries_programmatic_json(
850 run_list_boundaries(&ListBoundariesOptions { analysis })
851 .expect("list boundaries should run"),
852 )
853 .expect("list boundaries should serialize");
854 assert_eq!(boundaries["boundaries"]["zones"][0]["file_count"], 1);
855 assert_eq!(boundaries["boundaries"]["zones"][1]["file_count"], 0);
856 }
857
858 #[test]
859 fn boundary_json_empty_includes_logical_groups_key() {
860 let value = boundary_data_to_json(&empty_boundary_data());
861
862 assert_eq!(value["configured"], false);
863 assert_eq!(value["zone_count"], 0);
864 assert_eq!(value["rule_count"], 0);
865 assert_eq!(value["logical_group_count"], 0);
866 assert_eq!(value["logical_groups"], json!([]));
867 }
868
869 #[test]
870 fn boundary_json_logical_group_carries_all_fields() {
871 let data = BoundaryData {
872 zones: vec![ZoneInfo {
873 name: "features/auth".to_string(),
874 patterns: vec!["src/features/auth/**".to_string()],
875 file_count: 3,
876 }],
877 rules: vec![],
878 logical_groups: vec![LogicalGroupInfo {
879 name: "features".to_string(),
880 children: vec!["features/auth".to_string()],
881 auto_discover: vec!["./src/features/".to_string()],
882 authored_rule: Some(AuthoredRule {
883 allow: vec!["shared".to_string()],
884 allow_type_only: vec!["types".to_string()],
885 }),
886 fallback_zone: None,
887 source_zone_index: 1,
888 status: LogicalGroupStatus::Ok,
889 file_count: 3,
890 child_file_count: 3,
891 fallback_file_count: 0,
892 merged_from: None,
893 original_zone_root: None,
894 child_source_indices: vec![],
895 }],
896 is_empty: false,
897 };
898
899 let value = boundary_data_to_json(&data);
900 let group = &value["logical_groups"][0];
901
902 assert_eq!(value["logical_group_count"], 1);
903 assert_eq!(group["name"], "features");
904 assert_eq!(group["children"][0], "features/auth");
905 assert_eq!(group["auto_discover"][0], "./src/features/");
906 assert_eq!(group["status"], "ok");
907 assert_eq!(group["source_zone_index"], 1);
908 assert_eq!(group["file_count"], 3);
909 assert_eq!(group["authored_rule"]["allow"][0], "shared");
910 assert_eq!(group["authored_rule"]["allow_type_only"][0], "types");
911 assert!(group.get("fallback_zone").is_none());
912 assert!(group.get("merged_from").is_none());
913 assert!(group.get("original_zone_root").is_none());
914 assert!(group.get("child_source_indices").is_none());
915 }
916
917 #[test]
918 fn boundary_json_logical_group_optional_fields_round_trip() {
919 let data = BoundaryData {
920 zones: vec![],
921 rules: vec![],
922 logical_groups: vec![LogicalGroupInfo {
923 name: "features".to_string(),
924 children: vec!["features/auth".to_string(), "features/billing".to_string()],
925 auto_discover: vec!["src/features".to_string(), "src/modules".to_string()],
926 authored_rule: None,
927 fallback_zone: Some("features".to_string()),
928 source_zone_index: 0,
929 status: LogicalGroupStatus::Empty,
930 file_count: 2,
931 child_file_count: 0,
932 fallback_file_count: 2,
933 merged_from: Some(vec![0, 3]),
934 original_zone_root: Some("packages/app/".to_string()),
935 child_source_indices: vec![0, 1],
936 }],
937 is_empty: false,
938 };
939
940 let group = &boundary_data_to_json(&data)["logical_groups"][0];
941
942 assert_eq!(group["status"], "empty");
943 assert_eq!(group["fallback_zone"], "features");
944 assert_eq!(group["merged_from"][1], 3);
945 assert_eq!(group["original_zone_root"], "packages/app/");
946 assert_eq!(group["child_source_indices"][1], 1);
947 }
948}