Skip to main content

devimg_core/
scan.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
5use image::ImageFormat;
6use walkdir::WalkDir;
7
8use crate::config::{project_relative, resolve_project_path_checked, Config, FormatKind};
9use crate::hash::hash_bytes;
10use crate::pipeline::{path_to_string, ImageInspection, SourceImage};
11use crate::{DevimgError, Result};
12
13pub fn scan_sources(config: &Config) -> Result<Vec<SourceImage>> {
14    let mut images = Vec::new();
15    for source in &config.sources {
16        let input_root = resolve_project_path_checked(config, &source.input, "source input")?;
17        let output_root = resolve_project_path_checked(config, &source.output, "source output")?;
18        if !input_root.exists() {
19            return Err(DevimgError::config(
20                &config.path,
21                format!(
22                    "source `{}` input does not exist: {}",
23                    source.name,
24                    input_root.display()
25                ),
26            ));
27        }
28        if !input_root.is_dir() {
29            return Err(DevimgError::config(
30                &config.path,
31                format!(
32                    "source `{}` input is not a directory: {}",
33                    source.name,
34                    input_root.display()
35                ),
36            ));
37        }
38
39        let includes = compile_globs(&config.path, "include", &source.include)?;
40        let excludes = compile_globs(&config.path, "exclude", &source.exclude)?;
41        let mut files = collect_files(&input_root)?;
42        files.sort();
43        for path in files {
44            let normalized = crate::config::normalize_path(&path);
45            if path_is_under(&normalized, &output_root) {
46                continue;
47            }
48            if !has_supported_extension(&normalized) {
49                continue;
50            }
51            let relative_path = normalized
52                .strip_prefix(&input_root)
53                .map(Path::to_path_buf)
54                .unwrap_or_else(|_| normalized.clone());
55            let relative_string = path_to_string(&relative_path);
56            if !source.include.is_empty() && !includes.is_match(&relative_string) {
57                continue;
58            }
59            if excludes.is_match(&relative_string) {
60                continue;
61            }
62
63            let bytes =
64                fs::read(&normalized).map_err(|source| DevimgError::io(&normalized, source))?;
65            let expected = format_from_extension(&normalized)
66                .ok_or_else(|| DevimgError::image(&normalized, "unsupported file extension"))?;
67            let guessed = image::guess_format(&bytes).map_err(|source| {
68                DevimgError::image(
69                    &normalized,
70                    format!("could not determine image format: {source}"),
71                )
72            })?;
73            if guessed != expected.image_format() {
74                return Err(DevimgError::image(
75                    &normalized,
76                    format!(
77                        "file extension suggests {}, but image bytes are {}",
78                        expected.label(),
79                        image_format_label(guessed)
80                    ),
81                ));
82            }
83            let (width, height) = image::image_dimensions(&normalized).map_err(|source| {
84                DevimgError::image(&normalized, format!("could not read dimensions: {source}"))
85            })?;
86
87            images.push(SourceImage {
88                source_name: source.name.clone(),
89                project_path: path_to_string(&project_relative(config, &normalized)),
90                relative_path,
91                output_root_project_path: path_to_string(&project_relative(config, &output_root)),
92                output_root: output_root.clone(),
93                path: normalized,
94                width,
95                height,
96                bytes: bytes.len() as u64,
97                hash: hash_bytes(&bytes),
98                format: expected,
99            });
100        }
101    }
102    images.sort_by(|left, right| left.project_path.cmp(&right.project_path));
103    Ok(images)
104}
105
106pub fn inspect_image(path: &Path) -> Result<ImageInspection> {
107    let bytes = fs::read(path).map_err(|source| DevimgError::io(path, source))?;
108    let format = image::guess_format(&bytes)
109        .map(image_format_label)
110        .map_err(|source| {
111            DevimgError::image(path, format!("could not determine format: {source}"))
112        })?;
113    let (width, height) = image::image_dimensions(path).map_err(|source| {
114        DevimgError::image(path, format!("could not read dimensions: {source}"))
115    })?;
116    Ok(ImageInspection {
117        path: path_to_string(path),
118        width,
119        height,
120        format: format.to_string(),
121        bytes: bytes.len() as u64,
122        hash: hash_bytes(&bytes),
123    })
124}
125
126fn collect_files(dir: &Path) -> Result<Vec<PathBuf>> {
127    let mut files = Vec::new();
128    for entry in WalkDir::new(dir).follow_links(false) {
129        let entry = entry.map_err(|source| {
130            let path = source
131                .path()
132                .map(Path::to_path_buf)
133                .unwrap_or_else(|| dir.to_path_buf());
134            let message = source.to_string();
135            let io_error = source
136                .into_io_error()
137                .unwrap_or_else(|| std::io::Error::other(message));
138            DevimgError::io(path, io_error)
139        })?;
140        if entry.file_type().is_file() {
141            files.push(entry.into_path());
142        }
143    }
144    Ok(files)
145}
146
147fn has_supported_extension(path: &Path) -> bool {
148    format_from_extension(path).is_some_and(FormatKind::supports_source_input)
149}
150
151fn format_from_extension(path: &Path) -> Option<FormatKind> {
152    FormatKind::parse(&path.extension()?.to_string_lossy())
153}
154
155fn image_format_label(format: ImageFormat) -> &'static str {
156    match format {
157        ImageFormat::Png => "png",
158        ImageFormat::Jpeg => "jpeg",
159        ImageFormat::WebP => "webp",
160        ImageFormat::Avif => "avif",
161        _ => "unsupported",
162    }
163}
164
165fn path_is_under(path: &Path, parent: &Path) -> bool {
166    let path = crate::config::normalize_path(path);
167    let parent = crate::config::normalize_path(parent);
168    !parent.as_os_str().is_empty() && path.starts_with(parent)
169}
170
171pub(crate) fn compile_globs(
172    config_path: &Path,
173    label: &str,
174    patterns: &[String],
175) -> Result<GlobSet> {
176    let mut builder = GlobSetBuilder::new();
177    for pattern in patterns {
178        add_glob(config_path, label, &mut builder, pattern)?;
179        if let Some(root_pattern) = pattern.replace('\\', "/").strip_prefix("**/") {
180            add_glob(config_path, label, &mut builder, root_pattern)?;
181        }
182    }
183    builder.build().map_err(|source| {
184        DevimgError::config(config_path, format!("invalid {label} glob set: {source}"))
185    })
186}
187
188fn add_glob(
189    config_path: &Path,
190    label: &str,
191    builder: &mut GlobSetBuilder,
192    pattern: &str,
193) -> Result<()> {
194    let normalized = pattern.replace('\\', "/");
195    let glob = GlobBuilder::new(&normalized)
196        .case_insensitive(true)
197        .build()
198        .map_err(|source| {
199            DevimgError::config(
200                config_path,
201                format!("invalid {label} glob `{pattern}`: {source}"),
202            )
203        })?;
204    builder.add(glob);
205    Ok(())
206}