use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::modules::composer::Version;
use crate::modules::module::Module;
use crate::modules::target::Target;
use crate::php;
pub fn gives_data(version: &Version) -> bool {
released_since(version, (13, 4))
}
pub fn stores_surface(version: &Version) -> bool {
released_since(version, (13, 5))
}
fn released_since(version: &Version, since: (u64, u64)) -> bool {
let parts: Vec<&str> = version.full().split('.').collect();
let [major, minor, patch] = parts.as_slice() else {
return false;
};
let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
if !(digits(major) && digits(minor) && digits(patch)) {
return false;
}
match (major.parse::<u64>(), minor.parse::<u64>()) {
(Ok(major), Ok(minor)) => (major, minor) >= since,
_ => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DataError {
Missing,
Malformed(String),
Cut,
}
pub fn document<T: DeserializeOwned>(stdout: &[String]) -> Result<T, DataError> {
let line = stdout
.iter()
.rev()
.map(|line| line.trim())
.find(|line| !line.is_empty())
.ok_or(DataError::Missing)?;
serde_json::from_str(line).map_err(|error| DataError::Malformed(error.to_string()))
}
pub fn whole_document<T: DeserializeOwned>(stdout: &[String], cut: bool) -> Result<T, DataError> {
if cut {
return Err(DataError::Cut);
}
document(stdout)
}
pub fn has_option(words: &[String], option: &str) -> bool {
words
.iter()
.take_while(|word| *word != "--")
.any(|word| word == option)
}
pub fn with_json(words: Vec<String>) -> Vec<String> {
with_flags(words, &["--json"])
}
pub fn with_dry_run(words: Vec<String>) -> Vec<String> {
with_flags(words, &["--dry-run", "--json"])
}
pub fn migrate_status_args(target: &Target, database: &str) -> Vec<String> {
let mut words = vec!["module:migrate-status".to_string()];
let mut last = None;
match target {
Target::Module(name) if name.starts_with('-') => last = Some(name.clone()),
Target::Module(name) => words.push(name.clone()),
Target::All => words.push("--all".to_string()),
}
let database = database.trim();
if !database.is_empty() {
words.push(format!("--database={database}"));
}
if let Some(name) = last {
words.extend(["--".to_string(), name]);
}
with_json(words)
}
pub fn migrations_changed_by(args: &[String]) -> Option<Target> {
const CHANGE: [&str; 5] = [
"module:migrate",
"module:migrate-rollback",
"module:migrate-reset",
"module:migrate-refresh",
"module:migrate-fresh",
];
let command = args
.first()
.filter(|word| CHANGE.contains(&word.as_str()))?;
if has_option(args, "--pretend") {
return None;
}
let at = args.iter().position(|word| word == "--");
let options = &args[..at.unwrap_or(args.len())];
let module = match at {
Some(at) => args.get(at + 1),
None => options.get(1).filter(|word| !word.starts_with('-')),
};
match module {
Some(name) if command != "module:migrate-fresh" && !has_option(args, "--all") => {
Some(Target::Module(name.clone()))
}
_ => Some(Target::All),
}
}
fn with_flags(mut words: Vec<String>, flags: &[&str]) -> Vec<String> {
let at = words
.iter()
.position(|word| word == "--")
.unwrap_or(words.len());
let added: Vec<String> = flags
.iter()
.filter(|flag| !has_option(&words, flag))
.map(|flag| flag.to_string())
.collect();
words.splice(at..at, added);
words
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct GeneratorReport {
pub command: String,
pub dry_run: bool,
pub files: Vec<ReportedFile>,
pub errors: Vec<String>,
}
impl GeneratorReport {
pub fn autoload_failed(&self) -> bool {
self.errors
.iter()
.any(|error| error.trim().ends_with("composer dump-autoload failed."))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ReportedFile {
pub path: String,
pub exists: bool,
pub action: FileAction,
#[serde(default)]
pub result: Option<FileResult>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileAction {
Create,
Replace,
Keep,
Delete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileResult {
Created,
Replaced,
Exists,
Deleted,
Failed,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct MigrationStatus {
pub modules: Vec<ModuleStatus>,
pub migration_table: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ModuleStatus {
pub name: String,
pub migrations: Vec<MigrationRow>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct MigrationRow {
pub name: String,
pub ran: bool,
#[serde(default)]
pub batch: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct TestReport {
pub modules: Vec<ModuleTests>,
pub passed: Option<u32>,
pub failed: Option<u32>,
pub skipped: Option<u32>,
pub exit_code: Option<i32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ModuleTests {
pub name: String,
pub ran: bool,
pub passed: Option<u32>,
pub failed: Option<u32>,
pub skipped: Option<u32>,
pub exit_code: Option<i32>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LangReport {
pub modules: Vec<LangModule>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LangModule {
pub name: String,
pub checked: bool,
pub locales: BTreeMap<String, Locale>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Locale {
pub missing_files: Vec<String>,
pub missing_keys: BTreeMap<String, Vec<String>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PackageData {
pub migrations: BTreeMap<String, ModuleMigrations>,
pub migration_connection: String,
pub migrations_of_all: BTreeSet<String>,
pub migration_table: Option<bool>,
pub translations: Option<LangReport>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModuleMigrations {
pub ran: Vec<RanMigration>,
pub waiting: Vec<String>,
pub tables: Vec<String>,
pub read_ms: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RanMigration {
pub name: String,
pub batch: u32,
}
impl ModuleMigrations {
pub fn last_batch(&self) -> Vec<&RanMigration> {
let Some(last) = self.ran.iter().map(|ran| ran.batch).max() else {
return Vec::new();
};
self.ran.iter().filter(|ran| ran.batch == last).collect()
}
}
impl PackageData {
pub fn migrations_for(&self, connection: &str) -> Option<&BTreeMap<String, ModuleMigrations>> {
(self.migration_connection == connection.trim()).then_some(&self.migrations)
}
pub fn migrations_of_every(&self, connection: &str, modules_on: &[&str]) -> bool {
self.migrations_for(connection).is_some_and(|migrations| {
modules_on.iter().all(|name| {
migrations.contains_key(*name) || self.migrations_of_all.contains(*name)
})
})
}
pub fn forget_migrations(&mut self, target: &Target) -> bool {
let before = (
self.migrations.len(),
self.migration_table,
self.migrations_of_all.len(),
);
match target {
Target::All => self.migrations.clear(),
Target::Module(name) => self
.migrations
.retain(|module, _| !module.eq_ignore_ascii_case(name)),
}
if self.migration_table == Some(false) {
self.migration_table = None;
}
self.migrations_of_all.clear();
before
!= (
self.migrations.len(),
self.migration_table,
self.migrations_of_all.len(),
)
}
pub fn merge_migrations(
&mut self,
status: MigrationStatus,
target: &Target,
connection: &str,
modules_on: &[&str],
read_ms: i64,
) {
let connection = connection.trim();
if self.migration_connection != connection {
self.migrations.clear();
self.migration_connection = connection.to_string();
self.migrations_of_all.clear();
}
if *target == Target::All {
self.migrations_of_all = modules_on.iter().map(|name| name.to_string()).collect();
let listed: BTreeSet<&str> = status
.modules
.iter()
.map(|module| module.name.as_str())
.collect();
self.migrations.retain(|name, _| {
listed.contains(name.as_str()) || !modules_on.contains(&name.as_str())
});
}
for module in status.modules {
let mut entry = ModuleMigrations {
read_ms,
..ModuleMigrations::default()
};
for migration in module.migrations {
if migration.ran {
entry.ran.push(RanMigration {
name: migration.name,
batch: migration.batch.unwrap_or_default(),
});
} else {
entry.waiting.push(migration.name);
}
}
entry.ran.sort_by(|a, b| a.name.cmp(&b.name));
entry.waiting.sort();
self.migrations.insert(module.name, entry);
}
self.migration_table = Some(status.migration_table);
}
pub fn merge_translations(&mut self, report: LangReport) {
let kept = self.translations.get_or_insert_default();
for module in report.modules {
kept.modules.retain(|old| old.name != module.name);
kept.modules.push(module);
}
kept.modules.sort_by(|a, b| a.name.cmp(&b.name));
}
pub(crate) fn with_tables(&self, modules: &[Module]) -> PackageData {
let mut data = self.clone();
for (name, state) in &mut data.migrations {
state.tables.clear();
let Some(module) = modules.iter().find(|module| &module.name == name) else {
continue;
};
for ran in &state.ran {
let source = migration_file(&module.dir, &ran.name)
.and_then(|path| std::fs::read_to_string(path).ok());
for table in source
.as_deref()
.map(php::created_tables)
.unwrap_or_default()
{
if !state.tables.contains(&table) {
state.tables.push(table);
}
}
}
}
data
}
}
pub fn migration_file(module_dir: &Path, migration: &str) -> Option<PathBuf> {
let path = module_dir
.join("database")
.join("migrations")
.join(format!("{migration}.php"));
path.is_file().then_some(path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::generate::catalog::generator_gives_data;
const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
fn version(raw: &str, alias: Option<&str>) -> Version {
Version {
raw: raw.into(),
alias: alias.map(String::from),
}
}
fn stdout(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(String::from)
.collect()
}
fn words(words: &[&str]) -> Vec<String> {
words.iter().map(|word| word.to_string()).collect()
}
#[test]
fn only_a_released_13_4_or_later_gives_data() {
let cases = [
(version("v13.4.0", None), true),
(version("13.4.0", None), true),
(version("13.3.9", None), false),
(version("14.0.0", None), true),
(version("13.4.0-RC1", None), false),
(version("dev-master", Some("13.x-dev")), false),
];
for (version, gives) in cases {
assert_eq!(gives_data(&version), gives, "{}", version.raw);
}
assert!(!stores_surface(&version("v13.4.0", None)));
assert!(stores_surface(&version("v13.5.0", None)));
let v13_4 = version("13.4.0", None);
assert!(generator_gives_data(&v13_4, "module:make"));
assert!(generator_gives_data(&v13_4, "module:make-health-indicator"));
assert!(!generator_gives_data(&v13_4, "app:make-widget"));
assert!(!generator_gives_data(&v13_4, "module:make-widget"));
assert!(!generator_gives_data(
&version("13.3.0", None),
"module:make-model"
));
}
#[test]
fn documents_are_read_from_the_last_line_of_standard_output() {
let dry_run: GeneratorReport =
document(&stdout("module-make-model-policy-exists-dry-run")).unwrap();
assert!(dry_run.dry_run);
assert_eq!(dry_run.files.len(), 3);
let policy = &dry_run.files[2];
assert!(policy.exists && policy.path.ends_with("/Policies/InvoicePolicy.php"));
assert_eq!((policy.action, policy.result), (FileAction::Keep, None));
assert_eq!(dry_run.errors.len(), 1);
let run: GeneratorReport =
document(&stdout("module-make-model-policy-exists-json")).unwrap();
assert_eq!(run.files[0].result, Some(FileResult::Created));
assert_eq!(run.files[2].result, Some(FileResult::Exists));
let status: MigrationStatus = document(&stdout("module-migrate-status-waiting")).unwrap();
assert!(status.migration_table);
let checkout = &status.modules[0].migrations;
assert_eq!((checkout[0].ran, checkout[0].batch), (true, Some(1)));
assert_eq!((checkout[1].ran, checkout[1].batch), (false, None));
let tests: TestReport = document(&stdout("module-test-all")).unwrap();
assert_eq!(
(tests.passed, tests.failed, tests.exit_code),
(Some(1), Some(1), Some(1))
);
assert_eq!(tests.modules[1].failed, Some(1));
let lang: LangReport = document(&stdout("module-lang-all-json")).unwrap();
assert!(!lang.modules[0].checked && lang.modules[0].locales.is_empty());
assert_eq!(
lang.modules[1].locales["fr"].missing_keys["messages.php"],
["tracking_code", "order_placed"]
);
let lines = words(&["Warning: something", r#"{"modules":[]}"#, " "]);
assert_eq!(document::<LangReport>(&lines), Ok(LangReport::default()));
assert_eq!(
document::<LangReport>(&words(&["", " "])),
Err(DataError::Missing)
);
assert!(matches!(
document::<LangReport>(&words(&["Command \"module:lang\" is not defined."])),
Err(DataError::Malformed(_))
));
}
#[test]
fn json_goes_before_a_double_dash() {
assert_eq!(
with_json(words(&["module:make-model", "Invoice", "Billing"])),
words(&["module:make-model", "Invoice", "Billing", "--json"])
);
assert_eq!(
with_dry_run(words(&["module:make", "--", "--force"])),
words(&["module:make", "--dry-run", "--json", "--", "--force"])
);
assert_eq!(
migrate_status_args(&Target::Module("-Odd".into()), " testing "),
words(&[
"module:migrate-status",
"--database=testing",
"--json",
"--",
"-Odd"
])
);
assert_eq!(
with_json(words(&["module:make-model", "Invoice", "--json"])),
words(&["module:make-model", "Invoice", "--json"])
);
assert_eq!(
with_json(words(&["module:make-model", "Invoice", "--", "--json"])),
words(&["module:make-model", "Invoice", "--json", "--", "--json"])
);
}
#[test]
fn a_migration_command_changes_the_state_of_its_target() {
let changed = |line: &[&str]| migrations_changed_by(&words(line));
let checkout = Some(Target::Module("Checkout".into()));
assert_eq!(
changed(&["module:migrate", "Checkout", "--database=testing"]),
checkout
);
assert_eq!(
changed(&["module:migrate-rollback", "--", "Checkout"]),
checkout
);
assert_eq!(
changed(&["module:migrate-refresh", "--all"]),
Some(Target::All)
);
assert_eq!(
changed(&["module:migrate-fresh", "--force"]),
Some(Target::All)
);
assert_eq!(
changed(&["module:migrate-reset", "--force"]),
Some(Target::All)
);
assert_eq!(changed(&["module:migrate", "Checkout", "--pretend"]), None);
assert_eq!(changed(&["module:migrate-status", "Checkout"]), None);
assert_eq!(changed(&["module:seed", "Checkout"]), None);
}
#[test]
fn a_read_replaces_the_modules_it_holds() {
let mut data = PackageData::default();
let all: MigrationStatus = document(&stdout("module-migrate-status-all")).unwrap();
data.merge_migrations(
all,
&Target::All,
"",
&["Billing", "Checkout", "Loyalty", "Shipping"],
1,
);
assert!(data.migrations_of_every("", &["Checkout", "Shipping"]));
assert!(!data.migrations_of_every("", &["Checkout", "Catalog"]));
let checkout = &data.migrations["Checkout"];
assert_eq!(
checkout.waiting,
["2026_11_23_120000_create_order_items_table"]
);
assert_eq!(
checkout.last_batch()[0].name,
"2026_11_23_110149_create_orders_table"
);
assert_eq!(data.migrations["Billing"].waiting.len(), 2);
let two: MigrationStatus = document(&stdout("module-migrate-status-no-table")).unwrap();
data.merge_migrations(two, &Target::Module("Checkout".into()), "", &[], 2);
assert_eq!(data.migration_table, Some(false));
assert_eq!(data.migrations["Checkout"].ran, []);
assert_eq!(data.migrations["Checkout"].read_ms, 2);
assert_eq!(data.migrations["Loyalty"].read_ms, 1);
let none = MigrationStatus {
modules: Vec::new(),
migration_table: true,
};
data.merge_migrations(none.clone(), &Target::All, "", &["Checkout", "Loyalty"], 3);
assert_eq!(data.migrations.keys().collect::<Vec<_>>(), ["Billing"]);
data.migration_table = Some(false);
assert!(data.forget_migrations(&Target::Module("billing".into())));
assert!(!data.migrations_of_every("", &["Catalog"]));
assert!(data.migrations.is_empty() && data.migration_table.is_none());
assert!(!data.forget_migrations(&Target::All));
assert!(data.migrations_for("testing").is_none());
data.merge_migrations(none, &Target::Module("Checkout".into()), "testing", &[], 4);
assert!(data.migrations_for("").is_none());
assert_eq!(data.migrations_for(" testing").map(BTreeMap::len), Some(0));
data.merge_translations(document(&stdout("module-lang-all-json")).unwrap());
let mut one: LangReport = document(&stdout("module-lang-all-json")).unwrap();
one.modules.retain(|module| module.name == "Checkout");
one.modules[0].locales.clear();
data.merge_translations(one);
let kept = &data.translations.as_ref().unwrap().modules;
let names: Vec<&str> = kept.iter().map(|module| module.name.as_str()).collect();
assert_eq!(names, ["Billing", "Checkout", "Loyalty"]);
assert!(kept[1].locales.is_empty());
}
#[test]
fn a_migration_file_is_found_only_when_it_exists() {
let billing = Path::new(FIXTURES).join("shop-api/Modules/Billing");
let name = "2026_01_10_000000_create_invoices_table";
assert_eq!(
migration_file(&billing, name),
Some(
billing
.join("database/migrations")
.join(format!("{name}.php"))
)
);
assert_eq!(
migration_file(&billing, "2026_01_11_000000_create_refunds_table"),
None
);
}
}