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 let Some(expected) = source_input_format(&normalized) else {
49 continue;
50 };
51 let relative_path = relative_source_path(&normalized, &input_root);
52 let relative_string = path_to_string(&relative_path);
53 if !source.include.is_empty() && !includes.is_match(&relative_string) {
54 continue;
55 }
56 if excludes.is_match(&relative_string) {
57 continue;
58 }
59
60 let bytes = read_file(&normalized)?;
61 let guessed = image::guess_format(&bytes).map_err(|source| {
62 DevimgError::image(
63 &normalized,
64 format!("could not determine image format: {source}"),
65 )
66 })?;
67 if guessed != expected.image_format() {
68 return Err(DevimgError::image(
69 &normalized,
70 format!(
71 "file extension suggests {}, but image bytes are {}",
72 expected.label(),
73 image_format_label(guessed)
74 ),
75 ));
76 }
77 let (width, height) = image::image_dimensions(&normalized).map_err(|source| {
78 DevimgError::image(&normalized, format!("could not read dimensions: {source}"))
79 })?;
80
81 images.push(SourceImage {
82 source_name: source.name.clone(),
83 project_path: path_to_string(&project_relative(config, &normalized)),
84 relative_path,
85 output_root_project_path: path_to_string(&project_relative(config, &output_root)),
86 output_root: output_root.clone(),
87 path: normalized,
88 width,
89 height,
90 bytes: bytes.len() as u64,
91 hash: hash_bytes(&bytes),
92 format: expected,
93 });
94 }
95 }
96 images.sort_by(|left, right| left.project_path.cmp(&right.project_path));
97 Ok(images)
98}
99
100pub fn inspect_image(path: &Path) -> Result<ImageInspection> {
101 let bytes = read_file(path)?;
102 let format = image::guess_format(&bytes)
103 .map(image_format_label)
104 .map_err(|source| {
105 DevimgError::image(path, format!("could not determine format: {source}"))
106 })?;
107 let (width, height) = image::image_dimensions(path).map_err(|source| {
108 DevimgError::image(path, format!("could not read dimensions: {source}"))
109 })?;
110 Ok(ImageInspection {
111 path: path_to_string(path),
112 width,
113 height,
114 format: format.to_string(),
115 bytes: bytes.len() as u64,
116 hash: hash_bytes(&bytes),
117 })
118}
119
120fn collect_files(dir: &Path) -> Result<Vec<PathBuf>> {
121 let mut files = Vec::new();
122 for entry in WalkDir::new(dir).follow_links(false) {
123 let entry = entry.map_err(|source| {
124 let path = source.path().unwrap_or(dir).to_path_buf();
125 let message = source.to_string();
126 let io_error = source
127 .into_io_error()
128 .unwrap_or(std::io::Error::other(message));
129 DevimgError::io(path, io_error)
130 })?;
131 if entry.file_type().is_file() {
132 files.push(entry.into_path());
133 }
134 }
135 Ok(files)
136}
137
138fn source_input_format(path: &Path) -> Option<FormatKind> {
139 let format = format_from_extension(path)?;
140 if format.supports_source_input() {
141 Some(format)
142 } else {
143 None
144 }
145}
146
147fn read_file(path: &Path) -> Result<Vec<u8>> {
148 match fs::read(path) {
149 Ok(bytes) => Ok(bytes),
150 Err(source) => Err(DevimgError::io(path, source)),
151 }
152}
153
154fn relative_source_path(path: &Path, input_root: &Path) -> PathBuf {
155 match path.strip_prefix(input_root) {
156 Ok(relative_path) => relative_path.to_path_buf(),
157 Err(_) => path.to_path_buf(),
158 }
159}
160
161fn format_from_extension(path: &Path) -> Option<FormatKind> {
162 FormatKind::parse(&path.extension()?.to_string_lossy())
163}
164
165fn image_format_label(format: ImageFormat) -> &'static str {
166 match format {
167 ImageFormat::Png => "png",
168 ImageFormat::Jpeg => "jpeg",
169 ImageFormat::WebP => "webp",
170 ImageFormat::Avif => "avif",
171 _ => "unsupported",
172 }
173}
174
175fn path_is_under(path: &Path, parent: &Path) -> bool {
176 let path = crate::config::normalize_path(path);
177 let parent = crate::config::normalize_path(parent);
178 !parent.as_os_str().is_empty() && path.starts_with(parent)
179}
180
181pub(crate) fn compile_globs(
182 config_path: &Path,
183 label: &str,
184 patterns: &[String],
185) -> Result<GlobSet> {
186 let mut builder = GlobSetBuilder::new();
187 for pattern in patterns {
188 add_glob(config_path, label, &mut builder, pattern)?;
189 if let Some(root_pattern) = pattern.replace('\\', "/").strip_prefix("**/") {
190 add_glob(config_path, label, &mut builder, root_pattern)?;
191 }
192 }
193 build_glob_set(config_path, label, builder.build())
194}
195
196fn build_glob_set(
197 config_path: &Path,
198 label: &str,
199 result: std::result::Result<GlobSet, globset::Error>,
200) -> Result<GlobSet> {
201 match result {
202 Ok(globs) => Ok(globs),
203 Err(source) => Err(invalid_glob_set_error(config_path, label, source)),
204 }
205}
206
207fn invalid_glob_set_error(config_path: &Path, label: &str, source: globset::Error) -> DevimgError {
208 DevimgError::config(config_path, format!("invalid {label} glob set: {source}"))
209}
210
211fn add_glob(
212 config_path: &Path,
213 label: &str,
214 builder: &mut GlobSetBuilder,
215 pattern: &str,
216) -> Result<()> {
217 let normalized = pattern.replace('\\', "/");
218 let glob = GlobBuilder::new(&normalized)
219 .case_insensitive(true)
220 .build()
221 .map_err(|source| {
222 DevimgError::config(
223 config_path,
224 format!("invalid {label} glob `{pattern}`: {source}"),
225 )
226 })?;
227 builder.add(glob);
228 Ok(())
229}
230
231#[cfg(test)]
232#[path = "scan_tests.rs"]
233mod tests;