Skip to main content

devimg_core/
doctor.rs

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("report", format!("found {report_project_path}")));
191    } else {
192        warnings.push(diagnostic(
193            "missing_report",
194            report_project_path.as_str(),
195            "Markdown report is missing",
196            format!("Refresh it with `{}`.", check_command(&config_path)),
197        ));
198    }
199
200    if issues.is_empty() {
201        match check_with_options(
202            config,
203            CheckOptions {
204                write_report: false,
205            },
206        ) {
207            Ok(check_result) => {
208                generated_variant_count = check_result.result.manifest.outputs.len();
209                output_bytes = check_result.result.output_bytes;
210                budget_status = check_result.result.budget_status.clone();
211                for warning in check_result.result.warnings {
212                    warnings.push(warning_diagnostic(&warning, &config_path));
213                }
214                for warning in check_result.result.acknowledged_warnings {
215                    acknowledged_warnings
216                        .push(acknowledged_warning_diagnostic(&warning, &config_path));
217                }
218                for issue in check_result.result.issues {
219                    issues.push(check_issue_diagnostic(&issue, &config_path));
220                }
221                if check_result.passed {
222                    checks.push(pass_check(
223                        "outputs",
224                        format!("all {generated_variant_count} generated variant(s) are current"),
225                    ));
226                } else {
227                    checks.push(fail_check(
228                        "outputs",
229                        "generated outputs are missing, stale, modified, or over budget",
230                    ));
231                }
232            }
233            Err(error) => issues.push(error_diagnostic(
234                "check_failed",
235                config_path.as_str(),
236                &error,
237                "Fix the check error, then run `devimg doctor` again.",
238            )),
239        }
240    }
241
242    if let Some(export_options) = options.manifest_export {
243        inspect_manifest_export(&manifest_path, export_options, &mut checks, &mut issues)?;
244    }
245
246    let budget = DoctorBudget {
247        status: budget_status,
248        max_total_bytes: config.budgets.max_total_bytes,
249        max_file_bytes: config.budgets.max_file_bytes,
250        total_output_bytes: output_bytes,
251        total_headroom_bytes: config
252            .budgets
253            .max_total_bytes
254            .map(|max| max as i64 - output_bytes as i64),
255    };
256    let next_command = next_command(config, &issues, &warnings);
257    let status = if issues.is_empty() { "pass" } else { "fail" }.to_string();
258
259    Ok(DoctorReport {
260        status,
261        config_path,
262        project_root,
263        manifest_path: manifest_project_path,
264        report_path: report_project_path,
265        frameworks: framework_inspection.frameworks,
266        manifest_helpers: framework_inspection.manifest_helpers,
267        source_image_count,
268        planned_variant_count,
269        generated_variant_count,
270        source_bytes,
271        output_bytes,
272        budget,
273        checks,
274        warnings,
275        acknowledged_warnings,
276        issues,
277        next_command,
278    })
279}
280
281pub fn doctor_report_to_json(report: &DoctorReport) -> String {
282    serde_json::to_string_pretty(report).expect("doctor report serialization cannot fail") + "\n"
283}
284
285fn inspect_source_dirs(
286    config: &Config,
287    checks: &mut Vec<DoctorCheck>,
288    warnings: &mut Vec<DoctorDiagnostic>,
289    issues: &mut Vec<DoctorDiagnostic>,
290) -> Result<()> {
291    for source in &config.sources {
292        let input_root = resolve_project_path_checked(config, &source.input, "source input")?;
293        let output_root = resolve_project_path_checked(config, &source.output, "source output")?;
294        let input_project_path = path_to_string(&project_relative(config, &input_root));
295        let output_project_path = path_to_string(&project_relative(config, &output_root));
296
297        if !input_root.exists() {
298            checks.push(fail_check(
299                "sources",
300                format!(
301                    "source `{}` input is missing: {}",
302                    source.name, input_project_path
303                ),
304            ));
305            issues.push(diagnostic(
306                "missing_source_dir",
307                input_project_path,
308                format!("source `{}` input directory does not exist", source.name),
309                "Create the directory, add images, or update `input` in devimg.toml.",
310            ));
311            continue;
312        }
313        if !input_root.is_dir() {
314            checks.push(fail_check(
315                "sources",
316                format!(
317                    "source `{}` input is not a directory: {}",
318                    source.name, input_project_path
319                ),
320            ));
321            issues.push(diagnostic(
322                "invalid_source_dir",
323                input_project_path,
324                format!("source `{}` input is not a directory", source.name),
325                "Point `input` at a directory, then run `devimg doctor` again.",
326            ));
327            continue;
328        }
329
330        checks.push(pass_check(
331            "sources",
332            format!(
333                "source `{}` input exists: {}",
334                source.name, input_project_path
335            ),
336        ));
337
338        if output_root.starts_with(&input_root) {
339            warnings.push(diagnostic(
340                "output_inside_source",
341                output_project_path,
342                format!(
343                    "source `{}` output directory is inside its input directory",
344                    source.name
345                ),
346                "This is supported, but keep generated paths excluded from source globs.",
347            ));
348        } else if input_root.starts_with(&output_root) {
349            warnings.push(diagnostic(
350                "source_inside_output",
351                input_project_path,
352                format!(
353                    "source `{}` input directory is inside its output directory",
354                    source.name
355                ),
356                "Move input or output paths apart to avoid accidentally scanning generated files.",
357            ));
358        }
359    }
360    Ok(())
361}
362
363fn inspect_manifest_export(
364    manifest_path: &Path,
365    export_options: DoctorManifestExportOptions,
366    checks: &mut Vec<DoctorCheck>,
367    issues: &mut Vec<DoctorDiagnostic>,
368) -> Result<()> {
369    let manifest = match read_manifest(manifest_path) {
370        Ok(manifest) => manifest,
371        Err(error) => {
372            issues.push(error_diagnostic(
373                "manifest_export_unavailable",
374                path_to_string(manifest_path),
375                &error,
376                "Run `devimg optimize --config <path>` before checking manifest export drift.",
377            ));
378            checks.push(fail_check(
379                "manifest_export",
380                "manifest export could not be rendered",
381            ));
382            return Ok(());
383        }
384    };
385    let output = export_options.output;
386    let output_label = path_to_string(&output);
387    let options = ManifestExportOptions {
388        strip_prefix: export_options.strip_prefix,
389        url_prefix: export_options.url_prefix,
390    };
391    let rendered = match export_options.format {
392        DoctorManifestExportFormat::Json => manifest_export_to_json(&manifest, &options),
393        DoctorManifestExportFormat::Typescript => manifest_export_to_typescript_with_options(
394            &manifest,
395            &options,
396            &ManifestTypescriptOptions {
397                include_helpers: export_options.typescript_helpers,
398            },
399        ),
400    };
401
402    match fs::read(&output) {
403        Ok(current) if current == rendered.as_bytes() => checks.push(pass_check(
404            "manifest_export",
405            format!("export is up to date: {output_label}"),
406        )),
407        Ok(_) => {
408            checks.push(fail_check(
409                "manifest_export",
410                format!("export is stale: {output_label}"),
411            ));
412            issues.push(diagnostic(
413                "manifest_export_stale",
414                output_label,
415                "manifest export differs from the current manifest",
416                "Regenerate it with `devimg manifest export --manifest <manifest> --output <file>`.",
417            ));
418        }
419        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
420            checks.push(fail_check(
421                "manifest_export",
422                format!("export is missing: {output_label}"),
423            ));
424            issues.push(diagnostic(
425                "manifest_export_missing",
426                output_label,
427                "manifest export file does not exist",
428                "Generate it with `devimg manifest export --manifest <manifest> --output <file>`.",
429            ));
430        }
431        Err(source) => return Err(DevimgError::io(output, source)),
432    }
433    Ok(())
434}
435
436fn unique_source_bytes(sources: &[crate::SourceImage]) -> u64 {
437    let mut seen = Vec::<(&str, u64)>::new();
438    for source in sources {
439        if !seen.iter().any(|(path, _)| *path == source.project_path) {
440            seen.push((&source.project_path, source.bytes));
441        }
442    }
443    seen.iter().map(|(_, bytes)| *bytes).sum()
444}
445
446fn display_path(path: &Path) -> String {
447    let rendered = path_to_string(path);
448    if rendered.is_empty() {
449        ".".to_string()
450    } else {
451        rendered
452    }
453}
454
455fn check_issue_diagnostic(issue: &CheckIssue, config_path: &str) -> DoctorDiagnostic {
456    let hint = match issue.kind.as_str() {
457        "missing_manifest" | "missing" | "modified" | "stale" | "outdated_config"
458        | "invalid_output" => format!(
459            "Regenerate outputs with `{}`.",
460            optimize_command(config_path)
461        ),
462        "oversized_file" | "oversized_total" => {
463            "Reduce generated image bytes or update budgets, then run `devimg check` again."
464                .to_string()
465        }
466        _ => "Review the issue, then run `devimg doctor` again.".to_string(),
467    };
468    diagnostic(
469        issue.kind.as_str(),
470        issue.path.as_str(),
471        issue.message.as_str(),
472        hint,
473    )
474}
475
476fn warning_diagnostic(warning: &str, config_path: &str) -> DoctorDiagnostic {
477    let info = warning_info(warning);
478    let path = info
479        .source
480        .or(info.output)
481        .unwrap_or_else(|| config_path.to_string());
482    if info.code.starts_with("quality:") {
483        return diagnostic(
484            info.code,
485            path,
486            warning,
487            "Tune preset quality, fit/crop, widths, or source assets in devimg.toml, then run `devimg doctor` again.",
488        );
489    }
490    diagnostic(
491        info.code,
492        path,
493        warning,
494        "Review the preset/source config, then run `devimg doctor` again.",
495    )
496}
497
498fn acknowledged_warning_diagnostic(warning: &str, config_path: &str) -> DoctorDiagnostic {
499    let mut diagnostic = warning_diagnostic(warning, config_path);
500    diagnostic.hint =
501        "Acknowledged in devimg.toml. Keep the acknowledgement narrow and revisit it when the source image or preset changes."
502            .to_string();
503    diagnostic
504}
505
506fn framework_warning_diagnostic(warning: FrameworkWarning) -> DoctorDiagnostic {
507    diagnostic(warning.code, warning.path, warning.message, warning.hint)
508}
509
510fn error_diagnostic(
511    code: impl Into<String>,
512    path: impl Into<String>,
513    error: &DevimgError,
514    hint: impl Into<String>,
515) -> DoctorDiagnostic {
516    diagnostic(code, path, error.to_string(), hint)
517}
518
519fn diagnostic(
520    code: impl Into<String>,
521    path: impl Into<String>,
522    message: impl Into<String>,
523    hint: impl Into<String>,
524) -> DoctorDiagnostic {
525    DoctorDiagnostic {
526        code: code.into(),
527        path: path.into(),
528        message: message.into(),
529        hint: hint.into(),
530    }
531}
532
533fn pass_check(name: impl Into<String>, message: impl Into<String>) -> DoctorCheck {
534    DoctorCheck {
535        name: name.into(),
536        status: "pass".to_string(),
537        message: message.into(),
538    }
539}
540
541fn fail_check(name: impl Into<String>, message: impl Into<String>) -> DoctorCheck {
542    DoctorCheck {
543        name: name.into(),
544        status: "fail".to_string(),
545        message: message.into(),
546    }
547}
548
549fn next_command(
550    config: &Config,
551    issues: &[DoctorDiagnostic],
552    warnings: &[DoctorDiagnostic],
553) -> String {
554    let config_path = path_to_string(&config.path);
555    if issues.iter().any(|issue| {
556        matches!(
557            issue.code.as_str(),
558            "missing_manifest"
559                | "missing"
560                | "modified"
561                | "stale"
562                | "outdated_config"
563                | "invalid_output"
564        )
565    }) {
566        return optimize_command(&config_path);
567    }
568    if issues
569        .iter()
570        .any(|issue| issue.code.starts_with("manifest_export_"))
571    {
572        return "devimg manifest export --manifest <manifest> --output <file>".to_string();
573    }
574    if issues.iter().any(|issue| {
575        matches!(
576            issue.code.as_str(),
577            "oversized_file" | "oversized_total" | "empty_sources" | "missing_source_dir"
578        )
579    }) {
580        return doctor_command(&config_path);
581    }
582    if warnings
583        .iter()
584        .any(|warning| warning.code == "missing_report")
585    {
586        return check_command(&config_path);
587    }
588    check_command(&config_path)
589}
590
591fn optimize_command(config_path: &str) -> String {
592    format!(
593        "devimg optimize{} --allow-overwrite",
594        config_option(config_path)
595    )
596}
597
598fn check_command(config_path: &str) -> String {
599    format!("devimg check{}", config_option(config_path))
600}
601
602fn doctor_command(config_path: &str) -> String {
603    format!("devimg doctor{}", config_option(config_path))
604}
605
606fn config_option(config_path: &str) -> String {
607    if config_path == DEFAULT_CONFIG_PATH {
608        String::new()
609    } else {
610        format!(" --config {}", shell_arg(config_path))
611    }
612}
613
614fn shell_arg(value: &str) -> String {
615    if !value.is_empty()
616        && value
617            .chars()
618            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '.' | '_' | '-' | ':' | '@'))
619    {
620        value.to_string()
621    } else {
622        format!("'{}'", value.replace('\'', "'\\''"))
623    }
624}