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 => normalized.push(component.as_os_str()),
368 Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
369 }
370 }
371 normalized
372}
373
374#[derive(Debug, Deserialize, Default)]
375#[serde(default)]
376struct RawConfig {
377 project: RawProjectConfig,
378 #[serde(alias = "source")]
379 sources: Vec<RawSourceConfig>,
380 #[serde(alias = "presets")]
381 preset: Vec<RawPresetConfig>,
382 #[serde(alias = "override")]
383 overrides: Vec<RawPresetOverrideConfig>,
384 warnings: RawWarningsConfig,
385 budgets: RawBudgetConfig,
386}
387
388impl RawConfig {
389 fn into_config(self, path: &Path, raw: &str) -> Result<Config> {
390 let config_dir = path.parent().unwrap_or_else(|| Path::new("."));
391 let root_raw = self.project.root.unwrap_or_else(|| PathBuf::from("."));
392 let root = normalize_path(&config_dir.join(root_raw));
393 let manifest = self
394 .project
395 .manifest
396 .ok_or_else(|| DevimgError::config(path, "missing [project].manifest"))?;
397 let report = self
398 .project
399 .report
400 .unwrap_or_else(|| PathBuf::from("devimg-report.md"));
401
402 let mut sources = Vec::new();
403 for source in self.sources {
404 sources.push(SourceConfig {
405 name: required(source.name, path, "source.name")?,
406 input: required(source.input, path, "source.input")?,
407 output: required(source.output, path, "source.output")?,
408 include: source.include,
409 exclude: source.exclude,
410 });
411 }
412
413 let mut presets = Vec::new();
414 for preset in self.preset {
415 let widths = required(preset.widths, path, "preset.widths")?;
416 if widths.is_empty() {
417 return Err(DevimgError::config(path, "preset.widths cannot be empty"));
418 }
419 let formats = required(preset.formats, path, "preset.formats")?;
420 if formats.is_empty() {
421 return Err(DevimgError::config(path, "preset.formats cannot be empty"));
422 }
423 let quality = preset.quality.unwrap_or(82);
424 if quality > 100 {
425 return Err(DevimgError::config(path, "quality must be 0-100"));
426 }
427 presets.push(PresetConfig {
428 name: required(preset.name, path, "preset.name")?,
429 widths,
430 formats,
431 quality,
432 fit: preset.fit.unwrap_or(FitMode::Cover),
433 crop: preset.crop.unwrap_or_default(),
434 aspect_ratio: preset.aspect_ratio,
435 allow_upscale: preset.allow_upscale.unwrap_or(false),
436 });
437 }
438
439 let mut overrides = Vec::new();
440 for preset_override in self.overrides {
441 let quality = preset_override.quality;
442 if quality.is_some_and(|quality| quality > 100) {
443 return Err(DevimgError::config(path, "override quality must be 0-100"));
444 }
445 overrides.push(PresetOverrideConfig {
446 include: preset_override.include,
447 exclude: preset_override.exclude,
448 presets: preset_override.presets,
449 quality,
450 fit: preset_override.fit,
451 crop: preset_override.crop,
452 allow_upscale: preset_override.allow_upscale,
453 });
454 }
455
456 if sources.is_empty() {
457 return Err(DevimgError::config(
458 path,
459 "at least one [[sources]] entry is required",
460 ));
461 }
462 if presets.is_empty() {
463 return Err(DevimgError::config(
464 path,
465 "at least one [[preset]] entry is required",
466 ));
467 }
468
469 let warnings = warning_config_from_raw(path, self.warnings)?;
470
471 Ok(Config {
472 path: normalize_path(path),
473 config_hash: hash_bytes(raw.as_bytes()),
474 project: ProjectConfig {
475 root,
476 manifest,
477 report,
478 overwrite: self.project.overwrite.unwrap_or(false),
479 strip_metadata: self.project.strip_metadata.unwrap_or(true),
480 content_hash_filenames: self.project.content_hash_filenames.unwrap_or(false),
481 },
482 sources,
483 presets,
484 overrides,
485 warnings,
486 budgets: BudgetConfig {
487 max_total_bytes: self.budgets.max_total_bytes,
488 max_file_bytes: self.budgets.max_file_bytes,
489 fail_on_regression: self.budgets.fail_on_regression,
490 },
491 })
492 }
493}
494
495#[derive(Debug, Deserialize, Default)]
496#[serde(default)]
497struct RawProjectConfig {
498 root: Option<PathBuf>,
499 manifest: Option<PathBuf>,
500 report: Option<PathBuf>,
501 #[serde(alias = "allow_overwrite")]
502 overwrite: Option<bool>,
503 strip_metadata: Option<bool>,
504 #[serde(alias = "hash_filenames", alias = "hashed_filenames")]
505 content_hash_filenames: Option<bool>,
506}
507
508#[derive(Debug, Deserialize, Default)]
509#[serde(default)]
510struct RawSourceConfig {
511 name: Option<String>,
512 input: Option<PathBuf>,
513 output: Option<PathBuf>,
514 include: Vec<String>,
515 exclude: Vec<String>,
516}
517
518#[derive(Debug, Deserialize, Default)]
519#[serde(default)]
520struct RawPresetConfig {
521 name: Option<String>,
522 widths: Option<Vec<u32>>,
523 formats: Option<Vec<FormatKind>>,
524 quality: Option<u8>,
525 fit: Option<FitMode>,
526 #[serde(alias = "crop_anchor", alias = "crop_position", alias = "focal_point")]
527 crop: Option<CropPosition>,
528 aspect_ratio: Option<AspectRatio>,
529 #[serde(alias = "upscale")]
530 allow_upscale: Option<bool>,
531}
532
533#[derive(Debug, Deserialize, Default)]
534#[serde(default)]
535struct RawPresetOverrideConfig {
536 include: Vec<String>,
537 exclude: Vec<String>,
538 presets: Vec<String>,
539 quality: Option<u8>,
540 fit: Option<FitMode>,
541 #[serde(alias = "crop_anchor", alias = "crop_position", alias = "focal_point")]
542 crop: Option<CropPosition>,
543 #[serde(alias = "upscale")]
544 allow_upscale: Option<bool>,
545}
546
547#[derive(Debug, Deserialize, Default)]
548#[serde(default)]
549struct RawWarningsConfig {
550 #[serde(
551 alias = "acknowledgement",
552 alias = "acknowledgments",
553 alias = "acknowledgements"
554 )]
555 acknowledge: Vec<RawWarningAcknowledgementConfig>,
556}
557
558#[derive(Debug, Deserialize, Default)]
559#[serde(default)]
560struct RawWarningAcknowledgementConfig {
561 code: Option<String>,
562 source: Option<String>,
563 output: Option<String>,
564 preset: Option<String>,
565 width: Option<u32>,
566 reason: Option<String>,
567}
568
569#[derive(Debug, Deserialize, Default)]
570#[serde(default)]
571struct RawBudgetConfig {
572 #[serde(default, deserialize_with = "deserialize_optional_byte_size")]
573 max_total_bytes: Option<u64>,
574 #[serde(default, deserialize_with = "deserialize_optional_byte_size")]
575 max_file_bytes: Option<u64>,
576 fail_on_regression: bool,
577}
578
579#[derive(Debug, Deserialize)]
580#[serde(untagged)]
581enum ByteSizeValue {
582 Text(String),
583 Number(u64),
584}
585
586fn deserialize_optional_byte_size<'de, D>(
587 deserializer: D,
588) -> std::result::Result<Option<u64>, D::Error>
589where
590 D: Deserializer<'de>,
591{
592 let value = Option::<ByteSizeValue>::deserialize(deserializer)?;
593 value.map(parse_byte_size_value).transpose()
594}
595
596fn parse_byte_size_value<E>(value: ByteSizeValue) -> std::result::Result<u64, E>
597where
598 E: serde::de::Error,
599{
600 match value {
601 ByteSizeValue::Number(bytes) => Ok(bytes),
602 ByteSizeValue::Text(raw) => parse_byte_size(&raw).map_err(E::custom),
603 }
604}
605
606fn parse_byte_size(raw: &str) -> std::result::Result<u64, String> {
607 let value = raw.trim().to_ascii_lowercase();
608 let split = value
609 .find(|ch: char| !ch.is_ascii_digit())
610 .unwrap_or(value.len());
611 let (number, unit) = value.split_at(split);
612 if number.is_empty() {
613 return Err(format!("invalid byte size `{raw}`"));
614 }
615 let base = number
616 .parse::<u64>()
617 .map_err(|_| format!("invalid byte size `{raw}`"))?;
618 let multiplier = match unit.trim() {
619 "" | "b" => 1,
620 "kb" | "kib" => 1024,
621 "mb" | "mib" => 1024 * 1024,
622 "gb" | "gib" => 1024 * 1024 * 1024,
623 _ => return Err(format!("invalid byte size unit `{unit}`")),
624 };
625 Ok(base * multiplier)
626}
627
628fn required<T>(value: Option<T>, path: &Path, field: &str) -> Result<T> {
629 value.ok_or_else(|| DevimgError::config(path, format!("missing {field}")))
630}
631
632fn warning_config_from_raw(path: &Path, raw: RawWarningsConfig) -> Result<WarningConfig> {
633 let mut acknowledgements = Vec::new();
634 for acknowledgement in raw.acknowledge {
635 let code = required_trimmed(acknowledgement.code, path, "warnings.acknowledge.code")?;
636 let source = optional_trimmed_path(acknowledgement.source);
637 let output = optional_trimmed_path(acknowledgement.output);
638 let preset = optional_trimmed(acknowledgement.preset);
639 let reason = optional_trimmed(acknowledgement.reason);
640 let has_scope = source.is_some()
641 || output.is_some()
642 || preset.is_some()
643 || acknowledgement.width.is_some();
644 if !has_scope {
645 return Err(DevimgError::config(
646 path,
647 "warnings.acknowledge requires at least one of source, output, preset, or width",
648 ));
649 }
650 if warning_acknowledgement_requires_source_and_preset(&code)
651 && (source.is_none() || preset.is_none())
652 {
653 return Err(DevimgError::config(
654 path,
655 format!("{code} acknowledgements require source and preset"),
656 ));
657 }
658 if warning_acknowledgement_requires_output(&code) && output.is_none() {
659 return Err(DevimgError::config(
660 path,
661 format!("{code} acknowledgements require output"),
662 ));
663 }
664 if warning_acknowledgement_requires_source(&code) && source.is_none() {
665 return Err(DevimgError::config(
666 path,
667 format!("{code} acknowledgements require source"),
668 ));
669 }
670 acknowledgements.push(WarningAcknowledgementConfig {
671 code,
672 source,
673 output,
674 preset,
675 width: acknowledgement.width,
676 reason,
677 });
678 }
679 Ok(WarningConfig { acknowledgements })
680}
681
682fn required_trimmed(value: Option<String>, path: &Path, field: &str) -> Result<String> {
683 optional_trimmed(value).ok_or_else(|| DevimgError::config(path, format!("missing {field}")))
684}
685
686fn optional_trimmed(value: Option<String>) -> Option<String> {
687 value
688 .map(|value| value.trim().to_string())
689 .filter(|value| !value.is_empty())
690}
691
692fn optional_trimmed_path(value: Option<String>) -> Option<String> {
693 optional_trimmed(value).map(|value| normalize_warning_path(&value))
694}
695
696fn warning_acknowledgement_requires_source_and_preset(code: &str) -> bool {
697 matches!(
698 code,
699 QUALITY_LOW_LOSSY | QUALITY_SKIPPED_UPSCALE | QUALITY_ALLOWED_UPSCALE | QUALITY_COVER_CROP
700 )
701}
702
703fn warning_acknowledgement_requires_source(code: &str) -> bool {
704 matches!(code, PLAN_NO_VARIANTS)
705}
706
707fn warning_acknowledgement_requires_output(code: &str) -> bool {
708 matches!(
709 code,
710 QUALITY_GENERATED_UPSCALE | QUALITY_OUTPUT_LARGER_THAN_SOURCE
711 )
712}
713
714fn reject_unknown_top_level(path: &Path, value: &toml::Value) -> Result<()> {
715 let Some(table) = value.as_table() else {
716 return Err(DevimgError::config(
717 path,
718 "config root must be a TOML table",
719 ));
720 };
721 for key in table.keys() {
722 if !matches!(
723 key.as_str(),
724 "project"
725 | "sources"
726 | "source"
727 | "preset"
728 | "presets"
729 | "overrides"
730 | "override"
731 | "warnings"
732 | "budgets"
733 ) {
734 return Err(DevimgError::config(
735 path,
736 format!("unsupported top-level section or key `{key}`"),
737 ));
738 }
739 }
740 Ok(())
741}
742
743#[cfg(test)]
744mod tests {
745 use std::path::Path;
746
747 use super::{parse_config, CropPosition, FitMode, FormatKind};
748
749 #[test]
750 fn parses_minimal_config() {
751 let raw = r#"
752[project]
753root = "."
754manifest = "public/images/devimg-manifest.json"
755report = "devimg-report.md"
756
757[[sources]]
758name = "portfolio"
759input = "assets/images"
760output = "public/images/generated"
761include = ["**/*.png", "**/*.jpg"]
762
763[[preset]]
764name = "project-card"
765widths = [640, 960]
766formats = ["webp", "jpeg"]
767quality = 82
768fit = "cover"
769aspect_ratio = "16:9"
770
771[budgets]
772max_total_bytes = "3mb"
773max_file_bytes = "350kb"
774fail_on_regression = true
775"#;
776 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
777 assert_eq!(config.sources[0].name, "portfolio");
778 assert_eq!(
779 config.presets[0].formats,
780 vec![FormatKind::Webp, FormatKind::Jpeg]
781 );
782 assert_eq!(config.presets[0].fit, FitMode::Cover);
783 assert_eq!(config.presets[0].crop, CropPosition::CENTER);
784 assert_eq!(config.budgets.max_file_bytes, Some(350 * 1024));
785 }
786
787 #[test]
788 fn supports_aliases_and_defaults() {
789 let raw = r#"
790[project]
791manifest = "public/images/devimg-manifest.json"
792allow_overwrite = true
793
794[[source]]
795name = "portfolio"
796input = "assets/images"
797output = "public/images/generated"
798
799[[presets]]
800name = "project-card"
801widths = [640]
802formats = ["jpg"]
803upscale = true
804"#;
805 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
806 assert!(config.project.overwrite);
807 assert!(!config.project.content_hash_filenames);
808 assert!(config.presets[0].allow_upscale);
809 assert_eq!(config.presets[0].quality, 82);
810 assert_eq!(config.presets[0].formats, vec![FormatKind::Jpeg]);
811 }
812
813 #[test]
814 fn parses_avif_as_output_only_format() {
815 let raw = r#"
816[project]
817manifest = "public/images/devimg-manifest.json"
818
819[[sources]]
820name = "portfolio"
821input = "assets/images"
822output = "public/images/generated"
823
824[[preset]]
825name = "project-card"
826widths = [640]
827formats = ["webp", "avif"]
828"#;
829 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
830
831 assert_eq!(
832 config.presets[0].formats,
833 vec![FormatKind::Webp, FormatKind::Avif]
834 );
835 assert!(FormatKind::Webp.supports_source_input());
836 assert!(!FormatKind::Avif.supports_source_input());
837 }
838
839 #[test]
840 fn parses_crop_anchor() {
841 let raw = r#"
842[project]
843manifest = "public/images/devimg-manifest.json"
844
845[[sources]]
846name = "portfolio"
847input = "assets/images"
848output = "public/images/generated"
849
850[[preset]]
851name = "project-card"
852widths = [640]
853formats = ["webp"]
854crop = "top-right"
855"#;
856 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
857
858 assert_eq!(config.presets[0].crop, CropPosition { x: 1.0, y: 0.0 });
859 }
860
861 #[test]
862 fn parses_crop_focal_point() {
863 let raw = r#"
864[project]
865manifest = "public/images/devimg-manifest.json"
866
867[[sources]]
868name = "portfolio"
869input = "assets/images"
870output = "public/images/generated"
871
872[[preset]]
873name = "project-card"
874widths = [640]
875formats = ["webp"]
876crop = { x = 0.5, y = 0.0 }
877"#;
878 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
879
880 assert_eq!(config.presets[0].crop, CropPosition { x: 0.5, y: 0.0 });
881 }
882
883 #[test]
884 fn rejects_invalid_crop_focal_point() {
885 let raw = r#"
886[project]
887manifest = "public/images/devimg-manifest.json"
888
889[[sources]]
890name = "portfolio"
891input = "assets/images"
892output = "public/images/generated"
893
894[[preset]]
895name = "project-card"
896widths = [640]
897formats = ["webp"]
898crop = { x = 0.5, y = 1.5 }
899"#;
900 let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
901
902 assert!(error.to_string().contains("crop x and y"));
903 }
904
905 #[test]
906 fn parses_content_hash_filename_alias() {
907 let raw = r#"
908[project]
909manifest = "public/images/devimg-manifest.json"
910hash_filenames = true
911
912[[sources]]
913name = "portfolio"
914input = "assets/images"
915output = "public/images/generated"
916
917[[preset]]
918name = "project-card"
919widths = [640]
920formats = ["webp"]
921"#;
922 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
923
924 assert!(config.project.content_hash_filenames);
925 }
926
927 #[test]
928 fn parses_preset_overrides() {
929 let raw = r#"
930[project]
931manifest = "public/images/devimg-manifest.json"
932
933[[sources]]
934name = "portfolio"
935input = "assets/images"
936output = "public/images/generated"
937
938[[preset]]
939name = "project-card"
940widths = [640]
941formats = ["webp"]
942
943[[overrides]]
944include = ["cli_tools.png"]
945presets = ["project-card"]
946quality = 74
947fit = "contain"
948crop = "top"
949upscale = true
950"#;
951 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
952
953 assert_eq!(config.overrides.len(), 1);
954 assert_eq!(config.overrides[0].include, vec!["cli_tools.png"]);
955 assert_eq!(config.overrides[0].presets, vec!["project-card"]);
956 assert_eq!(config.overrides[0].quality, Some(74));
957 assert_eq!(config.overrides[0].fit, Some(FitMode::Contain));
958 assert_eq!(
959 config.overrides[0].crop,
960 Some(CropPosition { x: 0.5, y: 0.0 })
961 );
962 assert_eq!(config.overrides[0].allow_upscale, Some(true));
963 }
964
965 #[test]
966 fn parses_scoped_warning_acknowledgements() {
967 let raw = r#"
968[project]
969manifest = "public/images/devimg-manifest.json"
970
971[[sources]]
972name = "portfolio"
973input = "assets/images"
974output = "public/images/generated"
975
976[[preset]]
977name = "project-card"
978widths = [640]
979formats = ["webp"]
980
981[[warnings.acknowledge]]
982code = "quality:cover-crop"
983source = "./assets/images/accesstrace.png"
984preset = "project-card"
985reason = "Intentional social-card framing."
986"#;
987 let config = parse_config(Path::new("devimg.toml"), raw).expect("config parses");
988
989 assert_eq!(config.warnings.acknowledgements.len(), 1);
990 let acknowledgement = &config.warnings.acknowledgements[0];
991 assert_eq!(acknowledgement.code, "quality:cover-crop");
992 assert_eq!(
993 acknowledgement.source.as_deref(),
994 Some("assets/images/accesstrace.png")
995 );
996 assert_eq!(acknowledgement.preset.as_deref(), Some("project-card"));
997 assert_eq!(
998 acknowledgement.reason.as_deref(),
999 Some("Intentional social-card framing.")
1000 );
1001 }
1002
1003 #[test]
1004 fn rejects_broad_cover_crop_warning_acknowledgements() {
1005 let raw = r#"
1006[project]
1007manifest = "public/images/devimg-manifest.json"
1008
1009[[sources]]
1010name = "portfolio"
1011input = "assets/images"
1012output = "public/images/generated"
1013
1014[[preset]]
1015name = "project-card"
1016widths = [640]
1017formats = ["webp"]
1018
1019[[warnings.acknowledge]]
1020code = "quality:cover-crop"
1021preset = "project-card"
1022"#;
1023 let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
1024
1025 assert!(error.to_string().contains("source and preset"));
1026 }
1027
1028 #[test]
1029 fn rejects_invalid_override_quality() {
1030 let raw = r#"
1031[project]
1032manifest = "public/images/devimg-manifest.json"
1033
1034[[sources]]
1035name = "portfolio"
1036input = "assets/images"
1037output = "public/images/generated"
1038
1039[[preset]]
1040name = "project-card"
1041widths = [640]
1042formats = ["webp"]
1043
1044[[overrides]]
1045include = ["card.png"]
1046quality = 101
1047"#;
1048 let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
1049
1050 assert!(error.to_string().contains("override quality"));
1051 }
1052
1053 #[test]
1054 fn rejects_unknown_top_level_sections() {
1055 let raw = r#"
1056[project]
1057manifest = "public/images/devimg-manifest.json"
1058
1059[unknown]
1060value = true
1061
1062[[sources]]
1063name = "portfolio"
1064input = "assets/images"
1065output = "public/images/generated"
1066
1067[[preset]]
1068name = "project-card"
1069widths = [640]
1070formats = ["webp"]
1071"#;
1072 let error = parse_config(Path::new("devimg.toml"), raw).expect_err("config fails");
1073 assert!(error.to_string().contains("unsupported top-level"));
1074 }
1075}