Skip to main content

devimg_core/
config.rs

1use std::fs;
2use std::path::{Component, Path, PathBuf};
3
4use image::ImageFormat;
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 supports_source_input(self) -> bool {
162        match self {
163            Self::Png | Self::Jpeg | Self::Webp => true,
164            Self::Avif => false,
165        }
166    }
167}
168
169impl<'de> Deserialize<'de> for FormatKind {
170    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
171    where
172        D: Deserializer<'de>,
173    {
174        let raw = String::deserialize(deserializer)?;
175        Self::parse(&raw)
176            .ok_or_else(|| serde::de::Error::custom(format!("unsupported image format `{raw}`")))
177    }
178}
179
180impl FitMode {
181    fn parse(raw: &str) -> Option<Self> {
182        match raw.trim().to_ascii_lowercase().as_str() {
183            "cover" | "crop" => Some(Self::Cover),
184            "contain" => Some(Self::Contain),
185            "fill" | "stretch" => Some(Self::Fill),
186            _ => None,
187        }
188    }
189
190    pub fn label(self) -> &'static str {
191        match self {
192            Self::Cover => "cover",
193            Self::Contain => "contain",
194            Self::Fill => "fill",
195        }
196    }
197}
198
199impl<'de> Deserialize<'de> for FitMode {
200    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
201    where
202        D: Deserializer<'de>,
203    {
204        let raw = String::deserialize(deserializer)?;
205        Self::parse(&raw)
206            .ok_or_else(|| serde::de::Error::custom(format!("unsupported fit `{raw}`")))
207    }
208}
209
210impl Default for CropPosition {
211    fn default() -> Self {
212        Self::CENTER
213    }
214}
215
216impl CropPosition {
217    pub const CENTER: Self = Self { x: 0.5, y: 0.5 };
218
219    pub fn label(self) -> String {
220        format!("crop:{:.4}:{:.4}", self.x, self.y)
221    }
222
223    fn parse_anchor(raw: &str) -> Option<Self> {
224        match normalize_crop_anchor(raw).as_str() {
225            "center" => Some(Self::CENTER),
226            "top" => Some(Self { x: 0.5, y: 0.0 }),
227            "bottom" => Some(Self { x: 0.5, y: 1.0 }),
228            "left" => Some(Self { x: 0.0, y: 0.5 }),
229            "right" => Some(Self { x: 1.0, y: 0.5 }),
230            "top-left" => Some(Self { x: 0.0, y: 0.0 }),
231            "top-right" => Some(Self { x: 1.0, y: 0.0 }),
232            "bottom-left" => Some(Self { x: 0.0, y: 1.0 }),
233            "bottom-right" => Some(Self { x: 1.0, y: 1.0 }),
234            _ => None,
235        }
236    }
237
238    fn new(x: f32, y: f32) -> std::result::Result<Self, String> {
239        if !x.is_finite() || !y.is_finite() {
240            return Err("crop x and y must be finite numbers".to_string());
241        }
242        if !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) {
243            return Err("crop x and y must be between 0.0 and 1.0".to_string());
244        }
245        Ok(Self { x, y })
246    }
247}
248
249fn normalize_crop_anchor(raw: &str) -> String {
250    raw.trim().to_ascii_lowercase().replace(['_', ' '], "-")
251}
252
253impl<'de> Deserialize<'de> for CropPosition {
254    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
255    where
256        D: Deserializer<'de>,
257    {
258        #[derive(Deserialize)]
259        #[serde(untagged)]
260        enum CropValue {
261            Anchor(String),
262            Point(CropPoint),
263        }
264
265        #[derive(Deserialize)]
266        struct CropPoint {
267            x: f32,
268            y: f32,
269        }
270
271        match CropValue::deserialize(deserializer)? {
272            CropValue::Anchor(raw) => Self::parse_anchor(&raw)
273                .ok_or_else(|| serde::de::Error::custom(format!("unsupported crop `{raw}`"))),
274            CropValue::Point(point) => {
275                Self::new(point.x, point.y).map_err(serde::de::Error::custom)
276            }
277        }
278    }
279}
280
281impl AspectRatio {
282    fn parse(raw: &str) -> Option<Self> {
283        let (left, right) = raw.trim().split_once(':')?;
284        let width = left.trim().parse::<u32>().ok()?;
285        let height = right.trim().parse::<u32>().ok()?;
286        if width == 0 || height == 0 {
287            return None;
288        }
289        Some(Self { width, height })
290    }
291}
292
293impl<'de> Deserialize<'de> for AspectRatio {
294    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
295    where
296        D: Deserializer<'de>,
297    {
298        let raw = String::deserialize(deserializer)?;
299        Self::parse(&raw)
300            .ok_or_else(|| serde::de::Error::custom(format!("invalid aspect_ratio `{raw}`")))
301    }
302}
303
304pub fn load_config(path: impl AsRef<Path>) -> Result<Config> {
305    let path = path.as_ref();
306    let raw = fs::read_to_string(path).map_err(|source| {
307        if source.kind() == std::io::ErrorKind::NotFound {
308            DevimgError::config(path, "config file not found")
309        } else {
310            DevimgError::io(path, source)
311        }
312    })?;
313    parse_config(path, &raw)
314}
315
316pub fn parse_config(path: &Path, raw: &str) -> Result<Config> {
317    let value: toml::Value = toml::from_str(raw)
318        .map_err(|source| DevimgError::config(path, format!("invalid TOML: {source}")))?;
319    reject_unknown_top_level(path, &value)?;
320    let parsed: RawConfig = value
321        .try_into()
322        .map_err(|source| DevimgError::config(path, format!("invalid config: {source}")))?;
323    parsed.into_config(path, raw)
324}
325
326pub(crate) fn resolve_project_path(config: &Config, path: &Path) -> PathBuf {
327    if path.is_absolute() {
328        normalize_path(path)
329    } else {
330        normalize_path(&config.project.root.join(path))
331    }
332}
333
334pub(crate) fn resolve_project_path_checked(
335    config: &Config,
336    path: &Path,
337    label: &str,
338) -> Result<PathBuf> {
339    let resolved = resolve_project_path(config, path);
340    if config.project.root.as_os_str().is_empty() || resolved.starts_with(&config.project.root) {
341        Ok(resolved)
342    } else {
343        Err(DevimgError::config(
344            &config.path,
345            format!("{label} escapes project root: {}", resolved.display()),
346        ))
347    }
348}
349
350pub(crate) fn project_relative(config: &Config, path: &Path) -> PathBuf {
351    let normalized = normalize_path(path);
352    normalized
353        .strip_prefix(&config.project.root)
354        .map(Path::to_path_buf)
355        .unwrap_or(normalized)
356}
357
358pub(crate) fn normalize_path(path: &Path) -> PathBuf {
359    let mut normalized = PathBuf::new();
360    for component in path.components() {
361        match component {
362            Component::CurDir => {}
363            Component::ParentDir => {
364                normalized.pop();
365            }
366            Component::Normal(part) => normalized.push(part),
367            Component::RootDir | Component::Prefix(_) => normalized.push(component.as_os_str()),
368        }
369    }
370    normalized
371}
372
373#[derive(Debug, Deserialize, Default)]
374#[serde(default)]
375struct RawConfig {
376    project: RawProjectConfig,
377    #[serde(alias = "source")]
378    sources: Vec<RawSourceConfig>,
379    #[serde(alias = "presets")]
380    preset: Vec<RawPresetConfig>,
381    #[serde(alias = "override")]
382    overrides: Vec<RawPresetOverrideConfig>,
383    warnings: RawWarningsConfig,
384    budgets: RawBudgetConfig,
385}
386
387impl RawConfig {
388    fn into_config(self, path: &Path, raw: &str) -> Result<Config> {
389        let config_dir = path.parent().unwrap_or_else(|| Path::new("."));
390        let root_raw = self.project.root.unwrap_or_else(|| PathBuf::from("."));
391        let root = normalize_path(&config_dir.join(root_raw));
392        let manifest = self
393            .project
394            .manifest
395            .ok_or_else(|| DevimgError::config(path, "missing [project].manifest"))?;
396        let report = self
397            .project
398            .report
399            .unwrap_or_else(|| PathBuf::from("devimg-report.md"));
400
401        let mut sources = Vec::new();
402        for source in self.sources {
403            sources.push(SourceConfig {
404                name: required(source.name, path, "source.name")?,
405                input: required(source.input, path, "source.input")?,
406                output: required(source.output, path, "source.output")?,
407                include: source.include,
408                exclude: source.exclude,
409            });
410        }
411
412        let mut presets = Vec::new();
413        for preset in self.preset {
414            let widths = required(preset.widths, path, "preset.widths")?;
415            if widths.is_empty() {
416                return Err(DevimgError::config(path, "preset.widths cannot be empty"));
417            }
418            let formats = required(preset.formats, path, "preset.formats")?;
419            if formats.is_empty() {
420                return Err(DevimgError::config(path, "preset.formats cannot be empty"));
421            }
422            let quality = preset.quality.unwrap_or(82);
423            if quality > 100 {
424                return Err(DevimgError::config(path, "quality must be 0-100"));
425            }
426            presets.push(PresetConfig {
427                name: required(preset.name, path, "preset.name")?,
428                widths,
429                formats,
430                quality,
431                fit: preset.fit.unwrap_or(FitMode::Cover),
432                crop: preset.crop.unwrap_or_default(),
433                aspect_ratio: preset.aspect_ratio,
434                allow_upscale: preset.allow_upscale.unwrap_or(false),
435            });
436        }
437
438        let mut overrides = Vec::new();
439        for preset_override in self.overrides {
440            let quality = preset_override.quality;
441            if quality.is_some_and(|quality| quality > 100) {
442                return Err(DevimgError::config(path, "override quality must be 0-100"));
443            }
444            overrides.push(PresetOverrideConfig {
445                include: preset_override.include,
446                exclude: preset_override.exclude,
447                presets: preset_override.presets,
448                quality,
449                fit: preset_override.fit,
450                crop: preset_override.crop,
451                allow_upscale: preset_override.allow_upscale,
452            });
453        }
454
455        if sources.is_empty() {
456            return Err(DevimgError::config(
457                path,
458                "at least one [[sources]] entry is required",
459            ));
460        }
461        if presets.is_empty() {
462            return Err(DevimgError::config(
463                path,
464                "at least one [[preset]] entry is required",
465            ));
466        }
467
468        let warnings = warning_config_from_raw(path, self.warnings)?;
469
470        Ok(Config {
471            path: normalize_path(path),
472            config_hash: hash_bytes(raw.as_bytes()),
473            project: ProjectConfig {
474                root,
475                manifest,
476                report,
477                overwrite: self.project.overwrite.unwrap_or(false),
478                strip_metadata: self.project.strip_metadata.unwrap_or(true),
479                content_hash_filenames: self.project.content_hash_filenames.unwrap_or(false),
480            },
481            sources,
482            presets,
483            overrides,
484            warnings,
485            budgets: BudgetConfig {
486                max_total_bytes: self.budgets.max_total_bytes.map(|bytes| bytes.0),
487                max_file_bytes: self.budgets.max_file_bytes.map(|bytes| bytes.0),
488                fail_on_regression: self.budgets.fail_on_regression,
489            },
490        })
491    }
492}
493
494#[derive(Debug, Deserialize, Default)]
495#[serde(default)]
496struct RawProjectConfig {
497    root: Option<PathBuf>,
498    manifest: Option<PathBuf>,
499    report: Option<PathBuf>,
500    #[serde(alias = "allow_overwrite")]
501    overwrite: Option<bool>,
502    strip_metadata: Option<bool>,
503    #[serde(alias = "hash_filenames", alias = "hashed_filenames")]
504    content_hash_filenames: Option<bool>,
505}
506
507#[derive(Debug, Deserialize, Default)]
508#[serde(default)]
509struct RawSourceConfig {
510    name: Option<String>,
511    input: Option<PathBuf>,
512    output: Option<PathBuf>,
513    include: Vec<String>,
514    exclude: Vec<String>,
515}
516
517#[derive(Debug, Deserialize, Default)]
518#[serde(default)]
519struct RawPresetConfig {
520    name: Option<String>,
521    widths: Option<Vec<u32>>,
522    formats: Option<Vec<FormatKind>>,
523    quality: Option<u8>,
524    fit: Option<FitMode>,
525    #[serde(alias = "crop_anchor", alias = "crop_position", alias = "focal_point")]
526    crop: Option<CropPosition>,
527    aspect_ratio: Option<AspectRatio>,
528    #[serde(alias = "upscale")]
529    allow_upscale: Option<bool>,
530}
531
532#[derive(Debug, Deserialize, Default)]
533#[serde(default)]
534struct RawPresetOverrideConfig {
535    include: Vec<String>,
536    exclude: Vec<String>,
537    presets: Vec<String>,
538    quality: Option<u8>,
539    fit: Option<FitMode>,
540    #[serde(alias = "crop_anchor", alias = "crop_position", alias = "focal_point")]
541    crop: Option<CropPosition>,
542    #[serde(alias = "upscale")]
543    allow_upscale: Option<bool>,
544}
545
546#[derive(Debug, Deserialize, Default)]
547#[serde(default)]
548struct RawWarningsConfig {
549    #[serde(
550        alias = "acknowledgement",
551        alias = "acknowledgments",
552        alias = "acknowledgements"
553    )]
554    acknowledge: Vec<RawWarningAcknowledgementConfig>,
555}
556
557#[derive(Debug, Deserialize, Default)]
558#[serde(default)]
559struct RawWarningAcknowledgementConfig {
560    code: Option<String>,
561    source: Option<String>,
562    output: Option<String>,
563    preset: Option<String>,
564    width: Option<u32>,
565    reason: Option<String>,
566}
567
568#[derive(Debug, Deserialize, Default)]
569#[serde(default)]
570struct RawBudgetConfig {
571    max_total_bytes: Option<ByteSize>,
572    max_file_bytes: Option<ByteSize>,
573    fail_on_regression: bool,
574}
575
576#[derive(Debug, Copy, Clone)]
577struct ByteSize(u64);
578
579impl<'de> Deserialize<'de> for ByteSize {
580    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
581    where
582        D: Deserializer<'de>,
583    {
584        match ByteSizeValue::deserialize(deserializer)? {
585            ByteSizeValue::Number(bytes) => Ok(Self(bytes)),
586            ByteSizeValue::Text(raw) => parse_byte_size(&raw)
587                .map(Self)
588                .map_err(serde::de::Error::custom),
589        }
590    }
591}
592
593#[derive(Debug, Deserialize)]
594#[serde(untagged)]
595enum ByteSizeValue {
596    Text(String),
597    Number(u64),
598}
599
600fn parse_byte_size(raw: &str) -> std::result::Result<u64, String> {
601    let value = raw.trim().to_ascii_lowercase();
602    let split = value
603        .find(|ch: char| !ch.is_ascii_digit())
604        .unwrap_or(value.len());
605    let (number, unit) = value.split_at(split);
606    if number.is_empty() {
607        return Err(format!("invalid byte size `{raw}`"));
608    }
609    let base = number
610        .parse::<u64>()
611        .map_err(|_| format!("invalid byte size `{raw}`"))?;
612    let multiplier = match unit.trim() {
613        "" | "b" => 1,
614        "kb" | "kib" => 1024,
615        "mb" | "mib" => 1024 * 1024,
616        "gb" | "gib" => 1024 * 1024 * 1024,
617        _ => return Err(format!("invalid byte size unit `{unit}`")),
618    };
619    Ok(base * multiplier)
620}
621
622fn required<T>(value: Option<T>, path: &Path, field: &str) -> Result<T> {
623    value.ok_or_else(|| DevimgError::config(path, format!("missing {field}")))
624}
625
626fn warning_config_from_raw(path: &Path, raw: RawWarningsConfig) -> Result<WarningConfig> {
627    let mut acknowledgements = Vec::new();
628    for acknowledgement in raw.acknowledge {
629        let code = required_trimmed(acknowledgement.code, path, "warnings.acknowledge.code")?;
630        let source = optional_trimmed_path(acknowledgement.source);
631        let output = optional_trimmed_path(acknowledgement.output);
632        let preset = optional_trimmed(acknowledgement.preset);
633        let reason = optional_trimmed(acknowledgement.reason);
634        let has_scope = source.is_some()
635            || output.is_some()
636            || preset.is_some()
637            || acknowledgement.width.is_some();
638        if !has_scope {
639            return Err(DevimgError::config(
640                path,
641                "warnings.acknowledge requires at least one of source, output, preset, or width",
642            ));
643        }
644        if warning_acknowledgement_requires_source_and_preset(&code)
645            && (source.is_none() || preset.is_none())
646        {
647            return Err(DevimgError::config(
648                path,
649                format!("{code} acknowledgements require source and preset"),
650            ));
651        }
652        if warning_acknowledgement_requires_output(&code) && output.is_none() {
653            return Err(DevimgError::config(
654                path,
655                format!("{code} acknowledgements require output"),
656            ));
657        }
658        if warning_acknowledgement_requires_source(&code) && source.is_none() {
659            return Err(DevimgError::config(
660                path,
661                format!("{code} acknowledgements require source"),
662            ));
663        }
664        acknowledgements.push(WarningAcknowledgementConfig {
665            code,
666            source,
667            output,
668            preset,
669            width: acknowledgement.width,
670            reason,
671        });
672    }
673    Ok(WarningConfig { acknowledgements })
674}
675
676fn required_trimmed(value: Option<String>, path: &Path, field: &str) -> Result<String> {
677    optional_trimmed(value).ok_or_else(|| DevimgError::config(path, format!("missing {field}")))
678}
679
680fn optional_trimmed(value: Option<String>) -> Option<String> {
681    value
682        .map(|value| value.trim().to_string())
683        .filter(|value| !value.is_empty())
684}
685
686fn optional_trimmed_path(value: Option<String>) -> Option<String> {
687    optional_trimmed(value).map(|value| normalize_warning_path(&value))
688}
689
690fn warning_acknowledgement_requires_source_and_preset(code: &str) -> bool {
691    matches!(
692        code,
693        QUALITY_LOW_LOSSY | QUALITY_SKIPPED_UPSCALE | QUALITY_ALLOWED_UPSCALE | QUALITY_COVER_CROP
694    )
695}
696
697fn warning_acknowledgement_requires_source(code: &str) -> bool {
698    matches!(code, PLAN_NO_VARIANTS)
699}
700
701fn warning_acknowledgement_requires_output(code: &str) -> bool {
702    matches!(
703        code,
704        QUALITY_GENERATED_UPSCALE | QUALITY_OUTPUT_LARGER_THAN_SOURCE
705    )
706}
707
708fn reject_unknown_top_level(path: &Path, value: &toml::Value) -> Result<()> {
709    let Some(table) = value.as_table() else {
710        return Err(DevimgError::config(
711            path,
712            "config root must be a TOML table",
713        ));
714    };
715    for key in table.keys() {
716        if !matches!(
717            key.as_str(),
718            "project"
719                | "sources"
720                | "source"
721                | "preset"
722                | "presets"
723                | "overrides"
724                | "override"
725                | "warnings"
726                | "budgets"
727        ) {
728            return Err(DevimgError::config(
729                path,
730                format!("unsupported top-level section or key `{key}`"),
731            ));
732        }
733    }
734    Ok(())
735}
736
737#[cfg(test)]
738#[path = "config_tests.rs"]
739mod tests;