Skip to main content

mortise_core/palette/
recent.rs

1//! The actions and generators that ran last in an app, read from its history (S12.2 a).
2
3use crate::actions::plan::Action;
4use crate::app::AppSnapshot;
5use crate::generate::catalog::Catalog;
6use crate::modules::module::ModuleState;
7use crate::modules::target::Target;
8use crate::run::history::Entry;
9
10/// What a run of the history was.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Ran {
13    /// An action on a module, or on all modules with `None`.
14    Action {
15        action: Action,
16        module: Option<String>,
17    },
18    /// A generator in a module, or `module:make` with `None`.
19    Generator {
20        name: String,
21        module: Option<String>,
22    },
23}
24
25/// A run that was an action or a generator, and when it started.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct RecentRun {
28    pub ran: Ran,
29    /// In ms since 1970.
30    pub started_ms: i64,
31}
32
33/// The distinct actions and generators of `runs`, which hold the latest first: at most
34/// `limit`, the latest first. A run is the action of [`Action::from_artisan`] or a generator of
35/// `catalog`, by its first word, with the module of its words. A run that is neither,
36/// whose module is not in `app`, or whose action the Actions tab does not list for the
37/// module as it is now (Turn off of a module that is off), is left out. Of two runs of the same action or
38/// generator on the same module, the latest stays.
39pub fn recent_runs(
40    runs: &[Entry],
41    catalog: &Catalog,
42    app: &AppSnapshot,
43    limit: usize,
44) -> Vec<RecentRun> {
45    let mut recent: Vec<RecentRun> = Vec::new();
46    for run in runs {
47        if recent.len() == limit {
48            break;
49        }
50        let Some(ran) = ran(&run.args, catalog, app) else {
51            continue;
52        };
53        if recent.iter().all(|kept| kept.ran != ran) {
54            recent.push(RecentRun {
55                ran,
56                started_ms: run.started_ms,
57            });
58        }
59    }
60    recent
61}
62
63/// What the words of a run were. The words that are not options are the arguments:
64/// the words after `--` when there is one, as [`crate::actions::plan::plan`] and
65/// [`crate::generate::catalog::Generator::words`] write a name that starts with `-`.
66fn ran(args: &[String], catalog: &Catalog, app: &AppSnapshot) -> Option<Ran> {
67    let (first, rest) = args.split_first()?;
68    let options: Vec<&str> = rest
69        .iter()
70        .map(String::as_str)
71        .take_while(|word| *word != "--")
72        .collect();
73    let arguments: Vec<&str> = if options.len() < rest.len() {
74        rest[options.len() + 1..]
75            .iter()
76            .map(String::as_str)
77            .collect()
78    } else {
79        options
80            .iter()
81            .copied()
82            .filter(|word| !word.starts_with('-'))
83            .collect()
84    };
85    // The name the snapshot has for a module of the words.
86    let module = |word: Option<&&str>| Some(app.module(word?)?.name.clone());
87
88    if let Some(action) = Action::from_artisan(first) {
89        let module = if options.contains(&"--all") {
90            None
91        } else {
92            Some(module(arguments.first())?)
93        };
94        // The actions the Actions tab lists for the target: the everyday ones for the
95        // state of the module, and the destructive ones of the target.
96        let everyday = match &module {
97            Some(name) => {
98                let on = app.module(name)?.state != ModuleState::Off;
99                Action::for_module(on).contains(&action)
100            }
101            None => Action::for_all().contains(&action),
102        };
103        let target = module.clone().map_or(Target::All, Target::Module);
104        if !everyday && !Action::destructive(&target).contains(&action) {
105            return None;
106        }
107        return Some(Ran::Action { action, module });
108    }
109    let generator = catalog.get(first)?;
110    let module = match generator
111        .arguments
112        .iter()
113        .position(|argument| argument.name == "module")
114    {
115        Some(at) => Some(module(arguments.get(at))?),
116        None => None,
117    };
118    Some(Ran::Generator {
119        name: generator.name.clone(),
120        module,
121    })
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::run::history::Ended;
128    use std::path::Path;
129
130    fn run(words: &str, started_ms: i64) -> Entry {
131        let args: Vec<String> = words.split_whitespace().map(str::to_owned).collect();
132        Entry {
133            id: started_ms as u64,
134            label: words.to_owned(),
135            args,
136            started_ms,
137            ended: Ended::Done { ms: 5 },
138            cut: false,
139        }
140    }
141
142    #[test]
143    fn the_latest_distinct_actions_and_generators_of_modules_in_the_app() {
144        let root = Path::new(concat!(
145            env!("CARGO_MANIFEST_DIR"),
146            "/../../fixtures/shop-api"
147        ));
148        let app = crate::read_app(root).unwrap();
149        let runs = [
150            run("module:migrate Checkout --pretend", 9),
151            // Not an action or a generator, and a module the app does not have.
152            run("about", 8),
153            run("module:migrate Nowhere", 7),
154            // Checkout is on: the Actions tab offers Turn off, not Turn on.
155            run("module:enable Checkout", 7),
156            // A generator without its module runs in the module the package uses.
157            run("module:make-model Invoice", 6),
158            // The same action on the same module: the latest stays.
159            run("module:migrate Checkout", 5),
160            run("module:make-model --migration -- -Invoice Billing", 4),
161            run("module:migrate --all", 3),
162            // Past the limit.
163            run("module:make Loyalty --api", 2),
164        ];
165        let recent = recent_runs(&runs, Catalog::v13_3(), &app, 3);
166        assert_eq!(
167            recent,
168            [
169                RecentRun {
170                    ran: Ran::Action {
171                        action: Action::Migrate,
172                        module: Some("Checkout".into()),
173                    },
174                    started_ms: 9,
175                },
176                RecentRun {
177                    ran: Ran::Generator {
178                        name: "module:make-model".into(),
179                        module: Some("Billing".into()),
180                    },
181                    started_ms: 4,
182                },
183                RecentRun {
184                    ran: Ran::Action {
185                        action: Action::Migrate,
186                        module: None,
187                    },
188                    started_ms: 3,
189                },
190            ]
191        );
192        // `module:make` has no module.
193        assert_eq!(
194            recent_runs(&runs[runs.len() - 1..], Catalog::v13_3(), &app, 3)[0].ran,
195            Ran::Generator {
196                name: crate::MODULE_MAKE.into(),
197                module: None,
198            }
199        );
200    }
201}