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