Skip to main content

devimg_core/
config.rs

1use std::fs;
2use std::path::{Component, Path, PathBuf};
3
4use image::{ImageFormat, ImageOutputFormat};
5use serde::{Deserialize, Deserializer};
6
7use crate::hash::hash_bytes;
8use crate::warnings::{
9    normalize_warning_path, PLAN_NO_VARIANTS, QUALITY_ALLOWED_UPSCALE, QUALITY_COVER_CROP,
10    QUALITY_GENERATED_UPSCALE, QUALITY_LOW_LOSSY, QUALITY_OUTPUT_LARGER_THAN_SOURCE,
11    QUALITY_SKIPPED_UPSCALE,
12};
13use crate::{DevimgError, Result};
14
15#[derive(Debug, Clone)]
16pub struct Config {
17    pub path: PathBuf,
18    pub config_hash: String,
19    pub project: ProjectConfig,
20    pub sources: Vec<SourceConfig>,
21    pub presets: Vec<PresetConfig>,
22    pub overrides: Vec<PresetOverrideConfig>,
23    pub warnings: WarningConfig,
24    pub budgets: BudgetConfig,
25}
26
27#[derive(Debug, Clone)]
28pub struct ProjectConfig {
29    pub root: PathBuf,
30    pub manifest: PathBuf,
31    pub report: PathBuf,
32    pub overwrite: bool,
33    pub strip_metadata: bool,
34    pub content_hash_filenames: bool,
35}
36
37#[derive(Debug, Clone)]
38pub struct SourceConfig {
39    pub name: String,
40    pub input: PathBuf,
41    pub output: PathBuf,
42    pub include: Vec<String>,
43    pub exclude: Vec<String>,
44}
45
46#[derive(Debug, Clone)]
47pub struct PresetConfig {
48    pub name: String,
49    pub widths: Vec<u32>,
50    pub formats: Vec<FormatKind>,
51    pub quality: u8,
52    pub fit: FitMode,
53    pub crop: CropPosition,
54    pub aspect_ratio: Option<AspectRatio>,
55    pub allow_upscale: bool,
56}
57
58#[derive(Debug, Clone)]
59pub struct PresetOverrideConfig {
60    pub include: Vec<String>,
61    pub exclude: Vec<String>,
62    pub presets: Vec<String>,
63    pub quality: Option<u8>,
64    pub fit: Option<FitMode>,
65    pub crop: Option<CropPosition>,
66    pub allow_upscale: Option<bool>,
67}
68
69#[derive(Debug, Clone, Default)]
70pub struct WarningConfig {
71    pub acknowledgements: Vec<WarningAcknowledgementConfig>,
72}
73
74#[derive(Debug, Clone)]
75pub struct WarningAcknowledgementConfig {
76    pub code: String,
77    pub source: Option<String>,
78    pub output: Option<String>,
79    pub preset: Option<String>,
80    pub width: Option<u32>,
81    pub reason: Option<String>,
82}
83
84#[derive(Debug, Clone, Default)]
85pub struct BudgetConfig {
86    pub max_total_bytes: Option<u64>,
87    pub max_file_bytes: Option<u64>,
88    pub fail_on_regression: bool,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92pub enum FitMode {
93    Cover,
94    Contain,
95    Fill,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub struct CropPosition {
100    pub x: f32,
101    pub y: f32,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105pub enum FormatKind {
106    Png,
107    Jpeg,
108    Webp,
109    Avif,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub struct AspectRatio {
114    pub width: u32,
115    pub height: u32,
116}
117
118impl FormatKind {
119    pub fn parse(raw: &str) -> Option<Self> {
120        match raw
121            .trim()
122            .trim_start_matches('.')
123            .to_ascii_lowercase()
124            .as_str()
125        {
126            "png" => Some(Self::Png),
127            "jpg" | "jpeg" => Some(Self::Jpeg),
128            "webp" => Some(Self::Webp),
129            "avif" => Some(Self::Avif),
130            _ => None,
131        }
132    }
133
134    pub fn extension(self) -> &'static str {
135        match self {
136            Self::Png => "png",
137            Self::Jpeg => "jpeg",
138            Self::Webp => "webp",
139            Self::Avif => "avif",
140        }
141    }
142
143    pub fn label(self) -> &'static str {
144        match self {
145            Self::Png => "png",
146            Self::Jpeg => "jpeg",
147            Self::Webp => "webp",
148            Self::Avif => "avif",
149        }
150    }
151
152    pub fn image_format(self) -> ImageFormat {
153        match self {
154            Self::Png => ImageFormat::Png,
155            Self::Jpeg => ImageFormat::Jpeg,
156            Self::Webp => ImageFormat::WebP,
157            Self::Avif => ImageFormat::Avif,
158        }
159    }
160
161    pub fn output_format(self, quality: u8) -> ImageOutputFormat {
162        match self {
163            Self::Png => ImageOutputFormat::Png,
164            Self::Jpeg => ImageOutputFormat::Jpeg(quality),
165            Self::Webp => ImageOutputFormat::WebP,
166            Self::Avif => unreachable!("AVIF output uses the ravif encoder"),
167        }
168    }
169
170    pub fn supports_source_input(self) -> bool {
171        match self {
172            Self::Png | Self::Jpeg | Self::Webp => true,
173            Self::Avif => false,
174        }
175    }
176}
177
178impl<'de> Deserialize<'de> for FormatKind {
179    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
180    where
181        D: Deserializer<'de>,
182    {
183        let raw = String::deserialize(deserializer)?;
184        Self::parse(&raw)
185            .ok_or_else(|| serde::de::Error::custom(format!("unsupported image format `{raw}`")))
186    }
187}
188
189impl FitMode {
190    fn parse(raw: &str) -> Option<Self> {
191        match raw.trim().to_ascii_lowercase().as_str() {
192            "cover" | "crop" => Some(Self::Cover),
193            "contain" => Some(Self::Contain),
194            "fill" | "stretch" => Some(Self::Fill),
195            _ => None,
196        }
197    }
198
199    pub fn label(self) -> &'static str {
200        match self {
201            Self::Cover => "cover",
202            Self::Contain => "contain",
203            Self::Fill => "fill",
204        }
205    }
206}
207
208impl<'de> Deserialize<'de> for FitMode {
209    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
210    where
211        D: Deserializer<'de>,
212    {
213        let raw = String::deserialize(deserializer)?;
214        Self::parse(&raw)
215            .ok_or_else(|| serde::de::Error::custom(format!("unsupported fit `{raw}`")))
216    }
217}
218
219impl Default for CropPosition {
220    fn default() -> Self {
221        Self::CENTER
222    }
223}
224
225impl CropPosition {
226    pub const CENTER: Self = Self { x: 0.5, y: 0.5 };
227
228    pub fn label(self) -> String {
229        format!("crop:{:.4}:{:.4}", self.x, self.y)
230    }
231
232    fn parse_anchor(raw: &str) -> Option<Self> {
233        match normalize_crop_anchor(raw).as_str() {
234            "center" => Some(Self::CENTER),
235            "top" => Some(Self { x: 0.5, y: 0.0 }),
236            "bottom" => Some(Self { x: 0.5, y: 1.0 }),
237            "left" => Some(Self { x: 0.0, y: 0.5 }),
238            "right" => Some(Self { x: 1.0, y: 0.5 }),
239            "top-left" => Some(Self { x: 0.0, y: 0.0 }),
240            "top-right" => Some(Self { x: 1.0, y: 0.0 }),
241            "bottom-left" => Some(Self { x: 0.0, y: 1.0 }),
242            "bottom-right" => Some(Self { x: 1.0, y: 1.0 }),
243            _ => None,
244        }
245    }
246
247    fn new(x: f32, y: f32) -> std::result::Result<Self, String> {
248        if !x.is_finite() || !y.is_finite() {
249            return Err("crop x and y must be finite numbers".to_string());
250        }
251        if !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) {
252            return Err("crop x and y must be between 0.0 and 1.0".to_string());
253        }
254        Ok(Self { x, y })
255    }
256}
257
258fn normalize_crop_anchor(raw: &str) -> String {
259    raw.trim().to_ascii_lowercase().replace(['_', ' '], "-")
260}
261
262impl<'de> Deserialize<'de> for CropPosition {
263    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
264    where
265        D: Deserializer<'de>,
266    {
267        #[derive(Deserialize)]
268        #[serde(untagged)]
269        enum CropValue {
270            Anchor(String),
271            Point(CropPoint),
272        }
273
274        #[derive(Deserialize)]
275        struct CropPoint {
276            x: f32,
277            y: f32,
278        }
279
280        match CropValue::deserialize(deserializer)? {
281            CropValue::Anchor(raw) => Self::parse_anchor(&raw)
282                .ok_or_else(|| serde::de::Error::custom(format!("unsupported crop `{raw}`"))),
283            CropValue::Point(point) => {
284                Self::new(point.x, point.y).map_err(serde::de::Error::custom)
285            }
286        }
287    }
288}
289
290impl AspectRatio {
291    fn parse(raw: &str) -> Option<Self> {
292        let (left, right) = raw.trim().split_once(':')?;
293        let width = left.trim().parse::<u32>().ok()?;
294        let height = right.trim().parse::<u32>().ok()?;
295        if width == 0 || height == 0 {
296            return None;
297        }
298        Some(Self { width, height })
299    }
300}
301
302impl<'de> Deserialize<'de> for AspectRatio {
303    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
304    where
305        D: Deserializer<'de>,
306    {
307        let raw = String::deserialize(deserializer)?;
308        Self::parse(&raw)
309            .ok_or_else(|| serde::de::Error::custom(format!("invalid aspect_ratio `{raw}`")))
310    }
311}
312
313pub fn load_config(path: impl AsRef<Path>) -> Result<Config> {
314    let path = path.as_ref();
315    let raw = fs::read_to_string(path).map_err(|source| {
316        if source.kind() == std::io::ErrorKind::NotFound {
317            DevimgError::config(path, "config file not found")
318        } else {
319            DevimgError::io(path, source)
320        }
321    })?;
322    parse_config(path, &raw)
323}
324
325pub fn parse_config(path: &Path, raw: &str) -> Result<Config> {
326    let value: toml::Value = toml::from_str(raw)
327        .map_err(|source| DevimgError::config(path, format!("invalid TOML: {source}")))?;
328    reject_unknown_top_level(path, &value)?;
329    let parsed: RawConfig = value
330        .try_into()
331        .map_err(|source| DevimgError::config(path, format!("invalid config: {source}")))?;
332    parsed.into_config(path, raw)
333}
334
335pub(crate) fn resolve_project_path(config: &Config, path: &Path) -> PathBuf {
336    if path.is_absolute() {
337        normalize_path(path)
338    } else {
339        normalize_path(&config.project.root.join(path))
340    }
341}
342
343pub(crate) fn resolve_project_path_checked(
344    config: &Config,
345    path: &Path,
346    label: &str,
347) -> Result<PathBuf> {
348    let resolved = resolve_project_path(config, path);
349    if config.project.root.as_os_str().is_empty() || resolved.starts_with(&config.project.root) {
350        Ok(resolved)
351    } else {
352        Err(DevimgError::config(
353            &config.path,
354            format!("{label} escapes project root: {}", resolved.display()),
355        ))
356    }
357}
358
359pub(crate) fn project_relative(config: &Config, path: &Path) -> PathBuf {
360    let normalized = normalize_path(path);
361    normalized
362        .strip_prefix(&config.project.root)
363        .map(Path::to_path_buf)
364        .unwrap_or(normalized)
365}
366
367pub(crate) fn normalize_path(path: &Path) -> PathBuf {
368    let mut normalized = PathBuf::new();
369    for component in path.components() {
370        match component {
371            Component::CurDir => {}
372            Component::ParentDir => {
373                normalized.pop();
374            }
375            Component::Normal(part) => normalized.push(part),
376            Component::RootDir => normalized.push(component.as_os_str()),
377            Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
378        }
379    }
380    normalized
381}
382
383#[derive(Debug, Deserialize, Default)]
384#[serde(default)]
385struct RawConfig {
386    project: RawProjectConfig,
387    #[serde(alias = "source")]
388    sources: Vec<RawSourceConfig>,
389    #[serde(alias = "presets")]
390    preset: Vec<RawPresetConfig>,
391    #[serde(alias = "override")]
392    overrides: Vec<RawPresetOverrideConfig>,
393    warnings: RawWarningsConfig,
394    budgets: RawBudgetConfig,
395}
396
397impl RawConfig {
398    fn into_config(self, path: &Path, raw: &str) -> Result<Config> {
399        let config_dir = path.parent().unwrap_or_else(|| Path::new("."));
400        let root_raw = self.project.root.unwrap_or_else(|| PathBuf::from("."));
401        let root = normalize_path(&config_dir.join(root_raw));
402        let manifest = self
403            .project
404            .manifest
405            .ok_or_else(|| DevimgError::config(path, "missing [project].manifest"))?;
406        let report = self
407            .project
408            .report
409            .unwrap_or_else(|| PathBuf::from("devimg-report.md"));
410
411        let mut sources = Vec::new();
412        for source in self.sources {
413            sources.push(SourceConfig {
414                name: required(source.name, path, "source.name")?,
415                input: required(source.input, path, "source.input")?,
416                output: required(source.output, path, "source.output")?,
417                include: source.include,
418                exclude: source.exclude,
419            });
420        }
421
422        let mut presets = Vec::new();
423        for preset in self.preset {
424            let widths = required(preset.widths, path, "preset.widths")?;
425            if widths.is_empty() {
426                return Err(DevimgError::config(path, "preset.widths cannot be empty"));
427            }
428            let formats = required(preset.formats, path, "preset.formats")?;
429            if formats.is_empty() {
430                return Err(DevimgError::config(path, "preset.formats cannot be empty"));
431            }
432            let quality = preset.quality.unwrap_or(82);
433            if quality > 100 {
434                return Err(DevimgError::config(path, "quality must be 0-100"));
435            }
436            presets.push(PresetConfig {
437                name: required(preset.name, path, "preset.name")?,
438                widths,
439                formats,
440                quality,
441                fit: preset.fit.unwrap_or(FitMode::Cover),
442                crop: preset.crop.unwrap_or_default(),
443                aspect_ratio: preset.aspect_ratio,
444                allow_upscale: preset.allow_upscale.unwrap_or(false),
445            });
446        }
447
448        let mut overrides = Vec::new();
449        for preset_override in self.overrides {
450            let quality = preset_override.quality;
451            if quality.is_some_and(|quality| quality > 100) {
452                return Err(DevimgError::config(path, "override quality must be 0-100"));
453            }
454            overrides.push(PresetOverrideConfig {
455                include: preset_override.include,
456                exclude: preset_override.exclude,
457                presets: preset_override.presets,
458                quality,
459                fit: preset_override.fit,
460                crop: preset_override.crop,
461                allow_upscale: preset_override.allow_upscale,
462            });
463        }
464
465        if sources.is_empty() {
466            return Err(DevimgError::config(
467                path,
468                "at least one [[sources]] entry is required",
469            ));
470        }
471        if presets.is_empty() {
472            return Err(DevimgError::config(
473                path,
474                "at least one [[preset]] entry is required",
475            ));
476        }
477
478        let warnings = warning_config_from_raw(path, self.warnings)?;
479
480        Ok(Config {
481            path: normalize_path(path),
482            config_hash: hash_bytes(raw.as_bytes()),
483            project: ProjectConfig {
484                root,
485                manifest,
486                report,
487                overwrite: self.project.overwrite.unwrap_or(false),
488                strip_metadata: self.project.strip_metadata.unwrap_or(true),
489                content_hash_filenames: self.project.content_hash_filenames.unwrap_or(false),
490            },
491            sources,
492            presets,
493            overrides,
494            warnings,
495            budgets: BudgetConfig {
496                max_total_bytes: self.budgets.max_total_bytes,
497                max_file_bytes: self.budgets.max_file_bytes,
498                fail_on_regression: self.budgets.fail_on_regression,
499            },
500        })
501    }
502}
503
504#[derive(Debug, Deserialize, Default)]
505#[serde(default)]
506struct RawProjectConfig {
507    root: Option<PathBuf>,
508    manifest: Option<PathBuf>,
509    report: Option<PathBuf>,
510    #[serde(alias = "allow_overwrite")]
511    overwrite: Option<bool>,
512    strip_metadata: Option<bool>,
513    #[serde(alias = "hash_filenames", alias = "hashed_filenames")]
514    content_hash_filenames: Option<bool>,
515}
516
517#[derive(Debug, Deserialize, Default)]
518#[serde(default)]
519struct RawSourceConfig {
520    name: Option<String>,
521    input: Option<PathBuf>,
522    output: Option<PathBuf>,
523    include: Vec<String>,
524    exclude: Vec<String>,
525}
526
527#[derive(Debug, Deserialize, Default)]
528#[serde(default)]
529struct RawPresetConfig {
530    name: Option<String>,
531    widths: Option<Vec<u32>>,
532    formats: Option<Vec<FormatKind>>,
533    quality: Option<u8>,
534    fit: Option<FitMode>,
535    #[serde(alias = "crop_anchor", alias = "crop_position", alias = "focal_point")]
536    crop: Option<CropPosition>,
537    aspect_ratio: Option<AspectRatio>,
538    #[serde(alias = "upscale")]
539    allow_upscale: Option<bool>,
540}
541
542#[derive(Debug, Deserialize, Default)]
543#[serde(default)]
544struct RawPresetOverrideConfig {
545    include: Vec<String>,
546    exclude: Vec<String>,
547    presets: Vec<String>,
548    quality: Option<u8>,
549    fit: Option<FitMode>,
550    #[serde(alias = "crop_anchor", alias = "crop_position", alias = "focal_point")]
551    crop: Option<CropPosition>,
552    #[serde(alias = "upscale")]
553    allow_upscale: Option<bool>,
554}
555
556#[derive(Debug, Deserialize, Default)]
557#[serde(default)]
558struct RawWarningsConfig {
559    #[serde(
560        alias = "acknowledgement",
561        alias = "acknowledgments",
562        alias = "acknowledgements"
563    )]
564    acknowledge: Vec<RawWarningAcknowledgementConfig>,
565}
566
567#[derive(Debug, Deserialize, Default)]
568#[serde(default)]
569struct RawWarningAcknowledgementConfig {
570    code: Option<String>,
571    source: Option<String>,
572    output: Option<String>,
573    preset: Option<String>,
574    width: Option<u32>,
575    reason: Option<String>,
576}
577
578#[derive(Debug, Deserialize, Default)]
579#[serde(default)]
580struct RawBudgetConfig {
581    #[serde(default, deserialize_with = "deserialize_optional_byte_size")]
582    max_total_bytes: Option<u64>,
583    #[serde(default, deserialize_with = "deserialize_optional_byte_size")]
584    max_file_bytes: Option<u64>,
585    fail_on_regression: bool,
586}
587
588#[derive(Debug, Deserialize)]
589#[serde(untagged)]
590enum ByteSizeValue {
591    Text(String),
592    Number(u64),
593}
594
595fn deserialize_optional_byte_size<'de, D>(
596    deserializer: D,
597) -> std::result::Result<Option<u64>, D::Error>
598where
599    D: Deserializer<'de>,
600{
601    let value = Option::<ByteSizeValue>::deserialize(deserializer)?;
602    value.map(parse_byte_size_value).transpose()
603}
604
605fn parse_byte_size_value<E>(value: ByteSizeValue) -> std::result::Result<u64, E>
606where
607    E: serde::de::Error,
608{
609    match value {
610        ByteSizeValue::Number(bytes) => Ok(bytes),
611        ByteSizeValue::Text(raw) => parse_byte_size(&raw).map_err(E::custom),
612    }
613}
614
615fn parse_byte_size(raw: &str) -> std::result::Result<u64, String> {
616    let value = raw.trim().to_ascii_lowercase();
617    let split = value
618        .find(|ch: char| !ch.is_ascii_digit())
619        .unwrap_or(value.len());
620    let (number, unit) = value.split_at(split);
621    if number.is_empty() {
622        return Err(format!("invalid byte size `{raw}`"));
623    }
624    let base = number
625        .parse::<u64>()
626        .map_err(|_| format!("invalid byte size `{raw}`"))?;
627    let multiplier = match unit.trim() {
628        "" | "b" => 1,
629        "kb" | "kib" => 1024,
630        "mb" | "mib" => 1024 * 1024,
631        "gb" | "gib" => 1024 * 1024 * 1024,
632        _ => return Err(format!("invalid byte size unit `{unit}`")),
633    };
634    Ok(base * multiplier)
635}
636
637fn required<T>(value: Option<T>, path: &Path, field: &str) -> Result<T> {
638    value.ok_or_else(|| DevimgError::config(path, format!("missing {field}")))
639}
640
641fn warning_config_from_raw(path: &Path, raw: RawWarningsConfig) -> Result<WarningConfig> {
642    let mut acknowledgements = Vec::new();
643    for acknowledgement in raw.acknowledge {
644        let code = required_trimmed(acknowledgement.code, path, "warnings.acknowledge.code")?;
645        let source = optional_trimmed_path(acknowledgement.source);
646        let output = optional_trimmed_path(acknowledgement.output);
647        let preset = optional_trimmed(acknowledgement.preset);
648        let reason = optional_trimmed(acknowledgement.reason);
649        let has_scope = source.is_some()
650            || output.is_some()
651            || preset.is_some()
652            || acknowledgement.width.is_some();
653        if !has_scope {
654            return Err(DevimgError::config(
655                path,
656                "warnings.acknowledge requires at least one of source, output, preset, or width",
657            ));
658        }
659        if warning_acknowledgement_requires_source_and_preset(&code)
660            && (source.is_none() || preset.is_none())
661        {
662            return Err(DevimgError::config(
663                path,
664                format!("{code} acknowledgements require source and preset"),
665            ));
666        }
667        if warning_acknowledgement_requires_output(&code) && output.is_none() {
668            return Err(DevimgError::config(
669                path,
670                format!("{code} acknowledgements require output"),
671            ));
672        }
673        if warning_acknowledgement_requires_source(&code) && source.is_none() {
674            return Err(DevimgError::config(
675                path,
676                format!("{code} acknowledgements require source"),
677            ));
678        }
679        acknowledgements.push(WarningAcknowledgementConfig {
680            code,
681            source,
682            output,
683            preset,
684            width: acknowledgement.width,
685            reason,
686        });
687    }
688    Ok(WarningConfig { acknowledgements })
689}
690
691fn required_trimmed(value: Option<String>, path: &Path, field: &str) -> Result<String> {
692    optional_trimmed(value).ok_or_else(|| DevimgError::config(path, format!("missing {field}")))
693}
694
695fn optional_trimmed(value: Option<String>) -> Option<String> {
696    value
697        .map(|value| value.trim().to_string())
698        .filter(|value| !value.is_empty())
699}
700
701fn optional_trimmed_path(value: Option<String>) -> Option<String> {
702    optional_trimmed(value).map(|value| normalize_warning_path(&value))
703}
704
705fn warning_acknowledgement_requires_source_and_preset(code: &str) -> bool {
706    matches!(
707        code,
708        QUALITY_LOW_LOSSY | QUALITY_SKIPPED_UPSCALE | QUALITY_ALLOWED_UPSCALE | QUALITY_COVER_CROP
709    )
710}
711
712fn warning_acknowledgement_requires_source(code: &str) -> bool {
713    matches!(code, PLAN_NO_VARIANTS)
714}
715
716fn warning_acknowledgement_requires_output(code: &str) -> bool {
717    matches!(
718        code,
719        QUALITY_GENERATED_UPSCALE | QUALITY_OUTPUT_LARGER_THAN_SOURCE
720    )
721}
722
723fn reject_unknown_top_level(path: &Path, value: &toml::Value) -> Result<()> {
724    let Some(table) = value.as_table() else {
725        return Err(DevimgError::config(
726            path,
727            "config root must be a TOML table",
728        ));
729    };
730    for key in table.keys() {
731        if !matches!(
732            key.as_str(),
733            "project"
734                | "sources"
735                | "source"
736                | "preset"
737                | "presets"
738                | "overrides"
739                | "override"
740                | "warnings"
741                | "budgets"
742        ) {
743            return Err(DevimgError::config(
744                path,
745                format!("unsupported top-level section or key `{key}`"),
746            ));
747        }
748    }
749    Ok(())
750}
751
752#[cfg(test)]
753mod tests {
754    use std::path::Path;
755
756    use super::{parse_config, CropPosition, FitMode, FormatKind};
757
758    #[test]
759    fn parses_minimal_config() {
760        let raw = r#"
761[project]
762root = "."
763manifest = "public/images/devimg-manifest.json"
764report = "devimg-report.md"
765
766[[sources]]
767name = "portfolio"
768input = "assets/images"
769output = "public/images/generated"
770include = ["**/*.png", "**/*.jpg"]
771
772[[preset]]
773name = "project-card"
774widths = [640, 960]
775formats = ["webp", "jpeg"]
776quality = 82
777fit = "cover"
778aspect_ratio = "16:9"
779
780[budgets]
781max_total_bytes = "3mb"
782max_file_bytes = "350kb"
783fail_on_regression = true
784"#;
785        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
786        assert_eq!(config.sources[0].name, "portfolio");
787        assert_eq!(
788            config.presets[0].formats,
789            vec![FormatKind::Webp, FormatKind::Jpeg]
790        );
791        assert_eq!(config.presets[0].fit, FitMode::Cover);
792        assert_eq!(config.presets[0].crop, CropPosition::CENTER);
793        assert_eq!(config.budgets.max_file_bytes, Some(350 * 1024));
794    }
795
796    #[test]
797    fn supports_aliases_and_defaults() {
798        let raw = r#"
799[project]
800manifest = "public/images/devimg-manifest.json"
801allow_overwrite = true
802
803[[source]]
804name = "portfolio"
805input = "assets/images"
806output = "public/images/generated"
807
808[[presets]]
809name = "project-card"
810widths = [640]
811formats = ["jpg"]
812upscale = true
813"#;
814        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
815        assert!(config.project.overwrite);
816        assert!(!config.project.content_hash_filenames);
817        assert!(config.presets[0].allow_upscale);
818        assert_eq!(config.presets[0].quality, 82);
819        assert_eq!(config.presets[0].formats, vec![FormatKind::Jpeg]);
820    }
821
822    #[test]
823    fn parses_avif_as_output_only_format() {
824        let raw = r#"
825[project]
826manifest = "public/images/devimg-manifest.json"
827
828[[sources]]
829name = "portfolio"
830input = "assets/images"
831output = "public/images/generated"
832
833[[preset]]
834name = "project-card"
835widths = [640]
836formats = ["webp", "avif"]
837"#;
838        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
839
840        assert_eq!(
841            config.presets[0].formats,
842            vec![FormatKind::Webp, FormatKind::Avif]
843        );
844        assert!(FormatKind::Webp.supports_source_input());
845        assert!(!FormatKind::Avif.supports_source_input());
846    }
847
848    #[test]
849    fn parses_crop_anchor() {
850        let raw = r#"
851[project]
852manifest = "public/images/devimg-manifest.json"
853
854[[sources]]
855name = "portfolio"
856input = "assets/images"
857output = "public/images/generated"
858
859[[preset]]
860name = "project-card"
861widths = [640]
862formats = ["webp"]
863crop = "top-right"
864"#;
865        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
866
867        assert_eq!(config.presets[0].crop, CropPosition { x: 1.0, y: 0.0 });
868    }
869
870    #[test]
871    fn parses_crop_focal_point() {
872        let raw = r#"
873[project]
874manifest = "public/images/devimg-manifest.json"
875
876[[sources]]
877name = "portfolio"
878input = "assets/images"
879output = "public/images/generated"
880
881[[preset]]
882name = "project-card"
883widths = [640]
884formats = ["webp"]
885crop = { x = 0.5, y = 0.0 }
886"#;
887        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
888
889        assert_eq!(config.presets[0].crop, CropPosition { x: 0.5, y: 0.0 });
890    }
891
892    #[test]
893    fn rejects_invalid_crop_focal_point() {
894        let raw = r#"
895[project]
896manifest = "public/images/devimg-manifest.json"
897
898[[sources]]
899name = "portfolio"
900input = "assets/images"
901output = "public/images/generated"
902
903[[preset]]
904name = "project-card"
905widths = [640]
906formats = ["webp"]
907crop = { x = 0.5, y = 1.5 }
908"#;
909        let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
910
911        assert!(error.to_string().contains("crop x and y"));
912    }
913
914    #[test]
915    fn parses_content_hash_filename_alias() {
916        let raw = r#"
917[project]
918manifest = "public/images/devimg-manifest.json"
919hash_filenames = true
920
921[[sources]]
922name = "portfolio"
923input = "assets/images"
924output = "public/images/generated"
925
926[[preset]]
927name = "project-card"
928widths = [640]
929formats = ["webp"]
930"#;
931        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
932
933        assert!(config.project.content_hash_filenames);
934    }
935
936    #[test]
937    fn parses_preset_overrides() {
938        let raw = r#"
939[project]
940manifest = "public/images/devimg-manifest.json"
941
942[[sources]]
943name = "portfolio"
944input = "assets/images"
945output = "public/images/generated"
946
947[[preset]]
948name = "project-card"
949widths = [640]
950formats = ["webp"]
951
952[[overrides]]
953include = ["cli_tools.png"]
954presets = ["project-card"]
955quality = 74
956fit = "contain"
957crop = "top"
958upscale = true
959"#;
960        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
961
962        assert_eq!(config.overrides.len(), 1);
963        assert_eq!(config.overrides[0].include, vec!["cli_tools.png"]);
964        assert_eq!(config.overrides[0].presets, vec!["project-card"]);
965        assert_eq!(config.overrides[0].quality, Some(74));
966        assert_eq!(config.overrides[0].fit, Some(FitMode::Contain));
967        assert_eq!(
968            config.overrides[0].crop,
969            Some(CropPosition { x: 0.5, y: 0.0 })
970        );
971        assert_eq!(config.overrides[0].allow_upscale, Some(true));
972    }
973
974    #[test]
975    fn parses_scoped_warning_acknowledgements() {
976        let raw = r#"
977[project]
978manifest = "public/images/devimg-manifest.json"
979
980[[sources]]
981name = "portfolio"
982input = "assets/images"
983output = "public/images/generated"
984
985[[preset]]
986name = "project-card"
987widths = [640]
988formats = ["webp"]
989
990[[warnings.acknowledge]]
991code = "quality:cover-crop"
992source = "./assets/images/accesstrace.png"
993preset = "project-card"
994reason = "Intentional social-card framing."
995"#;
996        let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
997
998        assert_eq!(config.warnings.acknowledgements.len(), 1);
999        let acknowledgement = &config.warnings.acknowledgements[0];
1000        assert_eq!(acknowledgement.code, "quality:cover-crop");
1001        assert_eq!(
1002            acknowledgement.source.as_deref(),
1003            Some("assets/images/accesstrace.png")
1004        );
1005        assert_eq!(acknowledgement.preset.as_deref(), Some("project-card"));
1006        assert_eq!(
1007            acknowledgement.reason.as_deref(),
1008            Some("Intentional social-card framing.")
1009        );
1010    }
1011
1012    #[test]
1013    fn rejects_broad_cover_crop_warning_acknowledgements() {
1014        let raw = r#"
1015[project]
1016manifest = "public/images/devimg-manifest.json"
1017
1018[[sources]]
1019name = "portfolio"
1020input = "assets/images"
1021output = "public/images/generated"
1022
1023[[preset]]
1024name = "project-card"
1025widths = [640]
1026formats = ["webp"]
1027
1028[[warnings.acknowledge]]
1029code = "quality:cover-crop"
1030preset = "project-card"
1031"#;
1032        let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
1033
1034        assert!(error.to_string().contains("source and preset"));
1035    }
1036
1037    #[test]
1038    fn rejects_invalid_override_quality() {
1039        let raw = r#"
1040[project]
1041manifest = "public/images/devimg-manifest.json"
1042
1043[[sources]]
1044name = "portfolio"
1045input = "assets/images"
1046output = "public/images/generated"
1047
1048[[preset]]
1049name = "project-card"
1050widths = [640]
1051formats = ["webp"]
1052
1053[[overrides]]
1054include = ["card.png"]
1055quality = 101
1056"#;
1057        let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
1058
1059        assert!(error.to_string().contains("override quality"));
1060    }
1061
1062    #[test]
1063    fn rejects_unknown_top_level_sections() {
1064        let raw = r#"
1065[project]
1066manifest = "public/images/devimg-manifest.json"
1067
1068[unknown]
1069value = true
1070
1071[[sources]]
1072name = "portfolio"
1073input = "assets/images"
1074output = "public/images/generated"
1075
1076[[preset]]
1077name = "project-card"
1078widths = [640]
1079formats = ["webp"]
1080"#;
1081        let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
1082        assert!(error.to_string().contains("unsupported top-level"));
1083    }
1084}