Skip to main content

mortise_core/
package.rs

1//! What the package gives from 13.4.0 on: JSON documents on standard output.
2//!
3//! A `--json` command prints one document on one line, last. Its other messages go
4//! to standard error. The types here read those documents. Unknown keys are ignored,
5//! so a later package can add keys.
6
7use 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
18/// True when the app's package gives P2 to P8: a released 13.4.0 or later.
19///
20/// The version must be `MAJOR.MINOR.PATCH` in ASCII digits. A dev build, a branch
21/// alias or a pre-release may lack a feature, so it gets false.
22pub fn gives_data(version: &Version) -> bool {
23    released_since(version, (13, 4))
24}
25
26/// True when the app's package stores a public surface (P6): `module:surface`, in a
27/// released 13.5.0 or later. The version is read as for [`gives_data`].
28pub fn stores_surface(version: &Version) -> bool {
29    released_since(version, (13, 5))
30}
31
32/// True when the version is a release `MAJOR.MINOR.PATCH` of `since` or later.
33fn 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/// Why a run gave no document.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum DataError {
51    /// Standard output held no line, or only empty lines.
52    Missing,
53    /// The last line is not the document: serde's message.
54    Malformed(String),
55    /// The last line was longer than a line may be and only its start was kept, or
56    /// the output passed its limit. A cut document is never read in part.
57    Cut,
58}
59
60/// The last non-empty line of standard output, read as `T`.
61///
62/// The exit code does not matter: a dry run with a kept file exits 1 with a whole document.
63pub 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
73/// [`document`], unless the last non-empty line of `stdout` was cut (`cut`): then
74/// [`DataError::Cut`], since the start of a line may parse as a whole document.
75pub 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
82/// True when the artisan words hold `option` before a `--`. A word after `--` is a
83/// name, such as a module named `--json`.
84pub fn has_option(words: &[String], option: &str) -> bool {
85    words
86        .iter()
87        .take_while(|word| *word != "--")
88        .any(|word| word == option)
89}
90
91/// The artisan words with `--json`, before a `--` when the words hold one. Words
92/// that hold it already stay as they are.
93pub fn with_json(words: Vec<String>) -> Vec<String> {
94    with_flags(words, &["--json"])
95}
96
97/// The artisan words with `--dry-run --json`, before a `--` when the words hold one.
98/// A flag the words hold already is not added again.
99pub fn with_dry_run(words: Vec<String>) -> Vec<String> {
100    with_flags(words, &["--dry-run", "--json"])
101}
102
103/// The words of a read of the migration state of `target` on `database`:
104/// `module:migrate-status Checkout --database=testing --json`, or `--all`. An empty
105/// `database` is the default connection and is left out. A module name that starts
106/// with `-` goes after `--`, as [`crate::plan`] puts it.
107pub 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
125/// The migration state that a run of the artisan words `args` may have changed, when
126/// it ends, whatever its exit code (design D7): a migrate, roll back, reset, refresh
127/// or fresh that is not a dry run (`--pretend`). Every module for `--all`, for a fresh
128/// or for words that name no module; else the module the words name, the second word
129/// or the word after `--`. `None` for other words.
130pub 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/// The document of a generator and of `module:make`, for a run and for a dry run.
173#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
174pub struct GeneratorReport {
175    /// The artisan command: `module:make-model`.
176    pub command: String,
177    pub dry_run: bool,
178    /// The files in write order, with those of the generators it called.
179    pub files: Vec<ReportedFile>,
180    /// The error messages, as the package prints them.
181    pub errors: Vec<String>,
182}
183
184impl GeneratorReport {
185    /// True when the errors say that `composer dump-autoload` failed (`module:make`).
186    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/// One file of a [`GeneratorReport`].
194#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
195pub struct ReportedFile {
196    /// Absolute, with `/` between the parts.
197    pub path: String,
198    /// The file was there before the run.
199    pub exists: bool,
200    pub action: FileAction,
201    /// What the run did. A dry run has none.
202    #[serde(default)]
203    pub result: Option<FileResult>,
204}
205
206/// What a generator means to do with a file.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
208#[serde(rename_all = "lowercase")]
209pub enum FileAction {
210    Create,
211    Replace,
212    /// The file exists and is not written over.
213    Keep,
214    /// The folder that `module:make --force` deletes first.
215    Delete,
216}
217
218/// What a generator did with a file.
219#[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/// The document of `module:migrate-status --json`.
230#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
231pub struct MigrationStatus {
232    pub modules: Vec<ModuleStatus>,
233    /// False when the database has no migrations table. Every migration is then not ran.
234    pub migration_table: bool,
235}
236
237/// The migrations of one module in a [`MigrationStatus`].
238#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
239pub struct ModuleStatus {
240    pub name: String,
241    /// Sorted by name.
242    pub migrations: Vec<MigrationRow>,
243}
244
245/// One migration of a [`ModuleStatus`].
246#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
247pub struct MigrationRow {
248    /// The file name without `.php`.
249    pub name: String,
250    pub ran: bool,
251    /// The batch of a ran migration.
252    #[serde(default)]
253    pub batch: Option<u32>,
254}
255
256/// The document of `module:test --json`.
257#[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/// The tests of one module in a [`TestReport`]. The counts are `None` when the
267/// module has no tests folder or the runner wrote no report.
268#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
269pub struct ModuleTests {
270    pub name: String,
271    /// False for a module without a tests folder.
272    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/// The document of `module:lang --json`, and the report Mortise keeps of it.
280#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
281pub struct LangReport {
282    /// By name once kept in [`PackageData`].
283    pub modules: Vec<LangModule>,
284}
285
286/// The translations of one module in a [`LangReport`].
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288pub struct LangModule {
289    pub name: String,
290    /// False when the module has fewer than two locales.
291    pub checked: bool,
292    /// By locale.
293    pub locales: BTreeMap<String, Locale>,
294}
295
296/// What one locale of a module lacks.
297#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
298pub struct Locale {
299    /// Files of the other locales that this one has not.
300    pub missing_files: Vec<String>,
301    /// The missing keys, by file.
302    pub missing_keys: BTreeMap<String, Vec<String>>,
303}
304
305/// What the package said about an app, from the reads the user started.
306///
307/// It lives in memory only: the database changes outside Mortise.
308#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
309pub struct PackageData {
310    /// The migration state, by module name, of [`Self::migration_connection`].
311    pub migrations: BTreeMap<String, ModuleMigrations>,
312    /// The connection the migration state was read for (`--database`). Empty for
313    /// the default connection.
314    pub migration_connection: String,
315    /// The modules that were on at the last read of every module (`--all`), while
316    /// that read holds: nothing was forgotten after it. Such a module with no entry
317    /// was not in its answer. Empty without such a read.
318    pub migrations_of_all: BTreeSet<String>,
319    /// Whether the database has a migrations table, from the last state read.
320    pub migration_table: Option<bool>,
321    /// The last translation report, by module.
322    pub translations: Option<LangReport>,
323}
324
325/// The migration state of one module.
326#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
327pub struct ModuleMigrations {
328    /// By name.
329    pub ran: Vec<RanMigration>,
330    /// The migrations that did not run, by name.
331    pub waiting: Vec<String>,
332    /// The tables the ran migrations create, read from their files by the read of the app.
333    pub tables: Vec<String>,
334    /// When the state was read, in milliseconds since 1970.
335    pub read_ms: i64,
336}
337
338/// A migration that ran.
339#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
340pub struct RanMigration {
341    pub name: String,
342    pub batch: u32,
343}
344
345impl ModuleMigrations {
346    /// The ran migrations whose batch is the highest among them. A roll back takes these.
347    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    /// The migration state when it was read for `connection` (empty for the default).
357    /// A state of another connection says nothing about this one.
358    pub fn migrations_for(&self, connection: &str) -> Option<&BTreeMap<String, ModuleMigrations>> {
359        (self.migration_connection == connection.trim()).then_some(&self.migrations)
360    }
361
362    /// True when the state on `connection` says something of every module in `modules_on`:
363    /// each has an entry, or was on at a read of every module that holds since (design D7).
364    /// A count over the modules that are on is then whole.
365    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    /// Forgets the migration state of `target`, whatever connection it was read for:
374    /// every module for [`Target::All`], else the module's entry, by name in any case.
375    /// A "no migrations table" answer goes too: the run may have made the table.
376    /// A read of every module no longer covers them all. True when something was forgotten.
377    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    /// Takes in a state read of `target` on `connection`, read at `read_ms`. A read of
402    /// another connection than the state's replaces the whole state. A module of the
403    /// document replaces its entry. Under `--all`, a module in `modules_on` that the
404    /// document does not hold is removed, because the package lists every module that is on.
405    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    /// Takes in a translation report. A module of the report replaces its entry, so a
453    /// check of one module keeps the others.
454    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    /// This data with the tables of each module's ran migrations read from their files.
464    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
489/// The file of a migration in the default folder of the package,
490/// `database/migrations`, when it exists.
491pub 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    /// The lines of the standard output of a recording in `fixtures/output`.
514    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        // The surface comes one minor version later.
546        assert!(!stores_surface(&version("v13.4.0", None)));
547        assert!(stores_surface(&version("v13.5.0", None)));
548
549        // Only a generator the package ships gets the dry run and the answer: an
550        // app's own may declare `--dry-run` and write anyway.
551        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        // A kept file exits 1 with a whole document.
565        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        // A line of a broken setup before the document does not matter.
600        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        // Once only, and a module named `--json` after `--` is not the option.
633        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        // The read of every module covers a module that was on and is not in its answer,
684        // not one turned on after it.
685        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        // A read of two modules keeps the third, and says there is no table.
699        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        // Under --all a module that is on and not listed is gone. One that is off stays.
707        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        // A run forgets its module whatever the connection, and a "no table" answer.
715        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        // The state is of one connection: a read of another replaces it all.
722        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        // A report of one module keeps the others.
728        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}