1use std::path::Path;
12
13use crate::package::{FileResult, GeneratorReport};
14use crate::run::ansi::plain;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum FileOutcome {
19 Created,
21 Replaced,
23 Left,
25 Failed,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct GeneratedFile {
32 pub path: String,
34 pub outcome: FileOutcome,
35}
36
37pub fn generated_files(lines: &[String], force: bool) -> Vec<GeneratedFile> {
43 let mut files: Vec<GeneratedFile> = Vec::new();
44 for line in lines {
45 let line = plain(line);
46 if let Some((path, done)) = generating_line(&line) {
47 let outcome = match (done, force) {
48 (true, true) => FileOutcome::Replaced,
49 (true, false) => FileOutcome::Created,
50 (false, _) => FileOutcome::Failed,
51 };
52 files.push(GeneratedFile {
53 path: path.to_string(),
54 outcome,
55 });
56 } else if let Some(path) = exists_path(&line) {
57 let failed = files
58 .iter_mut()
59 .rev()
60 .find(|file| file.path == path && file.outcome == FileOutcome::Failed);
61 match failed {
62 Some(file) => file.outcome = FileOutcome::Left,
63 None => files.push(GeneratedFile {
64 path: path.to_string(),
65 outcome: FileOutcome::Left,
66 }),
67 }
68 }
69 }
70 files
71}
72
73pub fn reported_files(
78 report: &GeneratorReport,
79 root: &Path,
80 modules: &str,
81 names: &[&str],
82 folders: &[&str],
83) -> Vec<GeneratedFile> {
84 report
85 .files
86 .iter()
87 .filter_map(|file| {
88 let outcome = match file.result? {
89 FileResult::Created => FileOutcome::Created,
90 FileResult::Replaced => FileOutcome::Replaced,
91 FileResult::Exists => FileOutcome::Left,
92 FileResult::Failed => FileOutcome::Failed,
93 FileResult::Deleted => return None,
94 };
95 let path = app_relative(root, modules, names, folders, &file.path)
96 .unwrap_or_else(|| file.path.clone());
97 Some(GeneratedFile { path, outcome })
98 })
99 .collect()
100}
101
102pub fn app_relative(
119 root: &Path,
120 modules: &str,
121 names: &[&str],
122 folders: &[&str],
123 printed: &str,
124) -> Option<String> {
125 let printed = printed.replace('\\', "/");
126 [Some(root.to_path_buf()), root.canonicalize().ok()]
127 .into_iter()
128 .flatten()
129 .find_map(|root| {
130 let root = root.to_string_lossy().replace('\\', "/");
131 let root = root.strip_prefix("//?/").unwrap_or(&root);
133 let rest = printed.strip_prefix(root.trim_end_matches('/'))?;
134 let rest = rest.strip_prefix('/')?;
135 (!rest.is_empty()).then(|| rest.to_owned())
136 })
137 .or_else(|| from_modules(modules, names, folders, &printed))
138}
139
140fn from_modules(modules: &str, names: &[&str], folders: &[&str], printed: &str) -> Option<String> {
144 let modules = modules.trim_matches('/');
145 if modules.is_empty() {
146 return None;
147 }
148 let part = format!("/{modules}/");
149 let found: Vec<(&str, &str)> = printed
150 .char_indices()
151 .filter(|(at, _)| printed[*at..].starts_with(&part))
152 .filter_map(|(at, _)| {
153 let rest = &printed[at + 1..];
154 let (module, file) = rest[modules.len() + 1..].split_once('/')?;
155 (!module.is_empty() && !file.is_empty()).then_some((module, rest))
156 })
157 .collect();
158 let studly = |name: &str| {
159 name.chars()
160 .filter(|c| *c != '-' && *c != '_')
161 .map(|c| c.to_ascii_lowercase())
162 .collect::<String>()
163 };
164 let asked: Vec<String> = names.iter().map(|name| studly(name)).collect();
165 let first = |known: &dyn Fn(&str) -> bool| found.iter().find(|(module, _)| known(module));
166 first(&|module| asked.contains(&studly(module)))
167 .or_else(|| first(&|module| folders.contains(&module)))
168 .or(found.last())
169 .map(|(_, rest)| (*rest).to_owned())
170}
171
172pub fn autoload_failed(lines: &[String]) -> bool {
174 lines.iter().any(|line| {
175 plain(line)
176 .trim()
177 .ends_with("composer dump-autoload failed.")
178 })
179}
180
181fn generating_line(line: &str) -> Option<(&str, bool)> {
184 let rest = line.trim().strip_prefix("Generating file ")?;
185 let (rest, end) = rest.trim_end().rsplit_once(' ')?;
186 let done = match end {
187 "DONE" => true,
188 "FAIL" => false,
189 _ => return None,
190 };
191 let rest = rest.trim_end();
192 let rest = match rest.rsplit_once(' ') {
193 Some((before, time)) if is_time(time) => before,
194 _ => rest,
195 };
196 let path = rest.trim_end_matches(['.', ' ']);
197 (!path.is_empty()).then_some((path, done))
198}
199
200fn is_time(word: &str) -> bool {
202 word.starts_with(|c: char| c.is_ascii_digit()) && word.ends_with('s')
203}
204
205fn exists_path(line: &str) -> Option<&str> {
207 let (_, rest) = line.split_once("File : ")?;
208 let path = rest.trim_end().strip_suffix(" already exists.")?;
209 (!path.is_empty()).then_some(path)
210}
211
212#[cfg(test)]
213mod tests {
214 use std::path::Path;
215
216 use super::*;
217 use crate::actions::output::tests::recording;
218
219 fn files(name: &str, force: bool) -> Vec<(String, FileOutcome)> {
220 generated_files(&recording(name), force)
221 .into_iter()
222 .map(|file| (file.path, file.outcome))
223 .collect()
224 }
225
226 #[test]
227 fn a_generator_run_creates_its_files() {
228 let created = |path: &str| (path.to_string(), FileOutcome::Created);
229 assert_eq!(
230 files("module-make-model-migration-policy", false),
231 vec![
232 created("Modules/Billing/app/Models/PaymentIntent.php"),
233 created(
234 "Modules/Billing/database/migrations/2026_11_23_071900_create_payment_intents_table.php"
235 ),
236 created("Modules/Billing/app/Policies/PaymentIntentPolicy.php"),
237 ]
238 );
239 let module = files("module-make", false);
240 assert_eq!(module[0], created("Modules/Blog/module.json"));
241 assert!(
242 module
243 .iter()
244 .all(|(_, outcome)| *outcome == FileOutcome::Created)
245 );
246 assert_eq!(files("module-make-api", false).len(), 16);
247 }
248
249 #[test]
250 fn a_file_that_exists_is_left() {
251 let outcomes: Vec<_> = files("module-make-model-policy-exists", false)
253 .into_iter()
254 .map(|(_, outcome)| outcome)
255 .collect();
256 assert_eq!(
257 outcomes,
258 [
259 FileOutcome::Created,
260 FileOutcome::Created,
261 FileOutcome::Left
262 ]
263 );
264 assert_eq!(
265 files("module-make-controller-exists", false),
266 vec![(
267 "Modules/Blog/app/Http/Controllers/PostController.php".to_string(),
268 FileOutcome::Left
269 )]
270 );
271 }
272
273 #[test]
274 fn a_forced_run_replaces_its_file() {
275 assert_eq!(
276 files("module-make-policy-force", true),
277 vec![(
278 "Modules/Billing/app/Policies/InvoicePolicy.php".to_string(),
279 FileOutcome::Replaced
280 )]
281 );
282 }
283
284 #[test]
285 fn a_report_gives_the_files_relative_to_the_app() {
286 let root = Path::new("/tmp/scratch-app");
287 let read = |name: &str| {
288 let report: GeneratorReport = crate::package::document(&recording(name)).unwrap();
289 reported_files(&report, root, "Modules", &[], &[])
290 .into_iter()
291 .map(|file| (file.path, file.outcome))
292 .collect::<Vec<_>>()
293 };
294 let created = read("module-make-model-json");
295 assert_eq!(
296 created[0],
297 (
298 "Modules/Billing/app/Models/PaymentIntent.php".to_string(),
299 FileOutcome::Created
300 )
301 );
302 assert!(
303 created
304 .iter()
305 .all(|(_, outcome)| *outcome == FileOutcome::Created)
306 );
307 let left = read("module-make-model-policy-exists-json");
309 assert_eq!(
310 left[2],
311 (
312 "Modules/Billing/app/Policies/InvoicePolicy.php".to_string(),
313 FileOutcome::Left
314 )
315 );
316 assert_eq!(
317 app_relative(
318 Path::new("/tmp/other"),
319 "Modules",
320 &[],
321 &[],
322 "/tmp/scratch-app/x.php"
323 ),
324 None
325 );
326 let container = |modules: &str, printed: &str| {
329 app_relative(
330 Path::new("/Users/me/shop"),
331 modules,
332 &[],
333 &["Billing"],
334 printed,
335 )
336 };
337 assert_eq!(
338 container(
339 "Modules",
340 "/var/www/html/Modules/Billing/app/Models/Invoice.php"
341 )
342 .as_deref(),
343 Some("Modules/Billing/app/Models/Invoice.php")
344 );
345 assert_eq!(
346 container("src/Domains", "/app/src/Domains/Billing/Invoice.php").as_deref(),
347 Some("src/Domains/Billing/Invoice.php")
348 );
349 assert_eq!(container("Modules", "/var/www/html/Modules/x.php"), None);
350 assert_eq!(
353 container(
354 "Modules",
355 "/srv/Modules/shop-api/Modules/Billing/app/Models/Invoice.php"
356 )
357 .as_deref(),
358 Some("Modules/Billing/app/Models/Invoice.php")
359 );
360 assert_eq!(
363 app_relative(
364 Path::new("/Users/me/shop"),
365 "Modules",
366 &["loyalty"],
367 &["Billing"],
368 "/srv/Modules/Billing/Modules/Loyalty/module.json"
369 )
370 .as_deref(),
371 Some("Modules/Loyalty/module.json")
372 );
373 assert_eq!(
376 app_relative(
377 Path::new("/Users/me/shop"),
378 "Modules",
379 &["Billing"],
380 &["Billing"],
381 "/var/www/html/Modules/Billing/app/Models/Admin/Modules/Billing/Invoice.php"
382 )
383 .as_deref(),
384 Some("Modules/Billing/app/Models/Admin/Modules/Billing/Invoice.php")
385 );
386 }
387
388 #[test]
389 fn a_failed_autoload_is_read_from_its_error_line() {
390 assert!(!autoload_failed(&recording("module-make-api")));
391 assert!(autoload_failed(&[
392 " \x1b[37;41m ERROR \x1b[39;49m composer dump-autoload failed. ".to_string()
393 ]));
394 }
395}