1use std::collections::BTreeMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use crate::budget::evaluate_budgets;
6pub use crate::check::{check, check_with_options, CheckOptions};
7use crate::config::{resolve_project_path_checked, Config, CropPosition, FitMode, FormatKind};
8use crate::incremental::{IncrementalCache, IncrementalLookup};
9use crate::manifest::{write_manifest, Manifest};
10pub use crate::plan::build_plan;
11use crate::quality::{append_unique, manifest_quality_warnings};
12use crate::report::render_run_report;
13pub use crate::scan::{inspect_image, scan_sources};
14use crate::transform::execute_operation;
15use crate::warnings::{split_acknowledged_warnings, warning_message, BUDGET_FAILED};
16use crate::{DevimgError, Result};
17
18#[derive(Debug, Clone)]
19pub struct SourceImage {
20 pub source_name: String,
21 pub path: PathBuf,
22 pub project_path: String,
23 pub relative_path: PathBuf,
24 pub output_root: PathBuf,
25 pub output_root_project_path: String,
26 pub width: u32,
27 pub height: u32,
28 pub bytes: u64,
29 pub hash: String,
30 pub format: FormatKind,
31}
32
33#[derive(Debug, Clone)]
34pub struct Operation {
35 pub source: SourceImage,
36 pub preset: String,
37 pub fit: FitMode,
38 pub crop: CropPosition,
39 pub quality: u8,
40 pub format: FormatKind,
41 pub width: u32,
42 pub height: u32,
43 pub strip_metadata: bool,
44 pub content_hash_filenames: bool,
45 pub output_path: PathBuf,
46 pub output_project_path: String,
47 pub operation_hash: String,
48}
49
50#[derive(Debug, Clone)]
51pub struct Plan {
52 pub operations: Vec<Operation>,
53 pub warnings: Vec<String>,
54}
55
56#[derive(Debug, Clone, Copy, Default)]
57pub struct OptimizeOptions {
58 pub dry_run: bool,
59 pub allow_overwrite: bool,
60}
61
62#[derive(Debug, Clone)]
63pub struct OptimizeResult {
64 pub mode: String,
65 pub source_count: usize,
66 pub planned_count: usize,
67 pub generated_count: usize,
68 pub skipped_count: usize,
69 pub stale_count: usize,
70 pub source_bytes: u64,
71 pub output_bytes: u64,
72 pub warnings: Vec<String>,
73 pub acknowledged_warnings: Vec<String>,
74 pub issues: Vec<CheckIssue>,
75 pub budget_status: String,
76 pub manifest: Manifest,
77}
78
79#[derive(Debug, Clone)]
80pub struct CheckResult {
81 pub passed: bool,
82 pub result: OptimizeResult,
83}
84
85#[derive(Debug, Clone)]
86pub struct CheckIssue {
87 pub kind: String,
88 pub path: String,
89 pub message: String,
90}
91
92#[derive(Debug, Clone)]
93pub struct ImageInspection {
94 pub path: String,
95 pub width: u32,
96 pub height: u32,
97 pub format: String,
98 pub bytes: u64,
99 pub hash: String,
100}
101
102pub fn optimize(config: &Config, options: OptimizeOptions) -> Result<OptimizeResult> {
103 let sources = scan_sources(config)?;
104 let plan = build_plan(config, &sources)?;
105 let source_bytes = unique_source_bytes(&sources);
106 let mode = if options.dry_run {
107 "dry-run"
108 } else {
109 "optimize"
110 }
111 .to_string();
112
113 if options.dry_run {
114 let warning_groups = split_acknowledged_warnings(config, plan.warnings);
115 let result = OptimizeResult {
116 mode,
117 source_count: sources.len(),
118 planned_count: plan.operations.len(),
119 generated_count: 0,
120 skipped_count: 0,
121 stale_count: 0,
122 source_bytes,
123 output_bytes: 0,
124 warnings: warning_groups.active,
125 acknowledged_warnings: warning_groups.acknowledged,
126 issues: Vec::new(),
127 budget_status: "not evaluated during dry-run".to_string(),
128 manifest: Manifest::new(
129 path_to_string(&config.path),
130 config.config_hash.clone(),
131 Vec::new(),
132 ),
133 };
134 return Ok(result);
135 }
136
137 let manifest_path =
138 resolve_project_path_checked(config, &config.project.manifest, "manifest path")?;
139 let _report_path = resolve_project_path_checked(config, &config.project.report, "report path")?;
140
141 let mut outputs = Vec::new();
142 let mut warnings = plan.warnings;
143 let incremental_cache = IncrementalCache::read(config, &manifest_path);
144 let mut generated_count = 0usize;
145 let mut skipped_count = 0usize;
146 let mut stale_count = 0usize;
147 for operation in &plan.operations {
148 if let Some(cache) = &incremental_cache {
149 match cache.lookup_current(config, operation)? {
150 IncrementalLookup::Current(output) => {
151 skipped_count += 1;
152 outputs.push(*output);
153 continue;
154 }
155 IncrementalLookup::Stale => {
156 stale_count += 1;
157 }
158 }
159 }
160 outputs.push(execute_operation(
161 operation,
162 config.project.overwrite || options.allow_overwrite,
163 )?);
164 generated_count += 1;
165 }
166
167 let manifest = Manifest::new(
168 path_to_string(&config.path),
169 config.config_hash.clone(),
170 outputs,
171 );
172 let (budget_status, issues) = evaluate_budgets(config, &manifest.outputs);
173 let output_bytes = manifest.output_bytes_total();
174 append_unique(&mut warnings, manifest_quality_warnings(&manifest));
175 if !issues.is_empty() {
176 warnings.push(warning_message(
177 BUDGET_FAILED,
178 format!(
179 "budget status is fail with {} issue(s); `devimg check` will fail",
180 issues.len()
181 ),
182 ));
183 }
184 let warning_groups = split_acknowledged_warnings(config, warnings);
185
186 let result = OptimizeResult {
187 mode,
188 source_count: sources.len(),
189 planned_count: plan.operations.len(),
190 generated_count,
191 skipped_count,
192 stale_count,
193 source_bytes,
194 output_bytes,
195 warnings: warning_groups.active,
196 acknowledged_warnings: warning_groups.acknowledged,
197 issues,
198 budget_status,
199 manifest,
200 };
201
202 write_manifest(&manifest_path, &result.manifest)?;
203 write_report(config, &result)?;
204 Ok(result)
205}
206
207pub(crate) fn write_report(config: &Config, result: &OptimizeResult) -> Result<()> {
208 let report_path = resolve_project_path_checked(config, &config.project.report, "report path")?;
209 report_path.parent().map_or(Ok(()), |parent| {
210 fs::create_dir_all(parent).map_err(|source| DevimgError::io(parent, source))
211 })?;
212 write_report_markdown(&report_path, render_run_report(result))
213}
214
215fn write_report_markdown(path: &Path, markdown: String) -> Result<()> {
216 match fs::write(path, markdown) {
217 Ok(()) => Ok(()),
218 Err(source) => Err(DevimgError::io(path, source)),
219 }
220}
221
222pub(crate) fn unique_source_bytes(sources: &[SourceImage]) -> u64 {
223 let mut by_path = BTreeMap::new();
224 for source in sources {
225 by_path.insert(source.project_path.as_str(), source.bytes);
226 }
227 by_path.values().sum()
228}
229
230pub(crate) fn path_to_string(path: &Path) -> String {
231 path.to_string_lossy()
232 .replace(std::path::MAIN_SEPARATOR, "/")
233}
234
235#[cfg(test)]
236#[path = "pipeline_tests.rs"]
237mod tests;