use std::collections::BTreeSet;
use crate::run::ansi::plain;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailedMigration {
pub module: Option<String>,
pub migration: String,
}
pub fn failed_migration(lines: &[String]) -> Option<FailedMigration> {
let mut module = None;
for line in lines {
let line = plain(line);
if let Some(name) = running_module(&line) {
module = Some(name.to_string());
} else if let Some((migration, "FAIL")) = migration_line(&line) {
return Some(FailedMigration {
module,
migration: migration.to_string(),
});
}
}
None
}
const PROHIBITED: &str = "This command is prohibited from running in this environment.";
pub fn prohibited(lines: &[String]) -> bool {
lines
.iter()
.any(|line| plain(line).trim().ends_with(PROHIBITED))
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MigrationCount {
pub ran: usize,
pub rolled_back: usize,
}
pub fn migration_count(lines: &[String]) -> MigrationCount {
let mut ran = 0;
let mut rolled_back = BTreeSet::new();
for line in lines {
let line = plain(line);
if let Some(name) = rolled_back_name(&line) {
if line.trim_end().rsplit(' ').next() != Some("FAIL") {
rolled_back.insert(name.to_string());
}
} else if let Some((_, "DONE")) = migration_line(&line) {
ran += 1;
}
}
MigrationCount {
ran,
rolled_back: rolled_back.len(),
}
}
fn running_module(line: &str) -> Option<&str> {
let mut words = line.trim().strip_prefix("Running Migration ")?.split(' ');
let name = words.next()?;
(words.next() == Some("Module")).then_some(name)
}
fn migration_line(line: &str) -> Option<(&str, &str)> {
let line = line.trim();
let line = line.strip_prefix("Rollback: ").unwrap_or(line);
let name = line.split(' ').next()?;
let end = line.rsplit(' ').next()?;
(migration_name(name) && matches!(end, "DONE" | "FAIL")).then_some((name, end))
}
fn rolled_back_name(line: &str) -> Option<&str> {
let (_, rest) = line.split_once("Rollback: ")?;
let name = rest.split(' ').next()?.trim_end();
migration_name(name).then_some(name)
}
fn migration_name(name: &str) -> bool {
const SHAPE: &[u8] = b"dddd_dd_dd_dddddd_";
name.len() > SHAPE.len()
&& name.bytes().zip(SHAPE).all(|(byte, &shape)| match shape {
b'd' => byte.is_ascii_digit(),
_ => byte == shape,
})
}
#[cfg(test)]
pub(crate) mod tests {
use std::path::Path;
use super::*;
const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
pub(crate) fn recording(name: &str) -> Vec<String> {
let path = Path::new(FIXTURES)
.join("output")
.join(format!("{name}.json"));
let json: serde_json::Value =
serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
json["stdout"]
.as_str()
.unwrap()
.lines()
.map(str::to_owned)
.collect()
}
#[test]
fn a_failing_migrate_names_its_migration_and_module() {
let lines = recording("module-migrate-failing-migration");
assert_eq!(
failed_migration(&lines),
Some(FailedMigration {
module: Some("Shipping".to_string()),
migration: "2026_11_22_140500_add_tracking_code_to_shipments_table".to_string(),
})
);
assert_eq!(migration_count(&lines), MigrationCount::default());
}
#[test]
fn a_run_counts_what_ran_and_what_rolled_back() {
let lines = recording("module-migrate-one-migration");
assert_eq!(failed_migration(&lines), None);
let table = [
("module-migrate-one-migration", 1, 0),
("module-migrate-rollback", 0, 1),
("module-migrate-reset", 0, 3),
("module-migrate-reset-pretend", 0, 0),
("module-migrate-refresh", 3, 3),
("module-migrate-fresh-all", 8, 0),
];
for (name, ran, rolled_back) in table {
assert_eq!(
migration_count(&recording(name)),
MigrationCount { ran, rolled_back },
"{name}"
);
}
}
#[test]
fn a_plain_failure_names_no_migration() {
let lines = recording("module-failing");
assert_eq!(failed_migration(&lines), None);
assert!(!prohibited(&lines));
}
#[test]
fn a_prohibited_command_reads_as_prohibited() {
let lines = recording("module-migrate-reset-prohibited");
assert!(prohibited(&lines));
assert_eq!(failed_migration(&lines), None);
}
}