Skip to main content

mortise_core/generate/
output.rs

1//! What the output of a run says about generated files.
2//!
3//! A generator prints `Generating file <path> ... <time> DONE` or `FAIL` for each
4//! file. A `FAIL` is followed by an error line `File : <path> already exists.`
5//! when the file is there. `module:make` prints `composer dump-autoload failed.`
6//! when the autoload step fails.
7//!
8//! From 13.4.0 on a generator run with `--json` gives its files as a document
9//! ([`GeneratorReport`]); [`reported_files`] reads it into the same rows.
10
11use std::path::Path;
12
13use crate::package::{FileResult, GeneratorReport};
14use crate::run::ansi::plain;
15
16/// What a generator run did with one file.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum FileOutcome {
19    /// The file is new.
20    Created,
21    /// The file existed and the run, which carried `--force`, wrote it again.
22    Replaced,
23    /// The file exists and the run did not write it.
24    Left,
25    /// The file was not written for another reason.
26    Failed,
27}
28
29/// One file of a generator run.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct GeneratedFile {
32    /// The path as the output prints it.
33    pub path: String,
34    pub outcome: FileOutcome,
35}
36
37/// The files of a generator run, in output order. `force` is true when the run
38/// carried `--force`.
39///
40/// The exit code does not say what happened to each file: `module:make-model`
41/// exits 0 when it leaves its policy.
42pub 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
73/// The files of a generator run from its document (P5), in write order. The folder
74/// that `module:make --force` deletes is not a file. A path is made relative to the
75/// app folder `root`, as the output lines print it, through [`app_relative`] with the
76/// modules folder `modules`; a path it cannot place stays as printed.
77pub 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
102/// A path the package printed, relative to the app folder `root` with `/` between its
103/// parts, or `None` when Mortise cannot place it. The package prints absolute paths
104/// with `/` on every platform, from the real folder of the app, so `root` is compared
105/// as given and with its links resolved.
106///
107/// PHP in a container (Sail, Docker) prints the folder of the container, such as
108/// `/var/www/html/Modules/Billing/app/Models/Invoice.php`. A path outside `root` is
109/// then read from a part `/<modules>/<Module>/` on, where `modules` is the modules
110/// folder relative to the app (`Modules`): `Modules/Billing/app/Models/Invoice.php`.
111/// The container's folder may hold that name too (`/srv/Modules/shop-api/Modules/...`),
112/// and so may the class name (`.../Models/Admin/Modules/Billing/Invoice.php`). The
113/// first part counts whose `<Module>` is one of `names`, the modules the run writes
114/// in: its own module, or those `module:make` asks for (the package makes them
115/// studly: case, `-` and `_` do not count). Else the first part whose `<Module>` is
116/// one of `folders`, the folder names of the app's modules, counts, and with none of
117/// them, the last part.
118pub 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            // A resolved path on Windows starts with `\\?\`.
132            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
140/// The part of `printed` from a `/<modules>/<Module>/` on, when a file follows: the
141/// first whose `<Module>` is one of `names`, else the first whose `<Module>` is one of
142/// `folders`, else the last.
143fn 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
172/// True when the output says that `composer dump-autoload` failed.
173pub 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
181/// The path and the result (`true` for `DONE`) of a `Generating file` line. The
182/// path ends before the dots and the time.
183fn 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
200/// A time such as `0.24ms` or `1s`.
201fn is_time(word: &str) -> bool {
202    word.starts_with(|c: char| c.is_ascii_digit()) && word.ends_with('s')
203}
204
205/// The path of a `File : <path> already exists.` line.
206fn 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        // The model run exits 0 and leaves only its policy.
252        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        // The answer says the policy exists, as the lines do.
308        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        // PHP in a container prints the container's folder: the path is read from
327        // the modules folder of the app's layout on.
328        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        // A container folder that holds the name of the modules folder: the part of a
351        // module of the app counts.
352        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        // A new module comes before a known one: `module:make loyalty` placed in a
361        // container folder named after Billing.
362        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        // A class name that repeats the module's part: the first part of the run's
374        // own module counts.
375        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}