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            let output = hashed_manifest_output(
76                operation,
77                &manifest.config_hash,
78                &by_operation_hash,
79                &mut issues,
80            );
81            output?
82        } else {
83            stable_manifest_output(operation, &manifest.config_hash, &by_output, &mut issues)
84        };
85
86        let actual_project_path = manifest_output
87            .map(|output| output.output_path.clone())
88            .unwrap_or_else(|| operation.output_project_path.clone());
89        let actual_path = if let Some(output) = manifest_output {
90            manifest_output_path(config, output)?
91        } else {
92            operation.output_path.clone()
93        };
94
95        if !actual_path.exists() {
96            issues.push(CheckIssue {
97                kind: "missing".to_string(),
98                path: actual_project_path,
99                message: "output file does not exist".to_string(),
100            });
101            continue;
102        }
103
104        let actual_hash = hash_file(&actual_path)?;
105        let modified = manifest_output
106            .filter(|output| output.hash != actual_hash)
107            .is_some();
108        if modified {
109            issues.push(CheckIssue {
110                kind: "modified".to_string(),
111                path: actual_project_path.clone(),
112                message: "output content hash differs from manifest".to_string(),
113            });
114        }
115        let metadata = output_metadata(&actual_path)?;
116        if let Some(issue) = validate_output_file(operation, &actual_path, &actual_project_path) {
117            issues.push(issue);
118        }
119        actual_outputs.push(ManifestOutput {
120            source_path: operation.source.project_path.clone(),
121            source_hash: operation.source.hash.clone(),
122            source_width: operation.source.width,
123            source_height: operation.source.height,
124            source_bytes: operation.source.bytes,
125            output_path: actual_project_path,
126            preset: operation.preset.clone(),
127            fit: operation.fit.label().to_string(),
128            width: operation.width,
129            height: operation.height,
130            format: operation.format.label().to_string(),
131            bytes: metadata.len(),
132            hash: actual_hash,
133            operation_hash: operation.operation_hash.clone(),
134        });
135    }
136
137    let total_output_bytes = actual_outputs
138        .iter()
139        .map(|output| output.bytes)
140        .sum::<u64>();
141    issues.extend(budget_issues(config, &actual_outputs));
142    let budget_status = budget_status(&issues);
143    let generated_count = actual_outputs.len();
144    let result_manifest = Manifest::new(
145        path_to_string(&config.path),
146        config.config_hash.clone(),
147        actual_outputs,
148    );
149    let mut warnings = plan.warnings;
150    append_unique(&mut warnings, manifest_quality_warnings(&result_manifest));
151    let warning_groups = split_acknowledged_warnings(config, warnings);
152    let result = OptimizeResult {
153        mode: "check".to_string(),
154        source_count: sources.len(),
155        planned_count: plan.operations.len(),
156        generated_count,
157        skipped_count: 0,
158        stale_count: issues.iter().filter(|issue| issue.kind == "stale").count(),
159        source_bytes: unique_source_bytes(&sources),
160        output_bytes: total_output_bytes,
161        warnings: warning_groups.active,
162        acknowledged_warnings: warning_groups.acknowledged,
163        issues,
164        budget_status,
165        manifest: result_manifest,
166    };
167    if options.write_report {
168        write_report(config, &result)?;
169    }
170    Ok(CheckResult {
171        passed: result.issues.is_empty(),
172        result,
173    })
174}
175
176pub(crate) fn validate_output_file(
177    operation: &crate::pipeline::Operation,
178    actual_path: &PathBuf,
179    actual_project_path: &str,
180) -> Option<CheckIssue> {
181    if operation.format == FormatKind::Avif {
182        return validate_avif_container(actual_path)
183            .err()
184            .map(|message| CheckIssue {
185                kind: "invalid_output".to_string(),
186                path: actual_project_path.to_string(),
187                message,
188            });
189    }
190
191    match image::image_dimensions(actual_path) {
192        Ok((width, height)) if width == operation.width && height == operation.height => None,
193        Ok((width, height)) => Some(CheckIssue {
194            kind: "stale".to_string(),
195            path: actual_project_path.to_string(),
196            message: format!(
197                "output dimensions are {}x{}, expected {}x{}",
198                width, height, operation.width, operation.height
199            ),
200        }),
201        Err(source) => Some(CheckIssue {
202            kind: "invalid_output".to_string(),
203            path: actual_project_path.to_string(),
204            message: source.to_string(),
205        }),
206    }
207}
208
209fn manifest_output_path(config: &Config, output: &ManifestOutput) -> Result<PathBuf> {
210    resolve_project_path_checked(
211        config,
212        &PathBuf::from(&output.output_path),
213        "manifest output path",
214    )
215}
216
217fn output_metadata(path: &PathBuf) -> Result<fs::Metadata> {
218    match fs::metadata(path) {
219        Ok(metadata) => Ok(metadata),
220        Err(source) => Err(DevimgError::io(path, source)),
221    }
222}
223
224fn validate_avif_container(path: &PathBuf) -> std::result::Result<(), String> {
225    let bytes = fs::read(path).map_err(|source| source.to_string())?;
226    if bytes.len() <= 16 || &bytes[4..8] != b"ftyp" {
227        return Err("AVIF output is missing the ftyp box".to_string());
228    }
229    if !bytes.windows(4).any(|window| window == b"avif") {
230        return Err("AVIF output is missing the avif brand".to_string());
231    }
232    Ok(())
233}
234
235fn stable_manifest_output<'a>(
236    operation: &crate::pipeline::Operation,
237    manifest_config_hash: &str,
238    by_output: &'a HashMap<&str, &'a ManifestOutput>,
239    issues: &mut Vec<CheckIssue>,
240) -> Option<&'a ManifestOutput> {
241    match by_output.get(operation.output_project_path.as_str()) {
242        Some(manifest_output) => {
243            if !operation_hash_matches(manifest_output, operation, manifest_config_hash) {
244                issues.push(CheckIssue {
245                    kind: "stale".to_string(),
246                    path: operation.output_project_path.clone(),
247                    message: "planned operation no longer matches manifest".to_string(),
248                });
249            }
250            Some(*manifest_output)
251        }
252        None => {
253            issues.push(CheckIssue {
254                kind: "stale".to_string(),
255                path: operation.output_project_path.clone(),
256                message: "planned output is missing from manifest".to_string(),
257            });
258            None
259        }
260    }
261}
262
263fn hashed_manifest_output<'a>(
264    operation: &crate::pipeline::Operation,
265    manifest_config_hash: &str,
266    by_operation_hash: &'a HashMap<&str, Vec<&'a ManifestOutput>>,
267    issues: &mut Vec<CheckIssue>,
268) -> Result<Option<&'a ManifestOutput>> {
269    let legacy_hash = legacy_operation_hash(operation, manifest_config_hash);
270    let Some(outputs) = by_operation_hash
271        .get(operation.operation_hash.as_str())
272        .or_else(|| by_operation_hash.get(legacy_hash.as_str()))
273    else {
274        issues.push(CheckIssue {
275            kind: "stale".to_string(),
276            path: operation.output_project_path.clone(),
277            message: "planned hashed output is missing from manifest".to_string(),
278        });
279        return Ok(None);
280    };
281
282    if outputs.len() > 1 {
283        issues.push(CheckIssue {
284            kind: "stale".to_string(),
285            path: operation.output_project_path.clone(),
286            message: "manifest contains duplicate outputs for one planned operation".to_string(),
287        });
288    }
289
290    let output = outputs[0];
291    let expected_path =
292        final_output_project_path(&operation.output_project_path, &output.hash, operation)?;
293    if output.output_path != expected_path {
294        issues.push(CheckIssue {
295            kind: "stale".to_string(),
296            path: output.output_path.clone(),
297            message: "manifest output path does not match its content hash".to_string(),
298        });
299    }
300
301    Ok(Some(output))
302}
303
304fn operation_hash_matches(
305    output: &ManifestOutput,
306    operation: &crate::pipeline::Operation,
307    manifest_config_hash: &str,
308) -> bool {
309    output.operation_hash == operation.operation_hash
310        || output.operation_hash == legacy_operation_hash(operation, manifest_config_hash)
311}
312
313#[cfg(test)]
314#[path = "check_tests.rs"]
315mod tests;