1use std::fs;
2use std::path::{Path, PathBuf};
3
4use serde::Serialize;
5
6use crate::check::{check_with_options, CheckOptions};
7use crate::config::{project_relative, resolve_project_path_checked, Config};
8use crate::framework::{inspect_frameworks, FrameworkWarning};
9use crate::manifest::{
10 manifest_export_to_json, manifest_export_to_typescript_with_options, read_manifest,
11 ManifestExportOptions, ManifestTypescriptOptions,
12};
13use crate::pipeline::{path_to_string, CheckIssue};
14use crate::warnings::warning_info;
15use crate::{build_plan, scan_sources, DevimgError, Result};
16
17const DEFAULT_CONFIG_PATH: &str = "devimg.toml";
18
19#[derive(Debug, Clone, Default)]
20pub struct DoctorOptions {
21 pub manifest_export: Option<DoctorManifestExportOptions>,
22}
23
24#[derive(Debug, Clone)]
25pub struct DoctorManifestExportOptions {
26 pub output: PathBuf,
27 pub format: DoctorManifestExportFormat,
28 pub strip_prefix: Option<String>,
29 pub url_prefix: String,
30 pub typescript_helpers: bool,
31}
32
33#[derive(Debug, Clone, Copy)]
34pub enum DoctorManifestExportFormat {
35 Json,
36 Typescript,
37}
38
39#[derive(Debug, Clone, Serialize)]
40pub struct DoctorReport {
41 pub status: String,
42 pub config_path: String,
43 pub project_root: String,
44 pub manifest_path: String,
45 pub report_path: String,
46 pub frameworks: Vec<String>,
47 pub manifest_helpers: Vec<String>,
48 pub source_image_count: usize,
49 pub planned_variant_count: usize,
50 pub generated_variant_count: usize,
51 pub source_bytes: u64,
52 pub output_bytes: u64,
53 pub budget: DoctorBudget,
54 pub checks: Vec<DoctorCheck>,
55 pub warnings: Vec<DoctorDiagnostic>,
56 pub acknowledged_warnings: Vec<DoctorDiagnostic>,
57 pub issues: Vec<DoctorDiagnostic>,
58 pub next_command: String,
59}
60
61#[derive(Debug, Clone, Serialize)]
62pub struct DoctorBudget {
63 pub status: String,
64 pub max_total_bytes: Option<u64>,
65 pub max_file_bytes: Option<u64>,
66 pub total_output_bytes: u64,
67 pub total_headroom_bytes: Option<i64>,
68}
69
70#[derive(Debug, Clone, Serialize)]
71pub struct DoctorCheck {
72 pub name: String,
73 pub status: String,
74 pub message: String,
75}
76
77#[derive(Debug, Clone, Serialize)]
78pub struct DoctorDiagnostic {
79 pub code: String,
80 pub path: String,
81 pub message: String,
82 pub hint: String,
83}
84
85impl DoctorReport {
86 pub fn passed(&self) -> bool {
87 self.issues.is_empty()
88 }
89}
90
91pub fn doctor(config: &Config, options: DoctorOptions) -> Result<DoctorReport> {
92 let config_path = path_to_string(&config.path);
93 let project_root = display_path(&config.project.root);
94 let manifest_path =
95 resolve_project_path_checked(config, &config.project.manifest, "manifest path")?;
96 let report_path = resolve_project_path_checked(config, &config.project.report, "report path")?;
97 let manifest_project_path = path_to_string(&project_relative(config, &manifest_path));
98 let report_project_path = path_to_string(&project_relative(config, &report_path));
99 let mut checks = Vec::new();
100 let mut warnings = Vec::new();
101 let mut acknowledged_warnings = Vec::new();
102 let mut issues = Vec::new();
103 let manifest_export_output = options
104 .manifest_export
105 .as_ref()
106 .map(|export| export.output.as_path());
107
108 checks.push(pass_check(
109 "config",
110 format!("loaded {}", config.path.display()),
111 ));
112
113 inspect_source_dirs(config, &mut checks, &mut warnings, &mut issues)?;
114 let framework_inspection = inspect_frameworks(config, manifest_export_output);
115 if framework_inspection.frameworks.is_empty() {
116 checks.push(pass_check("framework", "no supported framework detected"));
117 } else {
118 checks.push(pass_check(
119 "framework",
120 format!("detected {}", framework_inspection.frameworks.join(", ")),
121 ));
122 checks.push(pass_check(
123 "framework_consumption",
124 "use generated variants through img/picture, framework Image with unoptimized when DevImg owns sizing and quality, or intentionally layer framework optimization on DevImg-generated source variants",
125 ));
126 }
127 for warning in framework_inspection.warnings {
128 warnings.push(framework_warning_diagnostic(warning));
129 }
130
131 let mut source_image_count = 0usize;
132 let mut planned_variant_count = 0usize;
133 let mut generated_variant_count = 0usize;
134 let mut source_bytes = 0u64;
135 let mut output_bytes = 0u64;
136 let mut budget_status = "not evaluated".to_string();
137
138 if issues.is_empty() {
139 match scan_sources(config) {
140 Ok(sources) => {
141 source_image_count = sources.len();
142 source_bytes = unique_source_bytes(&sources);
143 if source_image_count == 0 {
144 issues.push(diagnostic(
145 "empty_sources",
146 ".",
147 "no source images matched the configured sources",
148 "Add source images, or update `include`/`exclude` in devimg.toml.",
149 ));
150 }
151
152 match build_plan(config, &sources) {
153 Ok(plan) => {
154 planned_variant_count = plan.operations.len();
155 checks.push(pass_check(
156 "plan",
157 format!("planned {planned_variant_count} variant(s)"),
158 ));
159 }
160 Err(error) => issues.push(error_diagnostic(
161 "plan_failed",
162 config_path.as_str(),
163 &error,
164 "Fix the plan error, then run `devimg doctor` again.",
165 )),
166 }
167 }
168 Err(error) => issues.push(error_diagnostic(
169 "source_scan_failed",
170 config_path.as_str(),
171 &error,
172 "Fix the source image or config problem, then run `devimg doctor` again.",
173 )),
174 }
175 }
176
177 if manifest_path.exists() {
178 checks.push(pass_check(
179 "manifest",
180 format!("found {}", manifest_project_path),
181 ));
182 } else {
183 checks.push(fail_check(
184 "manifest",
185 format!("missing {}", manifest_project_path),
186 ));
187 }
188
189 if report_path.exists() {
190 checks.push(pass_check(
191 "report",
192 format!("found {}", report_project_path),
193 ));
194 } else {
195 warnings.push(diagnostic(
196 "missing_report",
197 report_project_path.as_str(),
198 "Markdown report is missing",
199 format!("Refresh it with `{}`.", check_command(&config_path)),
200 ));
201 }
202
203 if issues.is_empty() {
204 match check_with_options(
205 config,
206 CheckOptions {
207 write_report: false,
208 },
209 ) {
210 Ok(check_result) => {
211 generated_variant_count = check_result.result.manifest.outputs.len();
212 output_bytes = check_result.result.output_bytes;
213 budget_status = check_result.result.budget_status.clone();
214 for warning in check_result.result.warnings {
215 warnings.push(warning_diagnostic(&warning, &config_path));
216 }
217 for warning in check_result.result.acknowledged_warnings {
218 acknowledged_warnings
219 .push(acknowledged_warning_diagnostic(&warning, &config_path));
220 }
221 for issue in check_result.result.issues {
222 issues.push(check_issue_diagnostic(&issue, &config_path));
223 }
224 if check_result.passed {
225 checks.push(pass_check(
226 "outputs",
227 format!("all {generated_variant_count} generated variant(s) are current"),
228 ));
229 } else {
230 checks.push(fail_check(
231 "outputs",
232 "generated outputs are missing, stale, modified, or over budget",
233 ));
234 }
235 }
236 Err(error) => issues.push(error_diagnostic(
237 "check_failed",
238 config_path.as_str(),
239 &error,
240 "Fix the check error, then run `devimg doctor` again.",
241 )),
242 }
243 }
244
245 if let Some(export_options) = options.manifest_export {
246 inspect_manifest_export(&manifest_path, export_options, &mut checks, &mut issues)?;
247 }
248
249 let budget = DoctorBudget {
250 status: budget_status,
251 max_total_bytes: config.budgets.max_total_bytes,
252 max_file_bytes: config.budgets.max_file_bytes,
253 total_output_bytes: output_bytes,
254 total_headroom_bytes: config
255 .budgets
256 .max_total_bytes
257 .map(|max| max as i64 - output_bytes as i64),
258 };
259 let next_command = next_command(config, &issues, &warnings);
260 let status = if issues.is_empty() { "pass" } else { "fail" }.to_string();
261
262 Ok(DoctorReport {
263 status,
264 config_path,
265 project_root,
266 manifest_path: manifest_project_path,
267 report_path: report_project_path,
268 frameworks: framework_inspection.frameworks,
269 manifest_helpers: framework_inspection.manifest_helpers,
270 source_image_count,
271 planned_variant_count,
272 generated_variant_count,
273 source_bytes,
274 output_bytes,
275 budget,
276 checks,
277 warnings,
278 acknowledged_warnings,
279 issues,
280 next_command,
281 })
282}
283
284pub fn doctor_report_to_json(report: &DoctorReport) -> String {
285 serde_json::to_string_pretty(report).expect("doctor report serialization cannot fail") + "\n"
286}
287
288fn inspect_source_dirs(
289 config: &Config,
290 checks: &mut Vec<DoctorCheck>,
291 warnings: &mut Vec<DoctorDiagnostic>,
292 issues: &mut Vec<DoctorDiagnostic>,
293) -> Result<()> {
294 for source in &config.sources {
295 let input_root = resolve_project_path_checked(config, &source.input, "source input")?;
296 let output_root = resolve_project_path_checked(config, &source.output, "source output")?;
297 let input_project_path = path_to_string(&project_relative(config, &input_root));
298 let output_project_path = path_to_string(&project_relative(config, &output_root));
299
300 if !input_root.exists() {
301 checks.push(fail_check(
302 "sources",
303 format!(
304 "source `{}` input is missing: {}",
305 source.name, input_project_path
306 ),
307 ));
308 issues.push(diagnostic(
309 "missing_source_dir",
310 input_project_path,
311 format!("source `{}` input directory does not exist", source.name),
312 "Create the directory, add images, or update `input` in devimg.toml.",
313 ));
314 continue;
315 }
316 if !input_root.is_dir() {
317 checks.push(fail_check(
318 "sources",
319 format!(
320 "source `{}` input is not a directory: {}",
321 source.name, input_project_path
322 ),
323 ));
324 issues.push(diagnostic(
325 "invalid_source_dir",
326 input_project_path,
327 format!("source `{}` input is not a directory", source.name),
328 "Point `input` at a directory, then run `devimg doctor` again.",
329 ));
330 continue;
331 }
332
333 checks.push(pass_check(
334 "sources",
335 format!(
336 "source `{}` input exists: {}",
337 source.name, input_project_path
338 ),
339 ));
340
341 if output_root.starts_with(&input_root) {
342 warnings.push(diagnostic(
343 "output_inside_source",
344 output_project_path,
345 format!(
346 "source `{}` output directory is inside its input directory",
347 source.name
348 ),
349 "This is supported, but keep generated paths excluded from source globs.",
350 ));
351 } else if input_root.starts_with(&output_root) {
352 warnings.push(diagnostic(
353 "source_inside_output",
354 input_project_path,
355 format!(
356 "source `{}` input directory is inside its output directory",
357 source.name
358 ),
359 "Move input or output paths apart to avoid accidentally scanning generated files.",
360 ));
361 }
362 }
363 Ok(())
364}
365
366fn inspect_manifest_export(
367 manifest_path: &Path,
368 export_options: DoctorManifestExportOptions,
369 checks: &mut Vec<DoctorCheck>,
370 issues: &mut Vec<DoctorDiagnostic>,
371) -> Result<()> {
372 let manifest = match read_manifest(manifest_path) {
373 Ok(manifest) => manifest,
374 Err(error) => {
375 issues.push(error_diagnostic(
376 "manifest_export_unavailable",
377 path_to_string(manifest_path),
378 &error,
379 "Run `devimg optimize --config <path>` before checking manifest export drift.",
380 ));
381 checks.push(fail_check(
382 "manifest_export",
383 "manifest export could not be rendered",
384 ));
385 return Ok(());
386 }
387 };
388 let output = export_options.output;
389 let output_label = path_to_string(&output);
390 let options = ManifestExportOptions {
391 strip_prefix: export_options.strip_prefix,
392 url_prefix: export_options.url_prefix,
393 };
394 let rendered = match export_options.format {
395 DoctorManifestExportFormat::Json => manifest_export_to_json(&manifest, &options),
396 DoctorManifestExportFormat::Typescript => manifest_export_to_typescript_with_options(
397 &manifest,
398 &options,
399 &ManifestTypescriptOptions {
400 include_helpers: export_options.typescript_helpers,
401 },
402 ),
403 };
404
405 match fs::read(&output) {
406 Ok(current) if current == rendered.as_bytes() => checks.push(pass_check(
407 "manifest_export",
408 format!("export is up to date: {output_label}"),
409 )),
410 Ok(_) => {
411 checks.push(fail_check(
412 "manifest_export",
413 format!("export is stale: {output_label}"),
414 ));
415 issues.push(diagnostic(
416 "manifest_export_stale",
417 output_label,
418 "manifest export differs from the current manifest",
419 "Regenerate it with `devimg manifest export --manifest <manifest> --output <file>`.",
420 ));
421 }
422 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
423 checks.push(fail_check(
424 "manifest_export",
425 format!("export is missing: {output_label}"),
426 ));
427 issues.push(diagnostic(
428 "manifest_export_missing",
429 output_label,
430 "manifest export file does not exist",
431 "Generate it with `devimg manifest export --manifest <manifest> --output <file>`.",
432 ));
433 }
434 Err(source) => return Err(DevimgError::io(output, source)),
435 }
436 Ok(())
437}
438
439fn unique_source_bytes(sources: &[crate::SourceImage]) -> u64 {
440 let mut seen = Vec::<(&str, u64)>::new();
441 for source in sources {
442 if !seen.iter().any(|(path, _)| *path == source.project_path) {
443 seen.push((&source.project_path, source.bytes));
444 }
445 }
446 seen.iter().map(|(_, bytes)| *bytes).sum()
447}
448
449fn display_path(path: &Path) -> String {
450 let rendered = path_to_string(path);
451 if rendered.is_empty() {
452 ".".to_string()
453 } else {
454 rendered
455 }
456}
457
458fn check_issue_diagnostic(issue: &CheckIssue, config_path: &str) -> DoctorDiagnostic {
459 let hint = match issue.kind.as_str() {
460 "missing_manifest" | "missing" | "modified" | "stale" | "outdated_config"
461 | "invalid_output" => format!(
462 "Regenerate outputs with `{}`.",
463 optimize_command(config_path)
464 ),
465 "oversized_file" | "oversized_total" => {
466 "Reduce generated image bytes or update budgets, then run `devimg check` again."
467 .to_string()
468 }
469 _ => "Review the issue, then run `devimg doctor` again.".to_string(),
470 };
471 diagnostic(
472 issue.kind.as_str(),
473 issue.path.as_str(),
474 issue.message.as_str(),
475 hint,
476 )
477}
478
479fn warning_diagnostic(warning: &str, config_path: &str) -> DoctorDiagnostic {
480 let info = warning_info(warning);
481 let path = info
482 .source
483 .or(info.output)
484 .unwrap_or_else(|| config_path.to_string());
485 if info.code.starts_with("quality:") {
486 return diagnostic(
487 info.code,
488 path,
489 warning,
490 "Tune preset quality, fit/crop, widths, or source assets in devimg.toml, then run `devimg doctor` again.",
491 );
492 }
493 diagnostic(
494 info.code,
495 path,
496 warning,
497 "Review the preset/source config, then run `devimg doctor` again.",
498 )
499}
500
501fn acknowledged_warning_diagnostic(warning: &str, config_path: &str) -> DoctorDiagnostic {
502 let mut diagnostic = warning_diagnostic(warning, config_path);
503 diagnostic.hint =
504 "Acknowledged in devimg.toml. Keep the acknowledgement narrow and revisit it when the source image or preset changes."
505 .to_string();
506 diagnostic
507}
508
509fn framework_warning_diagnostic(warning: FrameworkWarning) -> DoctorDiagnostic {
510 diagnostic(warning.code, warning.path, warning.message, warning.hint)
511}
512
513fn error_diagnostic(
514 code: impl Into<String>,
515 path: impl Into<String>,
516 error: &DevimgError,
517 hint: impl Into<String>,
518) -> DoctorDiagnostic {
519 diagnostic(code, path, error.to_string(), hint)
520}
521
522fn diagnostic(
523 code: impl Into<String>,
524 path: impl Into<String>,
525 message: impl Into<String>,
526 hint: impl Into<String>,
527) -> DoctorDiagnostic {
528 DoctorDiagnostic {
529 code: code.into(),
530 path: path.into(),
531 message: message.into(),
532 hint: hint.into(),
533 }
534}
535
536fn pass_check(name: impl Into<String>, message: impl Into<String>) -> DoctorCheck {
537 DoctorCheck {
538 name: name.into(),
539 status: "pass".to_string(),
540 message: message.into(),
541 }
542}
543
544fn fail_check(name: impl Into<String>, message: impl Into<String>) -> DoctorCheck {
545 DoctorCheck {
546 name: name.into(),
547 status: "fail".to_string(),
548 message: message.into(),
549 }
550}
551
552fn next_command(
553 config: &Config,
554 issues: &[DoctorDiagnostic],
555 warnings: &[DoctorDiagnostic],
556) -> String {
557 let config_path = path_to_string(&config.path);
558 if issues.iter().any(|issue| {
559 matches!(
560 issue.code.as_str(),
561 "missing_manifest"
562 | "missing"
563 | "modified"
564 | "stale"
565 | "outdated_config"
566 | "invalid_output"
567 )
568 }) {
569 return optimize_command(&config_path);
570 }
571 if issues
572 .iter()
573 .any(|issue| issue.code.starts_with("manifest_export_"))
574 {
575 return "devimg manifest export --manifest <manifest> --output <file>".to_string();
576 }
577 if issues.iter().any(|issue| {
578 matches!(
579 issue.code.as_str(),
580 "oversized_file" | "oversized_total" | "empty_sources" | "missing_source_dir"
581 )
582 }) {
583 return doctor_command(&config_path);
584 }
585 if warnings
586 .iter()
587 .any(|warning| warning.code == "missing_report")
588 {
589 return check_command(&config_path);
590 }
591 check_command(&config_path)
592}
593
594fn optimize_command(config_path: &str) -> String {
595 format!(
596 "devimg optimize{} --allow-overwrite",
597 config_option(config_path)
598 )
599}
600
601fn check_command(config_path: &str) -> String {
602 format!("devimg check{}", config_option(config_path))
603}
604
605fn doctor_command(config_path: &str) -> String {
606 format!("devimg doctor{}", config_option(config_path))
607}
608
609fn config_option(config_path: &str) -> String {
610 if config_path == DEFAULT_CONFIG_PATH {
611 String::new()
612 } else {
613 format!(" --config {}", shell_arg(config_path))
614 }
615}
616
617fn shell_arg(value: &str) -> String {
618 if !value.is_empty()
619 && value
620 .chars()
621 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '.' | '_' | '-' | ':' | '@'))
622 {
623 value.to_string()
624 } else {
625 format!("'{}'", value.replace('\'', "'\\''"))
626 }
627}