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