1use std::path::{Path, PathBuf};
4
5use fallow_config::{ResolvedConfig, WorkspaceDiagnostic, WorkspaceInfo};
6use fallow_engine::resolved_run::{ResolvedRun, resolve_run};
7use fallow_output::{
8 DOCTOR_SCHEMA_VERSION, DoctorCheck, DoctorCheckCategory, DoctorCheckId, DoctorCheckStatus,
9 DoctorOutput, DoctorRemediation, DoctorStatus, DoctorSummary,
10};
11use fallow_types::envelope::{SchemaVersion, ToolVersion};
12use fallow_types::sourced::{Given, Origin};
13
14const ROOT_LINK_REFUSED: &str = "Project root passes through a link that resolves outside the checkout or the project. Pass the resolved absolute path with --root, or cd -P to it.";
15
16pub struct DoctorOptions<'a> {
18 pub root: &'a Path,
20 pub config_path: Option<&'a Path>,
22 pub root_is_current_dir: bool,
26}
27
28#[must_use]
31pub fn run_doctor(options: &DoctorOptions<'_>) -> DoctorOutput {
32 run_doctor_with_discovery(options, &crate::type_aware::discover_companion)
33}
34
35#[must_use]
43pub fn run_doctor_with_cache_dir(
44 options: &DoctorOptions<'_>,
45 cache_dir: Option<&Path>,
46) -> DoctorOutput {
47 run_doctor_with_cache_dir_and_discovery(
48 options,
49 cache_dir,
50 &crate::type_aware::discover_companion,
51 )
52}
53
54fn run_doctor_with_discovery<F>(options: &DoctorOptions<'_>, discover_companion: &F) -> DoctorOutput
55where
56 F: Fn(&Path) -> Result<(), String>,
57{
58 run_doctor_with_cache_dir_and_discovery(options, None, discover_companion)
59}
60
61fn run_doctor_with_cache_dir_and_discovery<F>(
62 options: &DoctorOptions<'_>,
63 cache_dir: Option<&Path>,
64 discover_companion: &F,
65) -> DoctorOutput
66where
67 F: Fn(&Path) -> Result<(), String>,
68{
69 let mut checks = Vec::with_capacity(9);
70 let validated = if options.root_is_current_dir {
71 fallow_engine::validate::validate_current_dir_root(options.root)
72 } else {
73 fallow_engine::validate::validate_root(options.root)
74 };
75 let root = match validated {
76 Ok(root) => {
77 checks.push(check(
78 DoctorCheckId::Root,
79 DoctorCheckCategory::Project,
80 DoctorCheckStatus::Pass,
81 true,
82 "Project root is an accessible directory.",
83 None,
84 ));
85 root
86 }
87 Err(_) => {
88 let message = if options.root.is_dir() {
91 ROOT_LINK_REFUSED
92 } else {
93 "Project root is not accessible. Set --root to an existing, readable directory."
94 };
95 checks.push(check(
96 DoctorCheckId::Root,
97 DoctorCheckCategory::Project,
98 DoctorCheckStatus::Fail,
99 true,
100 message,
101 None,
102 ));
103 push_prerequisite_skips(&mut checks, "Project root readiness failed.");
104 return build_output(checks);
105 }
106 };
107
108 match resolve_doctor_run(&root, options.config_path, cache_dir) {
109 Ok(run) => {
110 let project = ReadyProject::of(&run);
111 let cache_repair = || {
112 if cache_dir.is_some_and(|path| !path.as_os_str().is_empty()) {
113 return Err(
114 "Set FALLOW_CACHE_DIR to the inspected cache directory and run fallow dead-code --quiet with the same --config value if one was selected.",
115 );
116 }
117 let explicit = options.config_path.and(project.path.as_deref());
118 remediation_with_config("fallow dead-code --quiet", &root, explicit)
119 .ok_or("Run fallow dead-code --quiet with the same --config value.")
120 };
121 push_ready_project_checks(
122 &mut checks,
123 &root,
124 &project,
125 &run.plugin_readiness(),
126 cache_repair,
127 discover_companion,
128 );
129 }
130 Err(error) => {
131 push_project_failure_checks(&mut checks, &error.message(), &root, options.config_path);
132 }
133 }
134
135 build_output(checks)
136}
137
138fn resolve_doctor_run(
141 root: &Path,
142 config_path: Option<&Path>,
143 cache_dir: Option<&Path>,
144) -> Result<ResolvedRun, fallow_engine::resolved_run::ResolveError> {
145 let analysis = crate::AnalysisOptions {
146 root: Some(root.to_path_buf()),
147 config_path: config_path.map(Path::to_path_buf),
148 no_cache: true,
149 threads: Some(1),
150 ..crate::AnalysisOptions::default()
151 };
152 let mut inputs = crate::run::run_inputs(
153 &analysis,
154 &crate::run::ProgrammaticEntry::Doctor,
155 crate::run::RouteSettings::default(),
156 );
157 inputs.cache_dir = cache_dir
158 .filter(|path| !path.as_os_str().is_empty())
159 .map(|path| Given {
160 value: path.to_path_buf(),
161 origin: Origin::ApiOption("cache_dir"),
162 });
163 resolve_run(&inputs)
164}
165
166struct ReadyProject {
169 path: Option<PathBuf>,
170 config: ResolvedConfig,
171 workspaces: Vec<WorkspaceInfo>,
172 workspace_diagnostics: Vec<WorkspaceDiagnostic>,
173 type_aware: Result<(bool, fallow_config::TypeAwareRequire), &'static str>,
176}
177
178impl ReadyProject {
179 fn of(run: &ResolvedRun) -> Self {
180 let fallow_engine::resolved_run::AnalysisSlot::Runs(dead_code) =
181 run.analysis(fallow_config::PlannedAnalysis::DeadCode)
182 else {
183 unreachable!("the doctor run selects the dead-code analysis");
184 };
185 Self {
186 path: run.config_file().value().clone(),
187 config: dead_code.config().clone(),
188 workspaces: dead_code.workspaces().to_vec(),
189 workspace_diagnostics: dead_code.workspace_diagnostics().to_vec(),
190 type_aware: run
191 .type_aware()
192 .map(|settings| (*settings.enabled.value(), *settings.require.value()))
193 .map_err(|err| type_aware_readiness_text(&err)),
194 }
195 }
196}
197
198fn type_aware_readiness_text(err: &fallow_engine::resolved_run::ResolveError) -> &'static str {
200 use fallow_engine::resolved_run::{InputField, InputProblem, ResolveError};
201 match err {
202 ResolveError::Input {
203 field: InputField::Env(fallow_config::EnvVar::TypeAwareRequire),
204 problem: InputProblem::NotUnicode,
205 ..
206 } => "FALLOW_TYPE_AWARE_REQUIRE must contain valid UTF-8.",
207 ResolveError::Input {
208 field: InputField::Env(fallow_config::EnvVar::TypeAwareRequire),
209 ..
210 } => "FALLOW_TYPE_AWARE_REQUIRE must be best-effort or complete.",
211 ResolveError::Input {
212 problem: InputProblem::NotUnicode,
213 ..
214 } => "FALLOW_TYPE_AWARE must contain valid UTF-8.",
215 _ => "FALLOW_TYPE_AWARE must contain a supported boolean value.",
216 }
217}
218
219fn push_ready_project_checks<F>(
220 checks: &mut Vec<DoctorCheck>,
221 root: &Path,
222 project: &ReadyProject,
223 configured_plugin_diagnostics: &[fallow_config::ConfiguredPluginDiagnostic],
224 cache_repair: impl Fn() -> Result<DoctorRemediation, &'static str>,
225 discover_companion: &F,
226) where
227 F: Fn(&Path) -> Result<(), String>,
228{
229 let config_message = project.path.as_ref().map_or_else(
230 || "Zero-config defaults resolved successfully.".to_string(),
231 |path| match safe_config_argument(root, path) {
232 Some(path) => format!("Configuration resolved from {path}."),
233 None => "The explicitly selected configuration resolved successfully.".to_string(),
234 },
235 );
236 checks.push(check(
237 DoctorCheckId::Config,
238 DoctorCheckCategory::Configuration,
239 DoctorCheckStatus::Pass,
240 true,
241 config_message,
242 None,
243 ));
244
245 let workspace_status = if project.workspace_diagnostics.is_empty() {
246 DoctorCheckStatus::Pass
247 } else {
248 DoctorCheckStatus::Warn
249 };
250 let workspace_count = project.workspaces.len();
251 let workspace_noun = if workspace_count == 1 {
252 "workspace package"
253 } else {
254 "workspace packages"
255 };
256 let mut workspace_message = if project.workspace_diagnostics.is_empty() {
257 format!("Workspace discovery completed ({workspace_count} {workspace_noun}).")
258 } else {
259 let diagnostic_count = project.workspace_diagnostics.len();
260 let diagnostic_noun = if diagnostic_count == 1 {
261 "diagnostic"
262 } else {
263 "diagnostics"
264 };
265 format!(
266 "Workspace discovery completed with {diagnostic_count} {diagnostic_noun}; {workspace_count} {workspace_noun} retained."
267 )
268 };
269 if workspace_status == DoctorCheckStatus::Warn {
270 append_external_config_note(&mut workspace_message, root, project.path.as_deref());
271 }
272 checks.push(check(
273 DoctorCheckId::Workspaces,
274 DoctorCheckCategory::Workspace,
275 workspace_status,
276 false,
277 workspace_message,
278 (workspace_status == DoctorCheckStatus::Warn)
279 .then(|| {
280 remediation_with_config(
281 "fallow workspaces --format json --quiet",
282 root,
283 project.path.as_deref(),
284 )
285 })
286 .flatten(),
287 ));
288
289 checks.push(plugin_check(root, project, configured_plugin_diagnostics));
290
291 checks.push(type_aware_check(
292 root,
293 project.type_aware,
294 discover_companion,
295 ));
296
297 checks.push(dependencies_check(root));
298 for mut check in [
299 cache_check(&project.config),
300 graph_cache_check(&project.config),
301 ] {
302 if check.status == DoctorCheckStatus::Warn {
303 match cache_repair() {
304 Ok(repair) => check.remediation = Some(repair),
305 Err(hint) => {
306 check.message.push(' ');
307 check.message.push_str(hint);
308 }
309 }
310 }
311 checks.push(check);
312 }
313 checks.push(mutation_runner_check(root, project.config.mutation.runner));
314}
315
316fn dependencies_check(root: &Path) -> DoctorCheck {
322 if !fallow_config::node_modules_missing(root) {
323 return check(
324 DoctorCheckId::Dependencies,
325 DoctorCheckCategory::Project,
326 DoctorCheckStatus::Pass,
327 false,
328 "Dependencies are installed, or the project runs without a node_modules directory.",
329 None,
330 );
331 }
332 check(
333 DoctorCheckId::Dependencies,
334 DoctorCheckCategory::Project,
335 DoctorCheckStatus::Warn,
336 false,
337 "No node_modules directory. Package exports, plugin activation, and dependency \
338 classification degrade until dependencies are installed.",
339 Some(remediation(
340 &project_package_manager(root).install_command(),
341 true,
342 )),
343 )
344}
345
346fn cache_check(config: &fallow_config::ResolvedConfig) -> DoctorCheck {
353 let status = fallow_engine::cache_status::inspect_parse_cache(config);
354 let size = status
355 .size_bytes
356 .map_or_else(String::new, |bytes| format!(" ({})", format_size_mb(bytes)));
357 match status.rejection {
358 None => check(
359 DoctorCheckId::Cache,
360 DoctorCheckCategory::Cache,
361 DoctorCheckStatus::Pass,
362 false,
363 format!("Extraction cache is reusable{size}."),
364 None,
365 ),
366 Some(fallow_types::cache_rejection::CacheRejection::Absent) => check(
367 DoctorCheckId::Cache,
368 DoctorCheckCategory::Cache,
369 DoctorCheckStatus::Pass,
370 false,
371 "No extraction cache yet; the next run writes one.",
372 None,
373 ),
374 Some(rejection) => check(
375 DoctorCheckId::Cache,
376 DoctorCheckCategory::Cache,
377 DoctorCheckStatus::Warn,
378 false,
379 format!(
380 "Extraction cache{size} would not be reused: {}. The next run parses every file.",
381 rejection.describe()
382 ),
383 None,
384 ),
385 }
386}
387
388fn graph_cache_check(config: &fallow_config::ResolvedConfig) -> DoctorCheck {
400 let status = fallow_engine::cache_status::inspect_graph_cache(config);
401 let size = status
402 .size_bytes
403 .map_or_else(String::new, |bytes| format!(" ({})", format_size_mb(bytes)));
404 match status.rejection {
405 None => check(
406 DoctorCheckId::GraphCache,
407 DoctorCheckCategory::Cache,
408 DoctorCheckStatus::Pass,
409 false,
410 format!(
411 "Module-graph cache{size} loads; a run reuses it when the analysed files and \
412 options are unchanged."
413 ),
414 None,
415 ),
416 Some(fallow_types::cache_rejection::CacheRejection::Absent) => check(
417 DoctorCheckId::GraphCache,
418 DoctorCheckCategory::Cache,
419 DoctorCheckStatus::Pass,
420 false,
421 "No module-graph cache yet; the next run writes one.",
422 None,
423 ),
424 Some(rejection) => check(
425 DoctorCheckId::GraphCache,
426 DoctorCheckCategory::Cache,
427 DoctorCheckStatus::Warn,
428 false,
429 format!(
430 "Module-graph cache{size} would not be reused: {}. The next run resolves imports \
431 and rebuilds the graph.",
432 rejection.describe()
433 ),
434 None,
435 ),
436 }
437}
438
439fn mutation_runner_check(root: &Path, configured: fallow_config::MutationRunner) -> DoctorCheck {
453 use crate::mutation::runner_select::{Runner, declares_vitest, select_runner};
454 use crate::mutation::runner_version::{
455 check_runner_version, installs_package, runner_range, runner_version_help, supported_range,
456 unsupported_message,
457 };
458
459 let runner = select_runner(configured, root, &[]);
460 if runner != Runner::Vitest {
461 return skipped(
462 DoctorCheckId::MutationRunner,
463 DoctorCheckCategory::Companion,
464 "The mutation runner checks the version of its runtime when a run starts.",
465 );
466 }
467 if configured == fallow_config::MutationRunner::Auto
468 && !declares_vitest(root)
469 && !installs_package(root, runner.name())
470 {
471 return skipped(
472 DoctorCheckId::MutationRunner,
473 DoctorCheckCategory::Companion,
474 "The project declares no mutation test runner.",
475 );
476 }
477 let range = match runner_range(runner) {
478 Ok(range) => range,
479 Err(message) => {
480 return check(
481 DoctorCheckId::MutationRunner,
482 DoctorCheckCategory::Companion,
483 DoctorCheckStatus::Warn,
484 false,
485 message,
486 None,
487 );
488 }
489 };
490 let version = check_runner_version(runner, range, root);
491 if let (Some(installed), Some(true)) = (&version.installed_version, version.supported) {
492 return check(
493 DoctorCheckId::MutationRunner,
494 DoctorCheckCategory::Companion,
495 DoctorCheckStatus::Pass,
496 false,
497 format!(
498 "{} {installed} is in the supported mutation runner range {}.",
499 range.package,
500 supported_range(range)
501 ),
502 None,
503 );
504 }
505 check(
506 DoctorCheckId::MutationRunner,
507 DoctorCheckCategory::Companion,
508 DoctorCheckStatus::Warn,
509 false,
510 format!(
511 "{}. A mutation run stops before the first mutant. Fix: {}.",
512 unsupported_message(range, version.installed_version.as_deref()),
513 runner_version_help(range)
514 ),
515 Some(remediation(
516 &fallow_config::PackageManager::suggested_add_dev_command(
517 Some(root),
518 &format!("{}@^{}", range.package, range.min_version),
519 ),
520 true,
521 )),
522 )
523}
524
525fn format_size_mb(bytes: u64) -> String {
531 #[expect(
532 clippy::cast_precision_loss,
533 reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
534 )]
535 let scaled = bytes as f64;
536 if bytes >= 1024 * 1024 {
537 format!("{:.1} MB", scaled / (1024.0 * 1024.0))
538 } else if bytes >= 1024 {
539 format!("{:.1} KB", scaled / 1024.0)
540 } else {
541 format!("{bytes} bytes")
542 }
543}
544
545fn plugin_check(
546 root: &Path,
547 project: &ReadyProject,
548 configured_plugin_diagnostics: &[fallow_config::ConfiguredPluginDiagnostic],
549) -> DoctorCheck {
550 if !configured_plugin_diagnostics.is_empty() {
551 let diagnostic_count = configured_plugin_diagnostics.len();
552 let resource_noun = if diagnostic_count == 1 {
553 "resource"
554 } else {
555 "resources"
556 };
557 let mut message = format!(
558 "External plugin configuration contains {diagnostic_count} unresolved configured {resource_noun}."
559 );
560 append_external_config_note(&mut message, root, project.path.as_deref());
561 return check(
562 DoctorCheckId::Plugins,
563 DoctorCheckCategory::Plugin,
564 DoctorCheckStatus::Fail,
565 true,
566 message,
567 remediation_with_config(
568 "fallow plugin-check --format json --quiet",
569 root,
570 project.path.as_deref(),
571 ),
572 );
573 }
574
575 let configured = &project.config.external_plugins;
576 if configured.is_empty() {
577 return check(
578 DoctorCheckId::Plugins,
579 DoctorCheckCategory::Plugin,
580 DoctorCheckStatus::Pass,
581 true,
582 "No external plugins are configured; built-in detection remains available.",
583 None,
584 );
585 }
586
587 let active = configured
588 .iter()
589 .filter(|plugin| external_plugin_is_active(plugin, root, &project.workspaces))
590 .count();
591 let configured_count = configured.len();
592 let status = if active == configured_count {
593 DoctorCheckStatus::Pass
594 } else {
595 DoctorCheckStatus::Warn
596 };
597 let mut message = format!(
598 "External plugin activation evaluated ({active} active of {configured_count} configured)."
599 );
600 if status == DoctorCheckStatus::Warn {
601 append_external_config_note(&mut message, root, project.path.as_deref());
602 }
603 check(
604 DoctorCheckId::Plugins,
605 DoctorCheckCategory::Plugin,
606 status,
607 false,
608 message,
609 (status == DoctorCheckStatus::Warn)
610 .then(|| {
611 remediation_with_config(
612 "fallow plugin-check --format json --quiet",
613 root,
614 project.path.as_deref(),
615 )
616 })
617 .flatten(),
618 )
619}
620
621fn external_plugin_is_active(
622 plugin: &fallow_config::ExternalPluginDef,
623 root: &Path,
624 workspaces: &[fallow_config::WorkspaceInfo],
625) -> bool {
626 std::iter::once(root)
627 .chain(workspaces.iter().map(|workspace| workspace.root.as_path()))
628 .any(|package_root| {
629 let Some(package) = fallow_config::load_dir_package_json(package_root) else {
630 return false;
631 };
632 fallow_engine::plugins::is_external_plugin_active(
633 plugin,
634 &package.all_dependency_names(),
635 package_root,
636 &[],
637 )
638 })
639}
640
641fn push_project_failure_checks(
642 checks: &mut Vec<DoctorCheck>,
643 error: &str,
644 root: &Path,
645 config_path: Option<&Path>,
646) {
647 if error.starts_with("invalid external plugin definition") {
648 checks.push(check(
649 DoctorCheckId::Config,
650 DoctorCheckCategory::Configuration,
651 DoctorCheckStatus::Pass,
652 true,
653 "Configuration parsed, but external plugin validation failed.",
654 None,
655 ));
656 checks.push(skipped(
657 DoctorCheckId::Workspaces,
658 DoctorCheckCategory::Workspace,
659 "Plugin validation failed before workspace discovery.",
660 ));
661 let mut message = "External plugin configuration is invalid.".to_string();
662 append_external_config_note(&mut message, root, config_path);
663 checks.push(check(
664 DoctorCheckId::Plugins,
665 DoctorCheckCategory::Plugin,
666 DoctorCheckStatus::Fail,
667 true,
668 message,
669 remediation_with_config(
670 "fallow plugin-check --format json --quiet",
671 root,
672 config_path,
673 ),
674 ));
675 } else if error.starts_with("root package.json") || error.starts_with("root Deno config") {
676 checks.push(check(
677 DoctorCheckId::Config,
678 DoctorCheckCategory::Configuration,
679 DoctorCheckStatus::Pass,
680 true,
681 "Fallow configuration resolved successfully.",
682 None,
683 ));
684 let mut message = "Root workspace manifest discovery failed.".to_string();
685 append_external_config_note(&mut message, root, config_path);
686 checks.push(check(
687 DoctorCheckId::Workspaces,
688 DoctorCheckCategory::Workspace,
689 DoctorCheckStatus::Fail,
690 true,
691 message,
692 remediation_with_config("fallow workspaces --format json --quiet", root, config_path),
693 ));
694 checks.push(skipped(
695 DoctorCheckId::Plugins,
696 DoctorCheckCategory::Plugin,
697 "Workspace discovery failed before readiness collection completed.",
698 ));
699 } else {
700 let mut message = "Fallow configuration could not be resolved.".to_string();
701 append_external_config_note(&mut message, root, config_path);
702 checks.push(check(
703 DoctorCheckId::Config,
704 DoctorCheckCategory::Configuration,
705 DoctorCheckStatus::Fail,
706 true,
707 message,
708 remediation_with_config("fallow config", root, config_path),
709 ));
710 checks.push(skipped(
711 DoctorCheckId::Workspaces,
712 DoctorCheckCategory::Workspace,
713 "Configuration readiness failed.",
714 ));
715 checks.push(skipped(
716 DoctorCheckId::Plugins,
717 DoctorCheckCategory::Plugin,
718 "Configuration readiness failed.",
719 ));
720 }
721 checks.push(skipped(
722 DoctorCheckId::TypeAware,
723 DoctorCheckCategory::Companion,
724 "Configuration readiness did not establish whether type-aware analysis is enabled.",
725 ));
726 checks.push(dependencies_check(root));
727 checks.push(skipped(
728 DoctorCheckId::Cache,
729 DoctorCheckCategory::Cache,
730 "Configuration readiness did not establish which cache this project uses.",
731 ));
732 checks.push(skipped(
733 DoctorCheckId::GraphCache,
734 DoctorCheckCategory::Cache,
735 "Configuration readiness did not establish which cache this project uses.",
736 ));
737 checks.push(skipped(
738 DoctorCheckId::MutationRunner,
739 DoctorCheckCategory::Companion,
740 "Configuration readiness did not establish which mutation runner this project uses.",
741 ));
742}
743
744fn type_aware_check<F>(
745 root: &Path,
746 type_aware: Result<(bool, fallow_config::TypeAwareRequire), &'static str>,
747 discover_companion: &F,
748) -> DoctorCheck
749where
750 F: Fn(&Path) -> Result<(), String>,
751{
752 let (enabled, require) = match type_aware {
753 Ok(effective) => effective,
754 Err(message) => {
755 return check(
756 DoctorCheckId::TypeAware,
757 DoctorCheckCategory::Companion,
758 DoctorCheckStatus::Fail,
759 true,
760 message,
761 None,
762 );
763 }
764 };
765 if !enabled {
766 return skipped(
767 DoctorCheckId::TypeAware,
768 DoctorCheckCategory::Companion,
769 "Type-aware analysis is not enabled.",
770 );
771 }
772
773 match discover_companion(root) {
774 Ok(()) => check(
775 DoctorCheckId::TypeAware,
776 DoctorCheckCategory::Companion,
777 DoctorCheckStatus::Pass,
778 require == fallow_config::TypeAwareRequire::Complete,
779 "A trusted type-aware companion is discoverable without starting it.",
780 None,
781 ),
782 Err(_) => {
783 let required = require == fallow_config::TypeAwareRequire::Complete;
784 check(
785 DoctorCheckId::TypeAware,
786 DoctorCheckCategory::Companion,
787 if required {
788 DoctorCheckStatus::Fail
789 } else {
790 DoctorCheckStatus::Warn
791 },
792 required,
793 "Type-aware analysis is enabled, but no trusted companion is discoverable.",
794 Some(remediation(
795 &fallow_config::PackageManager::suggested_add_dev_command(
796 Some(root),
797 &format!("fallow-type-aware@{}", env!("CARGO_PKG_VERSION")),
798 ),
799 true,
800 )),
801 )
802 }
803 }
804}
805
806fn project_package_manager(root: &Path) -> fallow_config::PackageManager {
809 fallow_config::PackageManager::detect_nearest(root)
810 .unwrap_or(fallow_config::PackageManager::Npm)
811}
812
813fn remediation(command: &str, mutating: bool) -> DoctorRemediation {
814 DoctorRemediation {
815 command: command.to_string(),
816 cwd: ".".to_string(),
817 mutating,
818 }
819}
820
821fn remediation_with_config(
822 command: &str,
823 root: &Path,
824 config_path: Option<&Path>,
825) -> Option<DoctorRemediation> {
826 let command = match config_path {
827 None => command.to_string(),
828 Some(path) => format!("{command} --config={}", safe_config_argument(root, path)?),
829 };
830 Some(remediation(&command, false))
831}
832
833fn safe_config_argument(root: &Path, config_path: &Path) -> Option<String> {
834 let canonical_root = dunce::canonicalize(root).ok()?;
835 let canonical = canonicalize_with_missing_suffix(config_path)?;
836 let relative = relative_path(&canonical_root, &canonical)?;
837 relative
838 .bytes()
839 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'/'))
840 .then_some(relative)
841}
842
843fn canonicalize_with_missing_suffix(path: &Path) -> Option<PathBuf> {
844 let mut ancestor = path;
845 let mut suffix = Vec::new();
846
847 loop {
848 match dunce::canonicalize(ancestor) {
849 Ok(mut canonical) => {
850 if !suffix.is_empty() && !canonical.is_dir() {
851 return None;
852 }
853 for component in suffix.into_iter().rev() {
854 canonical.push(component);
855 }
856 return Some(canonical);
857 }
858 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
859 match std::fs::symlink_metadata(ancestor) {
860 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
861 _ => return None,
862 }
863 let std::path::Component::Normal(component) = ancestor.components().next_back()?
864 else {
865 return None;
866 };
867 suffix.push(component.to_os_string());
868 ancestor = ancestor.parent()?;
869 }
870 Err(_) => return None,
871 }
872 }
873}
874
875fn append_external_config_note(message: &mut String, root: &Path, config_path: Option<&Path>) {
876 if config_path.is_some_and(|path| safe_config_argument(root, path).is_none()) {
877 message.push_str(" Repeat this diagnostic with the same explicit --config value.");
878 }
879}
880
881fn push_prerequisite_skips(checks: &mut Vec<DoctorCheck>, message: &str) {
882 for (id, category) in [
883 (DoctorCheckId::Config, DoctorCheckCategory::Configuration),
884 (DoctorCheckId::Workspaces, DoctorCheckCategory::Workspace),
885 (DoctorCheckId::Plugins, DoctorCheckCategory::Plugin),
886 (DoctorCheckId::TypeAware, DoctorCheckCategory::Companion),
887 (DoctorCheckId::Dependencies, DoctorCheckCategory::Project),
888 (DoctorCheckId::Cache, DoctorCheckCategory::Cache),
889 (DoctorCheckId::GraphCache, DoctorCheckCategory::Cache),
890 (
891 DoctorCheckId::MutationRunner,
892 DoctorCheckCategory::Companion,
893 ),
894 ] {
895 checks.push(skipped(id, category, message));
896 }
897}
898
899fn skipped(id: DoctorCheckId, category: DoctorCheckCategory, message: &str) -> DoctorCheck {
900 check(
901 id,
902 category,
903 DoctorCheckStatus::Skipped,
904 false,
905 message,
906 None,
907 )
908}
909
910fn check(
911 id: DoctorCheckId,
912 category: DoctorCheckCategory,
913 status: DoctorCheckStatus,
914 required: bool,
915 message: impl Into<String>,
916 remediation: Option<DoctorRemediation>,
917) -> DoctorCheck {
918 DoctorCheck {
919 id,
920 category,
921 status,
922 required,
923 message: message.into(),
924 remediation,
925 }
926}
927
928fn build_output(checks: Vec<DoctorCheck>) -> DoctorOutput {
929 let summary = checks
930 .iter()
931 .fold(DoctorSummary::default(), |mut summary, check| {
932 match check.status {
933 DoctorCheckStatus::Pass => summary.pass += 1,
934 DoctorCheckStatus::Warn => summary.warn += 1,
935 DoctorCheckStatus::Fail => summary.fail += 1,
936 DoctorCheckStatus::Skipped => summary.skipped += 1,
937 }
938 summary
939 });
940 let status = if checks
941 .iter()
942 .any(|check| check.required && check.status == DoctorCheckStatus::Fail)
943 {
944 DoctorStatus::Fail
945 } else if summary.warn > 0 {
946 DoctorStatus::Warn
947 } else {
948 DoctorStatus::Pass
949 };
950 DoctorOutput {
951 schema_version: SchemaVersion(DOCTOR_SCHEMA_VERSION),
952 version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
953 root: ".".to_string(),
954 status,
955 summary,
956 checks,
957 }
958}
959
960fn relative_path(root: &Path, path: &Path) -> Option<String> {
961 path.strip_prefix(root).ok().map(|path| {
962 let relative = path
963 .to_string_lossy()
964 .replace(std::path::MAIN_SEPARATOR, "/");
965 if relative.is_empty() {
966 ".".to_string()
967 } else {
968 relative
969 }
970 })
971}
972
973#[cfg(test)]
974#[path = "doctor_tests.rs"]
975mod tests;