Skip to main content

mortise_core/actions/
output.rs

1//! What the output of a run says about migrations and a refusal.
2//!
3//! Laravel prints one task line per migration: the name, dots, a time and `DONE`
4//! or `FAIL`. The package prints `Running Migration <Name> Module` before the
5//! migrations of each module. A roll back prints `Rollback: <name>` as a task
6//! line, and a reset prints it as a line of its own. The reading depends on these
7//! words, which Laravel and the package can change.
8
9use std::collections::BTreeSet;
10
11use crate::run::ansi::plain;
12
13/// The migration at which a run failed.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct FailedMigration {
16    /// The module of the last `Running Migration` line before the failure.
17    pub module: Option<String>,
18    /// The name of the migration, without `.php`.
19    pub migration: String,
20}
21
22/// The first migration that failed, or `None` when no migration line failed.
23pub fn failed_migration(lines: &[String]) -> Option<FailedMigration> {
24    let mut module = None;
25    for line in lines {
26        let line = plain(line);
27        if let Some(name) = running_module(&line) {
28            module = Some(name.to_string());
29        } else if let Some((migration, "FAIL")) = migration_line(&line) {
30            return Some(FailedMigration {
31                module,
32                migration: migration.to_string(),
33            });
34        }
35    }
36    None
37}
38
39/// The sentence of Laravel's `Prohibitable` when an app prohibits a command.
40const PROHIBITED: &str = "This command is prohibited from running in this environment.";
41
42/// True when the output says that the app prohibits the command. Laravel's warn
43/// component prints the sentence after ` WARN `.
44pub fn prohibited(lines: &[String]) -> bool {
45    lines
46        .iter()
47        .any(|line| plain(line).trim().ends_with(PROHIBITED))
48}
49
50/// The migrations that a run ran and rolled back.
51#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
52pub struct MigrationCount {
53    /// Migration lines that end with `DONE`, without `Rollback: `.
54    pub ran: usize,
55    /// Migrations rolled back, each name once.
56    pub rolled_back: usize,
57}
58
59/// What the migration lines of a run say it ran and rolled back.
60///
61/// A rollback that ends with `FAIL` is not counted. A refresh prints its first
62/// `Rollback: ` after its own task label, on the same line, so the name is
63/// looked for anywhere in the line.
64pub fn migration_count(lines: &[String]) -> MigrationCount {
65    let mut ran = 0;
66    let mut rolled_back = BTreeSet::new();
67    for line in lines {
68        let line = plain(line);
69        if let Some(name) = rolled_back_name(&line) {
70            if line.trim_end().rsplit(' ').next() != Some("FAIL") {
71                rolled_back.insert(name.to_string());
72            }
73        } else if let Some((_, "DONE")) = migration_line(&line) {
74            ran += 1;
75        }
76    }
77    MigrationCount {
78        ran,
79        rolled_back: rolled_back.len(),
80    }
81}
82
83/// The module of a `Running Migration <Name> Module` line.
84fn running_module(line: &str) -> Option<&str> {
85    let mut words = line.trim().strip_prefix("Running Migration ")?.split(' ');
86    let name = words.next()?;
87    (words.next() == Some("Module")).then_some(name)
88}
89
90/// The name and the last word of a migration line. The line starts, after
91/// spaces, with a migration name, and ends with `DONE` or `FAIL`. A rollback
92/// puts `Rollback: ` before the name.
93fn migration_line(line: &str) -> Option<(&str, &str)> {
94    let line = line.trim();
95    let line = line.strip_prefix("Rollback: ").unwrap_or(line);
96    let name = line.split(' ').next()?;
97    let end = line.rsplit(' ').next()?;
98    (migration_name(name) && matches!(end, "DONE" | "FAIL")).then_some((name, end))
99}
100
101/// The migration name after `Rollback: ` in a line.
102fn rolled_back_name(line: &str) -> Option<&str> {
103    let (_, rest) = line.split_once("Rollback: ")?;
104    let name = rest.split(' ').next()?.trim_end();
105    migration_name(name).then_some(name)
106}
107
108/// A name of the form `dddd_dd_dd_dddddd_` and more.
109fn migration_name(name: &str) -> bool {
110    const SHAPE: &[u8] = b"dddd_dd_dd_dddddd_";
111    name.len() > SHAPE.len()
112        && name.bytes().zip(SHAPE).all(|(byte, &shape)| match shape {
113            b'd' => byte.is_ascii_digit(),
114            _ => byte == shape,
115        })
116}
117
118#[cfg(test)]
119pub(crate) mod tests {
120    use std::path::Path;
121
122    use super::*;
123
124    const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
125
126    /// The lines of the stdout of a recording in `fixtures/output`.
127    pub(crate) fn recording(name: &str) -> Vec<String> {
128        let path = Path::new(FIXTURES)
129            .join("output")
130            .join(format!("{name}.json"));
131        let json: serde_json::Value =
132            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
133        json["stdout"]
134            .as_str()
135            .unwrap()
136            .lines()
137            .map(str::to_owned)
138            .collect()
139    }
140
141    #[test]
142    fn a_failing_migrate_names_its_migration_and_module() {
143        let lines = recording("module-migrate-failing-migration");
144        assert_eq!(
145            failed_migration(&lines),
146            Some(FailedMigration {
147                module: Some("Shipping".to_string()),
148                migration: "2026_11_22_140500_add_tracking_code_to_shipments_table".to_string(),
149            })
150        );
151        assert_eq!(migration_count(&lines), MigrationCount::default());
152    }
153
154    #[test]
155    fn a_run_counts_what_ran_and_what_rolled_back() {
156        let lines = recording("module-migrate-one-migration");
157        assert_eq!(failed_migration(&lines), None);
158        // The recording, the migrations that ran, those rolled back.
159        let table = [
160            ("module-migrate-one-migration", 1, 0),
161            // A roll back prints a task line: `Rollback: <name> ... DONE`.
162            ("module-migrate-rollback", 0, 1),
163            // A reset prints `Rollback: <name>` lines with no `DONE`.
164            ("module-migrate-reset", 0, 3),
165            // A dry run prints the names with no `DONE`.
166            ("module-migrate-reset-pretend", 0, 0),
167            // A refresh glues its first `Rollback: ` to its own task label.
168            ("module-migrate-refresh", 3, 3),
169            // A fresh runs the migrations of the app too.
170            ("module-migrate-fresh-all", 8, 0),
171        ];
172        for (name, ran, rolled_back) in table {
173            assert_eq!(
174                migration_count(&recording(name)),
175                MigrationCount { ran, rolled_back },
176                "{name}"
177            );
178        }
179    }
180
181    #[test]
182    fn a_plain_failure_names_no_migration() {
183        let lines = recording("module-failing");
184        assert_eq!(failed_migration(&lines), None);
185        assert!(!prohibited(&lines));
186    }
187
188    #[test]
189    fn a_prohibited_command_reads_as_prohibited() {
190        let lines = recording("module-migrate-reset-prohibited");
191        assert!(prohibited(&lines));
192        assert_eq!(failed_migration(&lines), None);
193    }
194}