Skip to main content

devimg_core/
plan.rs

1use std::path::{Path, PathBuf};
2
3use globset::GlobSet;
4
5use crate::config::{
6    project_relative, AspectRatio, Config, FitMode, FormatKind, PresetConfig, PresetOverrideConfig,
7};
8use crate::hash::hash_bytes;
9use crate::pipeline::{path_to_string, Operation, Plan, SourceImage};
10use crate::quality::{
11    allowed_upscale_warning, append_unique, cover_crop_warning, lossy_quality_warnings,
12    skipped_upscale_warning,
13};
14use crate::scan::compile_globs;
15use crate::warnings::{warning_message, PLAN_METADATA_NOT_PRESERVED, PLAN_NO_VARIANTS};
16use crate::{DevimgError, Result};
17
18pub fn build_plan(config: &Config, sources: &[SourceImage]) -> Result<Plan> {
19    let mut operations = Vec::new();
20    let mut warnings = Vec::new();
21    let overrides = compile_overrides(config)?;
22    if !config.project.strip_metadata {
23        warnings.push(warning_message(
24            PLAN_METADATA_NOT_PRESERVED,
25            "strip_metadata=false was requested, but current encoders re-encode images and do not preserve source metadata",
26        ));
27    }
28
29    for source in sources {
30        let mut planned_for_source = 0usize;
31        for preset in &config.presets {
32            let effective_preset = apply_overrides(source, preset, &overrides);
33            for width in &effective_preset.widths {
34                let (target_width, target_height) =
35                    target_dimensions(source.width, source.height, *width, &effective_preset);
36                if !effective_preset.allow_upscale
37                    && (target_width > source.width || target_height > source.height)
38                {
39                    append_unique(
40                        &mut warnings,
41                        [skipped_upscale_warning(
42                            source,
43                            &effective_preset,
44                            *width,
45                            target_width,
46                            target_height,
47                        )],
48                    );
49                    continue;
50                }
51                append_unique(
52                    &mut warnings,
53                    lossy_quality_warnings(source, &effective_preset),
54                );
55                append_unique(
56                    &mut warnings,
57                    allowed_upscale_warning(
58                        source,
59                        &effective_preset,
60                        *width,
61                        target_width,
62                        target_height,
63                    ),
64                );
65                append_unique(
66                    &mut warnings,
67                    cover_crop_warning(
68                        source,
69                        &effective_preset,
70                        *width,
71                        target_width,
72                        target_height,
73                    ),
74                );
75                for format in &effective_preset.formats {
76                    let output_path = output_path_for(source, &effective_preset, *width, *format)?;
77                    if output_path == source.path {
78                        return Err(DevimgError::UnsafeOverwrite { path: output_path });
79                    }
80                    let output_project_path =
81                        path_to_string(&project_relative(config, &output_path));
82                    let op_hash = operation_hash(
83                        source,
84                        &effective_preset,
85                        *format,
86                        target_width,
87                        target_height,
88                        &output_project_path,
89                        OperationHashOptions {
90                            strip_metadata: config.project.strip_metadata,
91                            content_hash_filenames: config.project.content_hash_filenames,
92                        },
93                    );
94                    operations.push(Operation {
95                        source: source.clone(),
96                        preset: effective_preset.name.clone(),
97                        fit: effective_preset.fit,
98                        crop: effective_preset.crop,
99                        quality: effective_preset.quality,
100                        format: *format,
101                        width: target_width,
102                        height: target_height,
103                        strip_metadata: config.project.strip_metadata,
104                        content_hash_filenames: config.project.content_hash_filenames,
105                        output_path,
106                        output_project_path,
107                        operation_hash: op_hash,
108                    });
109                    planned_for_source += 1;
110                }
111            }
112        }
113        if planned_for_source == 0 {
114            warnings.push(warning_message(
115                PLAN_NO_VARIANTS,
116                format!(
117                    "no variants planned for {} after applying presets",
118                    source.project_path
119                ),
120            ));
121        }
122    }
123
124    operations.sort_by(|left, right| left.output_project_path.cmp(&right.output_project_path));
125    Ok(Plan {
126        operations,
127        warnings,
128    })
129}
130
131fn output_path_for(
132    source: &SourceImage,
133    preset: &PresetConfig,
134    width: u32,
135    format: FormatKind,
136) -> Result<PathBuf> {
137    let stem = source
138        .relative_path
139        .file_stem()
140        .ok_or_else(|| DevimgError::image(&source.path, "could not derive file stem"))?
141        .to_string_lossy();
142    let parent = source.relative_path.parent().unwrap_or(Path::new(""));
143    let file_name = format!("{stem}.{}.{}.{}", preset.name, width, format.extension());
144    Ok(source.output_root.join(parent).join(file_name))
145}
146
147fn target_dimensions(
148    source_width: u32,
149    source_height: u32,
150    requested_width: u32,
151    preset: &PresetConfig,
152) -> (u32, u32) {
153    let box_width = requested_width.max(1);
154    let box_height = match preset.aspect_ratio {
155        Some(AspectRatio { width, height }) => {
156            ((u64::from(box_width) * u64::from(height) + u64::from(width / 2)) / u64::from(width))
157                .max(1) as u32
158        }
159        None => ((u64::from(box_width) * u64::from(source_height) + u64::from(source_width / 2))
160            / u64::from(source_width))
161        .max(1) as u32,
162    };
163
164    if preset.fit != FitMode::Contain {
165        return (box_width, box_height);
166    }
167
168    if u64::from(source_width) * u64::from(box_height)
169        >= u64::from(source_height) * u64::from(box_width)
170    {
171        let height = ((u64::from(box_width) * u64::from(source_height)
172            + u64::from(source_width / 2))
173            / u64::from(source_width))
174        .max(1) as u32;
175        (box_width, height)
176    } else {
177        let width = ((u64::from(box_height) * u64::from(source_width)
178            + u64::from(source_height / 2))
179            / u64::from(source_height))
180        .max(1) as u32;
181        (width, box_height)
182    }
183}
184
185fn operation_hash(
186    source: &SourceImage,
187    preset: &PresetConfig,
188    format: FormatKind,
189    width: u32,
190    height: u32,
191    output_path: &str,
192    options: OperationHashOptions,
193) -> String {
194    let mut input = format!(
195        "operation-hash-v2|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}",
196        source.hash,
197        source.project_path,
198        output_path,
199        preset.name,
200        preset.fit.label(),
201        preset.crop.label(),
202        preset.quality,
203        width,
204        height,
205        format.label(),
206        options.strip_metadata,
207    );
208    if let Some(component) = encoder_hash_component(format) {
209        input.push('|');
210        input.push_str(component);
211    }
212    if options.content_hash_filenames {
213        input.push_str("|filename:content-hash-v1");
214    }
215    hash_bytes(input.as_bytes())
216}
217
218#[derive(Debug, Clone, Copy)]
219struct OperationHashOptions {
220    strip_metadata: bool,
221    content_hash_filenames: bool,
222}
223
224pub(crate) fn legacy_operation_hash(operation: &Operation, config_hash: &str) -> String {
225    let mut input = format!(
226        "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}",
227        config_hash,
228        operation.source.hash,
229        operation.source.project_path,
230        operation.output_project_path,
231        operation.preset,
232        operation.fit.label(),
233        operation.crop.label(),
234        operation.quality,
235        operation.width,
236        operation.height,
237        operation.format.label(),
238        operation.strip_metadata,
239    );
240    if let Some(component) = encoder_hash_component(operation.format) {
241        input.push('|');
242        input.push_str(component);
243    }
244    if operation.content_hash_filenames {
245        input.push_str("|filename:content-hash-v1");
246    }
247    hash_bytes(input.as_bytes())
248}
249
250fn encoder_hash_component(format: FormatKind) -> Option<&'static str> {
251    match format {
252        FormatKind::Webp => Some("encoder:webp-libwebp-lossy-v1"),
253        FormatKind::Avif => Some("encoder:ravif-0.13-speed8-v1"),
254        FormatKind::Png | FormatKind::Jpeg => None,
255    }
256}
257
258struct CompiledPresetOverride<'a> {
259    config: &'a PresetOverrideConfig,
260    includes: GlobSet,
261    excludes: GlobSet,
262}
263
264fn compile_overrides(config: &Config) -> Result<Vec<CompiledPresetOverride<'_>>> {
265    config
266        .overrides
267        .iter()
268        .map(|preset_override| {
269            Ok(CompiledPresetOverride {
270                config: preset_override,
271                includes: compile_globs(
272                    &config.path,
273                    "override include",
274                    &preset_override.include,
275                )?,
276                excludes: compile_globs(
277                    &config.path,
278                    "override exclude",
279                    &preset_override.exclude,
280                )?,
281            })
282        })
283        .collect()
284}
285
286fn apply_overrides(
287    source: &SourceImage,
288    preset: &PresetConfig,
289    overrides: &[CompiledPresetOverride<'_>],
290) -> PresetConfig {
291    let mut effective = preset.clone();
292    let relative_path = path_to_string(&source.relative_path);
293    for preset_override in overrides {
294        if !override_matches(preset_override, &relative_path, &preset.name) {
295            continue;
296        }
297        if let Some(quality) = preset_override.config.quality {
298            effective.quality = quality;
299        }
300        if let Some(fit) = preset_override.config.fit {
301            effective.fit = fit;
302        }
303        if let Some(crop) = preset_override.config.crop {
304            effective.crop = crop;
305        }
306        if let Some(allow_upscale) = preset_override.config.allow_upscale {
307            effective.allow_upscale = allow_upscale;
308        }
309    }
310    effective
311}
312
313fn override_matches(
314    preset_override: &CompiledPresetOverride<'_>,
315    relative_path: &str,
316    preset_name: &str,
317) -> bool {
318    if !preset_override.config.presets.is_empty()
319        && !preset_override
320            .config
321            .presets
322            .iter()
323            .any(|candidate| candidate == preset_name)
324    {
325        return false;
326    }
327    if !preset_override.config.include.is_empty()
328        && !preset_override.includes.is_match(relative_path)
329    {
330        return false;
331    }
332    !preset_override.excludes.is_match(relative_path)
333}
334
335pub(crate) fn cover_dimensions(
336    source_width: u32,
337    source_height: u32,
338    target_width: u32,
339    target_height: u32,
340) -> (u32, u32) {
341    let sw = u128::from(source_width);
342    let sh = u128::from(source_height);
343    let tw = u128::from(target_width);
344    let th = u128::from(target_height);
345
346    if sw * th >= sh * tw {
347        let resize_width = (sw * th).div_ceil(sh) as u32;
348        (resize_width, target_height)
349    } else {
350        let resize_height = (sh * tw).div_ceil(sw) as u32;
351        (target_width, resize_height)
352    }
353}
354
355#[cfg(test)]
356#[path = "plan_tests.rs"]
357mod tests;