Skip to main content

devimg_core/
check.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::PathBuf;
4
5use crate::budget::{budget_issues, budget_status};
6use crate::config::{project_relative, resolve_project_path_checked, Config, FormatKind};
7use crate::hash::hash_file;
8use crate::manifest::{Manifest, ManifestOutput};
9use crate::pipeline::{
10    path_to_string, unique_source_bytes, write_report, CheckIssue, CheckResult, OptimizeResult,
11};
12use crate::plan::legacy_operation_hash;
13use crate::quality::{append_unique, manifest_quality_warnings};
14use crate::transform::final_output_project_path;
15use crate::warnings::split_acknowledged_warnings;
16use crate::{build_plan, scan_sources, DevimgError, Result};
17
18#[derive(Debug, Clone, Copy)]
19pub struct CheckOptions {
20    pub write_report: bool,
21}
22
23impl Default for CheckOptions {
24    fn default() -> Self {
25        Self { write_report: true }
26    }
27}
28
29pub fn check(config: &Config) -> Result<CheckResult> {
30    check_with_options(config, CheckOptions::default())
31}
32
33pub fn check_with_options(config: &Config, options: CheckOptions) -> Result<CheckResult> {
34    let sources = scan_sources(config)?;
35    let plan = build_plan(config, &sources)?;
36    let manifest_path =
37        resolve_project_path_checked(config, &config.project.manifest, "manifest path")?;
38    let mut issues = Vec::new();
39    let manifest = match crate::manifest::read_manifest(&manifest_path) {
40        Ok(manifest) => manifest,
41        Err(error) => {
42            issues.push(CheckIssue {
43                kind: "missing_manifest".to_string(),
44                path: path_to_string(&project_relative(config, &manifest_path)),
45                message: error.to_string(),
46            });
47            Manifest::new(path_to_string(&config.path), String::new(), Vec::new())
48        }
49    };
50
51    if !manifest.config_hash.is_empty() && manifest.config_hash != config.config_hash {
52        issues.push(CheckIssue {
53            kind: "outdated_config".to_string(),
54            path: path_to_string(&config.path),
55            message: "manifest was generated with a different config hash".to_string(),
56        });
57    }
58
59    let by_output: HashMap<&str, &ManifestOutput> = manifest
60        .outputs
61        .iter()
62        .map(|output| (output.output_path.as_str(), output))
63        .collect();
64    let mut by_operation_hash = HashMap::<&str, Vec<&ManifestOutput>>::new();
65    for output in &manifest.outputs {
66        by_operation_hash
67            .entry(output.operation_hash.as_str())
68            .or_default()
69            .push(output);
70    }
71
72    let mut actual_outputs = Vec::new();
73    for operation in &plan.operations {
74        let manifest_output = if operation.content_hash_filenames {
75            hashed_manifest_output(
76                operation,
77                &manifest.config_hash,
78                &by_operation_hash,
79                &mut issues,
80            )?
81        } else {
82            stable_manifest_output(operation, &manifest.config_hash, &by_output, &mut issues)
83        };
84
85        let actual_project_path = manifest_output
86            .map(|output| output.output_path.clone())
87            .unwrap_or_else(|| operation.output_project_path.clone());
88        let actual_path = if let Some(output) = manifest_output {
89            resolve_project_path_checked(
90                config,
91                &PathBuf::from(&output.output_path),
92                "manifest output path",
93            )?
94        } else {
95            operation.output_path.clone()
96        };
97
98        if !actual_path.exists() {
99            issues.push(CheckIssue {
100                kind: "missing".to_string(),
101                path: actual_project_path,
102                message: "output file does not exist".to_string(),
103            });
104            continue;
105        }
106
107        let actual_hash = hash_file(&actual_path)?;
108        if let Some(manifest_output) = manifest_output {
109            if manifest_output.hash != actual_hash {
110                issues.push(CheckIssue {
111                    kind: "modified".to_string(),
112                    path: actual_project_path.clone(),
113                    message: "output content hash differs from manifest".to_string(),
114                });
115            }
116        }
117        let metadata =
118            fs::metadata(&actual_path).map_err(|source| DevimgError::io(&actual_path, source))?;
119        if let Some(issue) = validate_output_file(operation, &actual_path, &actual_project_path) {
120            issues.push(issue);
121        }
122        actual_outputs.push(ManifestOutput {
123            source_path: operation.source.project_path.clone(),
124            source_hash: operation.source.hash.clone(),
125            source_width: operation.source.width,
126            source_height: operation.source.height,
127            source_bytes: operation.source.bytes,
128            output_path: actual_project_path,
129            preset: operation.preset.clone(),
130            fit: operation.fit.label().to_string(),
131            width: operation.width,
132            height: operation.height,
133            format: operation.format.label().to_string(),
134            bytes: metadata.len(),
135            hash: actual_hash,
136            operation_hash: operation.operation_hash.clone(),
137        });
138    }
139
140    let total_output_bytes = actual_outputs
141        .iter()
142        .map(|output| output.bytes)
143        .sum::<u64>();
144    issues.extend(budget_issues(config, &actual_outputs));
145    let budget_status = budget_status(&issues);
146    let generated_count = actual_outputs.len();
147    let result_manifest = Manifest::new(
148        path_to_string(&config.path),
149        config.config_hash.clone(),
150        actual_outputs,
151    );
152    let mut warnings = plan.warnings;
153    append_unique(&mut warnings, manifest_quality_warnings(&result_manifest));
154    let warning_groups = split_acknowledged_warnings(config, warnings);
155    let result = OptimizeResult {
156        mode: "check".to_string(),
157        source_count: sources.len(),
158        planned_count: plan.operations.len(),
159        generated_count,
160        skipped_count: 0,
161        stale_count: issues.iter().filter(|issue| issue.kind == "stale").count(),
162        source_bytes: unique_source_bytes(&sources),
163        output_bytes: total_output_bytes,
164        warnings: warning_groups.active,
165        acknowledged_warnings: warning_groups.acknowledged,
166        issues,
167        budget_status,
168        manifest: result_manifest,
169    };
170    if options.write_report {
171        write_report(config, &result)?;
172    }
173    Ok(CheckResult {
174        passed: result.issues.is_empty(),
175        result,
176    })
177}
178
179pub(crate) fn validate_output_file(
180    operation: &crate::pipeline::Operation,
181    actual_path: &PathBuf,
182    actual_project_path: &str,
183) -> Option<CheckIssue> {
184    if operation.format == FormatKind::Avif {
185        return validate_avif_container(actual_path)
186            .err()
187            .map(|message| CheckIssue {
188                kind: "invalid_output".to_string(),
189                path: actual_project_path.to_string(),
190                message,
191            });
192    }
193
194    match image::image_dimensions(actual_path) {
195        Ok((width, height)) if width == operation.width && height == operation.height => None,
196        Ok((width, height)) => Some(CheckIssue {
197            kind: "stale".to_string(),
198            path: actual_project_path.to_string(),
199            message: format!(
200                "output dimensions are {}x{}, expected {}x{}",
201                width, height, operation.width, operation.height
202            ),
203        }),
204        Err(source) => Some(CheckIssue {
205            kind: "invalid_output".to_string(),
206            path: actual_project_path.to_string(),
207            message: source.to_string(),
208        }),
209    }
210}
211
212fn validate_avif_container(path: &PathBuf) -> std::result::Result<(), String> {
213    let bytes = fs::read(path).map_err(|source| source.to_string())?;
214    if bytes.len() <= 16 || &bytes[4..8] != b"ftyp" {
215        return Err("AVIF output is missing the ftyp box".to_string());
216    }
217    if !bytes.windows(4).any(|window| window == b"avif") {
218        return Err("AVIF output is missing the avif brand".to_string());
219    }
220    Ok(())
221}
222
223fn stable_manifest_output<'a>(
224    operation: &crate::pipeline::Operation,
225    manifest_config_hash: &str,
226    by_output: &'a HashMap<&str, &'a ManifestOutput>,
227    issues: &mut Vec<CheckIssue>,
228) -> Option<&'a ManifestOutput> {
229    match by_output.get(operation.output_project_path.as_str()) {
230        Some(manifest_output) => {
231            if !operation_hash_matches(manifest_output, operation, manifest_config_hash) {
232                issues.push(CheckIssue {
233                    kind: "stale".to_string(),
234                    path: operation.output_project_path.clone(),
235                    message: "planned operation no longer matches manifest".to_string(),
236                });
237            }
238            Some(*manifest_output)
239        }
240        None => {
241            issues.push(CheckIssue {
242                kind: "stale".to_string(),
243                path: operation.output_project_path.clone(),
244                message: "planned output is missing from manifest".to_string(),
245            });
246            None
247        }
248    }
249}
250
251fn hashed_manifest_output<'a>(
252    operation: &crate::pipeline::Operation,
253    manifest_config_hash: &str,
254    by_operation_hash: &'a HashMap<&str, Vec<&'a ManifestOutput>>,
255    issues: &mut Vec<CheckIssue>,
256) -> Result<Option<&'a ManifestOutput>> {
257    let legacy_hash = legacy_operation_hash(operation, manifest_config_hash);
258    let Some(outputs) = by_operation_hash
259        .get(operation.operation_hash.as_str())
260        .or_else(|| by_operation_hash.get(legacy_hash.as_str()))
261    else {
262        issues.push(CheckIssue {
263            kind: "stale".to_string(),
264            path: operation.output_project_path.clone(),
265            message: "planned hashed output is missing from manifest".to_string(),
266        });
267        return Ok(None);
268    };
269
270    if outputs.len() > 1 {
271        issues.push(CheckIssue {
272            kind: "stale".to_string(),
273            path: operation.output_project_path.clone(),
274            message: "manifest contains duplicate outputs for one planned operation".to_string(),
275        });
276    }
277
278    let output = outputs[0];
279    let expected_path =
280        final_output_project_path(&operation.output_project_path, &output.hash, operation)?;
281    if output.output_path != expected_path {
282        issues.push(CheckIssue {
283            kind: "stale".to_string(),
284            path: output.output_path.clone(),
285            message: "manifest output path does not match its content hash".to_string(),
286        });
287    }
288
289    Ok(Some(output))
290}
291
292fn operation_hash_matches(
293    output: &ManifestOutput,
294    operation: &crate::pipeline::Operation,
295    manifest_config_hash: &str,
296) -> bool {
297    output.operation_hash == operation.operation_hash
298        || output.operation_hash == legacy_operation_hash(operation, manifest_config_hash)
299}