use std::path::{Path, PathBuf};
use assay_core::config::{load_config_with_cause, path_resolver::PathResolver, LoadOptions};
use assay_core::errors::ConfigLoadError;
use assay_core::render_safety::{render_safe, Sink};
use crate::cli::args::common::OutputFormat;
use crate::cli::args::DoctorArgs;
use crate::cli::helpers::decide_exit;
use crate::diagnostics;
use crate::diagnostics::format::format_text;
use crate::exit_codes::{
reason_for_unloadable_explicit_config, ReasonCode, RunOutcome, EXIT_SUCCESS,
};
use crate::output_write::write_stdout_json;
use super::fixes::run_doctor_fix;
use super::parse_error::try_fix_parse_error;
pub(super) fn config_failure(path: &Path, err: &ConfigLoadError) -> RunOutcome {
let path = path.display().to_string();
RunOutcome::from_reason(
reason_for_unloadable_explicit_config(err),
Some(err.to_string()),
Some(path.as_str()),
)
}
const NO_CONFIG_FOUND: &str = "No config found; run inside project or use --config";
fn caller_text(value: impl std::fmt::Display) -> String {
render_safe(Sink::Stdout, &value.to_string(), usize::MAX)
}
fn config_check_skipped(reason: &str) -> serde_json::Value {
serde_json::json!({
"status": "skipped",
"reason": reason,
})
}
fn config_check_marker(checked: bool, failed: bool) -> serde_json::Value {
match (checked, failed) {
(_, true) => serde_json::json!({ "status": "failed" }),
(true, false) => serde_json::json!({ "status": "checked" }),
(false, false) => config_check_skipped(NO_CONFIG_FOUND),
}
}
fn insert_outcome_fields(
obj: &mut serde_json::Map<String, serde_json::Value>,
outcome: &RunOutcome,
) {
obj.insert(
"reason_code".to_string(),
serde_json::json!(outcome.reason_code),
);
obj.insert(
"next_step".to_string(),
serde_json::json!(outcome.next_step),
);
}
fn invalid_argument_outcome(args: &DoctorArgs) -> Option<RunOutcome> {
let message = if args.fix && args.format == OutputFormat::Json {
"doctor --fix currently supports text output only; use --format text"
} else if (args.yes || args.dry_run) && !args.fix {
"doctor: --yes/--dry-run require --fix"
} else {
return None;
};
Some(RunOutcome::from_reason(
ReasonCode::EInvalidArgs,
Some(message.to_string()),
None,
))
}
fn reject_invalid_args(format: OutputFormat, outcome: RunOutcome) -> anyhow::Result<i32> {
if format == OutputFormat::Json {
let report = diagnostics::probe_system();
let timestamp = chrono::Utc::now().to_rfc3339();
let mut json_out = serde_json::to_value(&report)?;
if let Some(obj) = json_out.as_object_mut() {
obj.insert("generated_at".to_string(), serde_json::json!(timestamp));
let skip_reason = outcome
.message
.as_deref()
.unwrap_or(outcome.reason_code.as_str());
obj.insert(
"config_check".to_string(),
config_check_skipped(skip_reason),
);
insert_outcome_fields(obj, &outcome);
if let Some(message) = &outcome.message {
obj.insert("message".to_string(), serde_json::json!(message));
}
}
let write_code = write_stdout_json(&serde_json::to_string_pretty(&json_out)?);
if write_code != EXIT_SUCCESS {
return Ok(write_code);
}
return Ok(outcome.exit_code);
}
if let Some(message) = &outcome.message {
eprintln!("{message}");
}
Ok(outcome.exit_code)
}
pub async fn run(args: DoctorArgs, legacy_mode: bool) -> anyhow::Result<i32> {
if let Some(outcome) = invalid_argument_outcome(&args) {
return reject_invalid_args(args.format, outcome);
}
let report = diagnostics::probe_system();
let (target_path, explicit) = match args.config.clone() {
Some(p) => (p, true),
None => (PathBuf::from("eval.yaml"), false),
};
let (cfg, cfg_err) = if explicit || target_path.exists() {
match load_config_with_cause(
&target_path,
LoadOptions {
legacy_mode,
..Default::default()
},
) {
Ok(c) => (Some(c), None),
Err(e) => (None, Some(e)),
}
} else {
(None, None)
};
if args.format == OutputFormat::Json {
let timestamp = chrono::Utc::now().to_rfc3339();
let mut json_out = serde_json::to_value(&report)?;
let mut exit = 0;
if let Some(obj) = json_out.as_object_mut() {
obj.insert("generated_at".to_string(), serde_json::json!(timestamp));
obj.insert(
"config_check".to_string(),
config_check_marker(cfg.is_some(), cfg_err.is_some()),
);
if let Some(err) = &cfg_err {
let outcome = config_failure(&target_path, err);
insert_outcome_fields(obj, &outcome);
obj.insert(
"config_error".to_string(),
serde_json::json!({
"message": outcome.message,
"code": outcome.reason_code,
}),
);
let write_code = write_stdout_json(&serde_json::to_string_pretty(&json_out)?);
if write_code != EXIT_SUCCESS {
return Ok(write_code);
}
return Ok(outcome.exit_code);
}
if let Some(c) = &cfg {
let resolver = PathResolver::new(&target_path);
let opts = assay_core::doctor::DoctorOptions {
config_path: target_path.clone(),
trace_file: args.trace_file.clone(),
baseline_file: args.baseline.clone(),
db_path: args.db.clone(),
replay_strict: args.replay_strict,
};
let core_report = assay_core::doctor::doctor(c, &opts, &resolver).await?;
obj.insert(
"data_diagnostics".to_string(),
serde_json::to_value(&core_report.diagnostics)?,
);
obj.insert(
"data_suggestions".to_string(),
serde_json::to_value(&core_report.suggested_actions)?,
);
exit = decide_exit(&core_report.diagnostics);
}
}
let write_code = write_stdout_json(&serde_json::to_string_pretty(&json_out)?);
if write_code != EXIT_SUCCESS {
return Ok(write_code);
}
return Ok(exit);
}
let text_output = format_text(&report);
println!("{}", text_output);
if let Some(e) = &cfg_err {
println!("\nConfig Status: FAILED");
println!(" File: {}", caller_text(target_path.display()));
println!(" Error: {}\n", caller_text(e));
if args.fix {
return try_fix_parse_error(&args, &target_path, e, legacy_mode);
}
return Ok(config_failure(&target_path, e).exit_code);
}
if let Some(c) = cfg {
println!("\nPolicy Check:");
println!(" Config: {}", caller_text(target_path.display()));
println!(" Suite: {}", caller_text(&c.suite));
let resolver = PathResolver::new(&target_path);
let opts = assay_core::doctor::DoctorOptions {
config_path: target_path.clone(),
trace_file: args.trace_file.clone(),
baseline_file: args.baseline.clone(),
db_path: args.db.clone(),
replay_strict: args.replay_strict,
};
let core_report = assay_core::doctor::doctor(&c, &opts, &resolver).await?;
if !core_report.diagnostics.is_empty() {
println!(" Issues: {}", core_report.diagnostics.len());
for d in &core_report.diagnostics {
println!(
" - [{}] [{}] {}",
d.code,
d.severity,
caller_text(&d.message)
);
}
} else {
println!(" Issues: None (Clean)");
}
if args.fix {
let fix_result =
run_doctor_fix(&args, &target_path, &core_report.diagnostics, legacy_mode).await?;
return Ok(fix_result);
}
return Ok(decide_exit(&core_report.diagnostics));
}
println!("\nPolicy Check: SKIPPED ({NO_CONFIG_FOUND})");
Ok(0)
}