1use std::collections::{BTreeMap, BTreeSet};
8use std::path::{Path, PathBuf};
9
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Serialize};
12
13use crate::modules::composer::Version;
14use crate::modules::module::Module;
15use crate::modules::target::Target;
16use crate::php;
17
18pub fn gives_data(version: &Version) -> bool {
23 released_since(version, (13, 4))
24}
25
26pub fn stores_surface(version: &Version) -> bool {
29 released_since(version, (13, 5))
30}
31
32fn released_since(version: &Version, since: (u64, u64)) -> bool {
34 let parts: Vec<&str> = version.full().split('.').collect();
35 let [major, minor, patch] = parts.as_slice() else {
36 return false;
37 };
38 let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
39 if !(digits(major) && digits(minor) && digits(patch)) {
40 return false;
41 }
42 match (major.parse::<u64>(), minor.parse::<u64>()) {
43 (Ok(major), Ok(minor)) => (major, minor) >= since,
44 _ => false,
45 }
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum DataError {
51 Missing,
53 Malformed(String),
55 Cut,
58}
59
60pub fn document<T: DeserializeOwned>(stdout: &[String]) -> Result<T, DataError> {
64 let line = stdout
65 .iter()
66 .rev()
67 .map(|line| line.trim())
68 .find(|line| !line.is_empty())
69 .ok_or(DataError::Missing)?;
70 serde_json::from_str(line).map_err(|error| DataError::Malformed(error.to_string()))
71}
72
73pub fn whole_document<T: DeserializeOwned>(stdout: &[String], cut: bool) -> Result<T, DataError> {
76 if cut {
77 return Err(DataError::Cut);
78 }
79 document(stdout)
80}
81
82pub fn has_option(words: &[String], option: &str) -> bool {
85 words
86 .iter()
87 .take_while(|word| *word != "--")
88 .any(|word| word == option)
89}
90
91pub fn with_json(words: Vec<String>) -> Vec<String> {
94 with_flags(words, &["--json"])
95}
96
97pub fn with_dry_run(words: Vec<String>) -> Vec<String> {
100 with_flags(words, &["--dry-run", "--json"])
101}
102
103pub fn migrate_status_args(target: &Target, database: &str) -> Vec<String> {
108 let mut words = vec!["module:migrate-status".to_string()];
109 let mut last = None;
110 match target {
111 Target::Module(name) if name.starts_with('-') => last = Some(name.clone()),
112 Target::Module(name) => words.push(name.clone()),
113 Target::All => words.push("--all".to_string()),
114 }
115 let database = database.trim();
116 if !database.is_empty() {
117 words.push(format!("--database={database}"));
118 }
119 if let Some(name) = last {
120 words.extend(["--".to_string(), name]);
121 }
122 with_json(words)
123}
124
125pub fn migrations_changed_by(args: &[String]) -> Option<Target> {
131 const CHANGE: [&str; 5] = [
132 "module:migrate",
133 "module:migrate-rollback",
134 "module:migrate-reset",
135 "module:migrate-refresh",
136 "module:migrate-fresh",
137 ];
138 let command = args
139 .first()
140 .filter(|word| CHANGE.contains(&word.as_str()))?;
141 if has_option(args, "--pretend") {
142 return None;
143 }
144 let at = args.iter().position(|word| word == "--");
145 let options = &args[..at.unwrap_or(args.len())];
146 let module = match at {
147 Some(at) => args.get(at + 1),
148 None => options.get(1).filter(|word| !word.starts_with('-')),
149 };
150 match module {
151 Some(name) if command != "module:migrate-fresh" && !has_option(args, "--all") => {
152 Some(Target::Module(name.clone()))
153 }
154 _ => Some(Target::All),
155 }
156}
157
158fn with_flags(mut words: Vec<String>, flags: &[&str]) -> Vec<String> {
159 let at = words
160 .iter()
161 .position(|word| word == "--")
162 .unwrap_or(words.len());
163 let added: Vec<String> = flags
164 .iter()
165 .filter(|flag| !has_option(&words, flag))
166 .map(|flag| flag.to_string())
167 .collect();
168 words.splice(at..at, added);
169 words
170}
171
172#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
174pub struct GeneratorReport {
175 pub command: String,
177 pub dry_run: bool,
178 pub files: Vec<ReportedFile>,
180 pub errors: Vec<String>,
182}
183
184impl GeneratorReport {
185 pub fn autoload_failed(&self) -> bool {
187 self.errors
188 .iter()
189 .any(|error| error.trim().ends_with("composer dump-autoload failed."))
190 }
191}
192
193#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
195pub struct ReportedFile {
196 pub path: String,
198 pub exists: bool,
200 pub action: FileAction,
201 #[serde(default)]
203 pub result: Option<FileResult>,
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
208#[serde(rename_all = "lowercase")]
209pub enum FileAction {
210 Create,
211 Replace,
212 Keep,
214 Delete,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
220#[serde(rename_all = "lowercase")]
221pub enum FileResult {
222 Created,
223 Replaced,
224 Exists,
225 Deleted,
226 Failed,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
231pub struct MigrationStatus {
232 pub modules: Vec<ModuleStatus>,
233 pub migration_table: bool,
235}
236
237#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
239pub struct ModuleStatus {
240 pub name: String,
241 pub migrations: Vec<MigrationRow>,
243}
244
245#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
247pub struct MigrationRow {
248 pub name: String,
250 pub ran: bool,
251 #[serde(default)]
253 pub batch: Option<u32>,
254}
255
256#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
258pub struct TestReport {
259 pub modules: Vec<ModuleTests>,
260 pub passed: Option<u32>,
261 pub failed: Option<u32>,
262 pub skipped: Option<u32>,
263 pub exit_code: Option<i32>,
264}
265
266#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
269pub struct ModuleTests {
270 pub name: String,
271 pub ran: bool,
273 pub passed: Option<u32>,
274 pub failed: Option<u32>,
275 pub skipped: Option<u32>,
276 pub exit_code: Option<i32>,
277}
278
279#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
281pub struct LangReport {
282 pub modules: Vec<LangModule>,
284}
285
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288pub struct LangModule {
289 pub name: String,
290 pub checked: bool,
292 pub locales: BTreeMap<String, Locale>,
294}
295
296#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
298pub struct Locale {
299 pub missing_files: Vec<String>,
301 pub missing_keys: BTreeMap<String, Vec<String>>,
303}
304
305#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
309pub struct PackageData {
310 pub migrations: BTreeMap<String, ModuleMigrations>,
312 pub migration_connection: String,
315 pub migrations_of_all: BTreeSet<String>,
319 pub migration_table: Option<bool>,
321 pub translations: Option<LangReport>,
323}
324
325#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
327pub struct ModuleMigrations {
328 pub ran: Vec<RanMigration>,
330 pub waiting: Vec<String>,
332 pub tables: Vec<String>,
334 pub read_ms: i64,
336}
337
338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
340pub struct RanMigration {
341 pub name: String,
342 pub batch: u32,
343}
344
345impl ModuleMigrations {
346 pub fn last_batch(&self) -> Vec<&RanMigration> {
348 let Some(last) = self.ran.iter().map(|ran| ran.batch).max() else {
349 return Vec::new();
350 };
351 self.ran.iter().filter(|ran| ran.batch == last).collect()
352 }
353}
354
355impl PackageData {
356 pub fn migrations_for(&self, connection: &str) -> Option<&BTreeMap<String, ModuleMigrations>> {
359 (self.migration_connection == connection.trim()).then_some(&self.migrations)
360 }
361
362 pub fn migrations_of_every(&self, connection: &str, modules_on: &[&str]) -> bool {
366 self.migrations_for(connection).is_some_and(|migrations| {
367 modules_on.iter().all(|name| {
368 migrations.contains_key(*name) || self.migrations_of_all.contains(*name)
369 })
370 })
371 }
372
373 pub fn forget_migrations(&mut self, target: &Target) -> bool {
378 let before = (
379 self.migrations.len(),
380 self.migration_table,
381 self.migrations_of_all.len(),
382 );
383 match target {
384 Target::All => self.migrations.clear(),
385 Target::Module(name) => self
386 .migrations
387 .retain(|module, _| !module.eq_ignore_ascii_case(name)),
388 }
389 if self.migration_table == Some(false) {
390 self.migration_table = None;
391 }
392 self.migrations_of_all.clear();
393 before
394 != (
395 self.migrations.len(),
396 self.migration_table,
397 self.migrations_of_all.len(),
398 )
399 }
400
401 pub fn merge_migrations(
406 &mut self,
407 status: MigrationStatus,
408 target: &Target,
409 connection: &str,
410 modules_on: &[&str],
411 read_ms: i64,
412 ) {
413 let connection = connection.trim();
414 if self.migration_connection != connection {
415 self.migrations.clear();
416 self.migration_connection = connection.to_string();
417 self.migrations_of_all.clear();
418 }
419 if *target == Target::All {
420 self.migrations_of_all = modules_on.iter().map(|name| name.to_string()).collect();
421 let listed: BTreeSet<&str> = status
422 .modules
423 .iter()
424 .map(|module| module.name.as_str())
425 .collect();
426 self.migrations.retain(|name, _| {
427 listed.contains(name.as_str()) || !modules_on.contains(&name.as_str())
428 });
429 }
430 for module in status.modules {
431 let mut entry = ModuleMigrations {
432 read_ms,
433 ..ModuleMigrations::default()
434 };
435 for migration in module.migrations {
436 if migration.ran {
437 entry.ran.push(RanMigration {
438 name: migration.name,
439 batch: migration.batch.unwrap_or_default(),
440 });
441 } else {
442 entry.waiting.push(migration.name);
443 }
444 }
445 entry.ran.sort_by(|a, b| a.name.cmp(&b.name));
446 entry.waiting.sort();
447 self.migrations.insert(module.name, entry);
448 }
449 self.migration_table = Some(status.migration_table);
450 }
451
452 pub fn merge_translations(&mut self, report: LangReport) {
455 let kept = self.translations.get_or_insert_default();
456 for module in report.modules {
457 kept.modules.retain(|old| old.name != module.name);
458 kept.modules.push(module);
459 }
460 kept.modules.sort_by(|a, b| a.name.cmp(&b.name));
461 }
462
463 pub(crate) fn with_tables(&self, modules: &[Module]) -> PackageData {
465 let mut data = self.clone();
466 for (name, state) in &mut data.migrations {
467 state.tables.clear();
468 let Some(module) = modules.iter().find(|module| &module.name == name) else {
469 continue;
470 };
471 for ran in &state.ran {
472 let source = migration_file(&module.dir, &ran.name)
473 .and_then(|path| std::fs::read_to_string(path).ok());
474 for table in source
475 .as_deref()
476 .map(php::created_tables)
477 .unwrap_or_default()
478 {
479 if !state.tables.contains(&table) {
480 state.tables.push(table);
481 }
482 }
483 }
484 }
485 data
486 }
487}
488
489pub fn migration_file(module_dir: &Path, migration: &str) -> Option<PathBuf> {
492 let path = module_dir
493 .join("database")
494 .join("migrations")
495 .join(format!("{migration}.php"));
496 path.is_file().then_some(path)
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502 use crate::generate::catalog::generator_gives_data;
503
504 const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
505
506 fn version(raw: &str, alias: Option<&str>) -> Version {
507 Version {
508 raw: raw.into(),
509 alias: alias.map(String::from),
510 }
511 }
512
513 fn stdout(name: &str) -> Vec<String> {
515 let path = Path::new(FIXTURES)
516 .join("output")
517 .join(format!("{name}.json"));
518 let json: serde_json::Value =
519 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
520 json["stdout"]
521 .as_str()
522 .unwrap()
523 .lines()
524 .map(String::from)
525 .collect()
526 }
527
528 fn words(words: &[&str]) -> Vec<String> {
529 words.iter().map(|word| word.to_string()).collect()
530 }
531
532 #[test]
533 fn only_a_released_13_4_or_later_gives_data() {
534 let cases = [
535 (version("v13.4.0", None), true),
536 (version("13.4.0", None), true),
537 (version("13.3.9", None), false),
538 (version("14.0.0", None), true),
539 (version("13.4.0-RC1", None), false),
540 (version("dev-master", Some("13.x-dev")), false),
541 ];
542 for (version, gives) in cases {
543 assert_eq!(gives_data(&version), gives, "{}", version.raw);
544 }
545 assert!(!stores_surface(&version("v13.4.0", None)));
547 assert!(stores_surface(&version("v13.5.0", None)));
548
549 let v13_4 = version("13.4.0", None);
552 assert!(generator_gives_data(&v13_4, "module:make"));
553 assert!(generator_gives_data(&v13_4, "module:make-health-indicator"));
554 assert!(!generator_gives_data(&v13_4, "app:make-widget"));
555 assert!(!generator_gives_data(&v13_4, "module:make-widget"));
556 assert!(!generator_gives_data(
557 &version("13.3.0", None),
558 "module:make-model"
559 ));
560 }
561
562 #[test]
563 fn documents_are_read_from_the_last_line_of_standard_output() {
564 let dry_run: GeneratorReport =
566 document(&stdout("module-make-model-policy-exists-dry-run")).unwrap();
567 assert!(dry_run.dry_run);
568 assert_eq!(dry_run.files.len(), 3);
569 let policy = &dry_run.files[2];
570 assert!(policy.exists && policy.path.ends_with("/Policies/InvoicePolicy.php"));
571 assert_eq!((policy.action, policy.result), (FileAction::Keep, None));
572 assert_eq!(dry_run.errors.len(), 1);
573
574 let run: GeneratorReport =
575 document(&stdout("module-make-model-policy-exists-json")).unwrap();
576 assert_eq!(run.files[0].result, Some(FileResult::Created));
577 assert_eq!(run.files[2].result, Some(FileResult::Exists));
578
579 let status: MigrationStatus = document(&stdout("module-migrate-status-waiting")).unwrap();
580 assert!(status.migration_table);
581 let checkout = &status.modules[0].migrations;
582 assert_eq!((checkout[0].ran, checkout[0].batch), (true, Some(1)));
583 assert_eq!((checkout[1].ran, checkout[1].batch), (false, None));
584
585 let tests: TestReport = document(&stdout("module-test-all")).unwrap();
586 assert_eq!(
587 (tests.passed, tests.failed, tests.exit_code),
588 (Some(1), Some(1), Some(1))
589 );
590 assert_eq!(tests.modules[1].failed, Some(1));
591
592 let lang: LangReport = document(&stdout("module-lang-all-json")).unwrap();
593 assert!(!lang.modules[0].checked && lang.modules[0].locales.is_empty());
594 assert_eq!(
595 lang.modules[1].locales["fr"].missing_keys["messages.php"],
596 ["tracking_code", "order_placed"]
597 );
598
599 let lines = words(&["Warning: something", r#"{"modules":[]}"#, " "]);
601 assert_eq!(document::<LangReport>(&lines), Ok(LangReport::default()));
602 assert_eq!(
603 document::<LangReport>(&words(&["", " "])),
604 Err(DataError::Missing)
605 );
606 assert!(matches!(
607 document::<LangReport>(&words(&["Command \"module:lang\" is not defined."])),
608 Err(DataError::Malformed(_))
609 ));
610 }
611
612 #[test]
613 fn json_goes_before_a_double_dash() {
614 assert_eq!(
615 with_json(words(&["module:make-model", "Invoice", "Billing"])),
616 words(&["module:make-model", "Invoice", "Billing", "--json"])
617 );
618 assert_eq!(
619 with_dry_run(words(&["module:make", "--", "--force"])),
620 words(&["module:make", "--dry-run", "--json", "--", "--force"])
621 );
622 assert_eq!(
623 migrate_status_args(&Target::Module("-Odd".into()), " testing "),
624 words(&[
625 "module:migrate-status",
626 "--database=testing",
627 "--json",
628 "--",
629 "-Odd"
630 ])
631 );
632 assert_eq!(
634 with_json(words(&["module:make-model", "Invoice", "--json"])),
635 words(&["module:make-model", "Invoice", "--json"])
636 );
637 assert_eq!(
638 with_json(words(&["module:make-model", "Invoice", "--", "--json"])),
639 words(&["module:make-model", "Invoice", "--json", "--", "--json"])
640 );
641 }
642
643 #[test]
644 fn a_migration_command_changes_the_state_of_its_target() {
645 let changed = |line: &[&str]| migrations_changed_by(&words(line));
646 let checkout = Some(Target::Module("Checkout".into()));
647 assert_eq!(
648 changed(&["module:migrate", "Checkout", "--database=testing"]),
649 checkout
650 );
651 assert_eq!(
652 changed(&["module:migrate-rollback", "--", "Checkout"]),
653 checkout
654 );
655 assert_eq!(
656 changed(&["module:migrate-refresh", "--all"]),
657 Some(Target::All)
658 );
659 assert_eq!(
660 changed(&["module:migrate-fresh", "--force"]),
661 Some(Target::All)
662 );
663 assert_eq!(
664 changed(&["module:migrate-reset", "--force"]),
665 Some(Target::All)
666 );
667 assert_eq!(changed(&["module:migrate", "Checkout", "--pretend"]), None);
668 assert_eq!(changed(&["module:migrate-status", "Checkout"]), None);
669 assert_eq!(changed(&["module:seed", "Checkout"]), None);
670 }
671
672 #[test]
673 fn a_read_replaces_the_modules_it_holds() {
674 let mut data = PackageData::default();
675 let all: MigrationStatus = document(&stdout("module-migrate-status-all")).unwrap();
676 data.merge_migrations(
677 all,
678 &Target::All,
679 "",
680 &["Billing", "Checkout", "Loyalty", "Shipping"],
681 1,
682 );
683 assert!(data.migrations_of_every("", &["Checkout", "Shipping"]));
686 assert!(!data.migrations_of_every("", &["Checkout", "Catalog"]));
687 let checkout = &data.migrations["Checkout"];
688 assert_eq!(
689 checkout.waiting,
690 ["2026_11_23_120000_create_order_items_table"]
691 );
692 assert_eq!(
693 checkout.last_batch()[0].name,
694 "2026_11_23_110149_create_orders_table"
695 );
696 assert_eq!(data.migrations["Billing"].waiting.len(), 2);
697
698 let two: MigrationStatus = document(&stdout("module-migrate-status-no-table")).unwrap();
700 data.merge_migrations(two, &Target::Module("Checkout".into()), "", &[], 2);
701 assert_eq!(data.migration_table, Some(false));
702 assert_eq!(data.migrations["Checkout"].ran, []);
703 assert_eq!(data.migrations["Checkout"].read_ms, 2);
704 assert_eq!(data.migrations["Loyalty"].read_ms, 1);
705
706 let none = MigrationStatus {
708 modules: Vec::new(),
709 migration_table: true,
710 };
711 data.merge_migrations(none.clone(), &Target::All, "", &["Checkout", "Loyalty"], 3);
712 assert_eq!(data.migrations.keys().collect::<Vec<_>>(), ["Billing"]);
713
714 data.migration_table = Some(false);
716 assert!(data.forget_migrations(&Target::Module("billing".into())));
717 assert!(!data.migrations_of_every("", &["Catalog"]));
718 assert!(data.migrations.is_empty() && data.migration_table.is_none());
719 assert!(!data.forget_migrations(&Target::All));
720
721 assert!(data.migrations_for("testing").is_none());
723 data.merge_migrations(none, &Target::Module("Checkout".into()), "testing", &[], 4);
724 assert!(data.migrations_for("").is_none());
725 assert_eq!(data.migrations_for(" testing").map(BTreeMap::len), Some(0));
726
727 data.merge_translations(document(&stdout("module-lang-all-json")).unwrap());
729 let mut one: LangReport = document(&stdout("module-lang-all-json")).unwrap();
730 one.modules.retain(|module| module.name == "Checkout");
731 one.modules[0].locales.clear();
732 data.merge_translations(one);
733 let kept = &data.translations.as_ref().unwrap().modules;
734 let names: Vec<&str> = kept.iter().map(|module| module.name.as_str()).collect();
735 assert_eq!(names, ["Billing", "Checkout", "Loyalty"]);
736 assert!(kept[1].locales.is_empty());
737 }
738
739 #[test]
740 fn a_migration_file_is_found_only_when_it_exists() {
741 let billing = Path::new(FIXTURES).join("shop-api/Modules/Billing");
742 let name = "2026_01_10_000000_create_invoices_table";
743 assert_eq!(
744 migration_file(&billing, name),
745 Some(
746 billing
747 .join("database/migrations")
748 .join(format!("{name}.php"))
749 )
750 );
751 assert_eq!(
752 migration_file(&billing, "2026_01_11_000000_create_refunds_table"),
753 None
754 );
755 }
756}