1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use super::{
    Autocomplete, AutocompleteSuggestion, Command, CommandMatches, ContextAwareParse, Runnable,
};
use crate::app::AppMeta;
use crate::utils::CaseInsensitiveStr;
use async_trait::async_trait;
use std::borrow::Cow;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem;

#[derive(Clone, Debug)]
pub enum CommandAlias {
    Literal {
        term: Cow<'static, str>,
        summary: Cow<'static, str>,
        command: Box<Command>,
    },
    StrictWildcard {
        command: Box<Command>,
    },
}

impl CommandAlias {
    pub fn literal(
        term: impl Into<Cow<'static, str>>,
        summary: impl Into<Cow<'static, str>>,
        command: Command,
    ) -> Self {
        Self::Literal {
            term: term.into(),
            summary: summary.into(),
            command: Box::new(command),
        }
    }

    pub fn strict_wildcard(command: Command) -> Self {
        Self::StrictWildcard {
            command: Box::new(command),
        }
    }

    pub fn get_command(&self) -> &Command {
        match self {
            Self::Literal { command, .. } => command,
            Self::StrictWildcard { command, .. } => command,
        }
    }
}

impl Hash for CommandAlias {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Self::Literal { term, .. } => {
                if term.chars().any(char::is_uppercase) {
                    term.to_lowercase().hash(state);
                } else {
                    term.hash(state);
                }
            }
            Self::StrictWildcard { .. } => {}
        }
    }
}

impl PartialEq for CommandAlias {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::Literal { term, .. },
                Self::Literal {
                    term: other_term, ..
                },
            ) => term.eq_ci(other_term),
            (Self::StrictWildcard { .. }, Self::StrictWildcard { .. }) => true,
            _ => false,
        }
    }
}

impl Eq for CommandAlias {}

#[async_trait(?Send)]
impl Runnable for CommandAlias {
    async fn run(self, input: &str, app_meta: &mut AppMeta) -> Result<String, String> {
        match self {
            Self::Literal { command, .. } => {
                let mut temp_aliases = mem::take(&mut app_meta.command_aliases);

                let result = command.run(input, app_meta).await;

                if app_meta.command_aliases.is_empty() {
                    app_meta.command_aliases = temp_aliases;
                } else {
                    temp_aliases.drain().for_each(|command| {
                        if !app_meta.command_aliases.contains(&command) {
                            app_meta.command_aliases.insert(command);
                        }
                    });
                }

                result
            }
            Self::StrictWildcard { .. } => {
                app_meta.command_aliases.remove(&self);
                if let Self::StrictWildcard { command } = self {
                    command.run(input, app_meta).await
                } else {
                    unreachable!();
                }
            }
        }
    }
}

#[async_trait(?Send)]
impl ContextAwareParse for CommandAlias {
    async fn parse_input(input: &str, app_meta: &AppMeta) -> CommandMatches<Self> {
        app_meta
            .command_aliases
            .iter()
            .find(|c| matches!(c, Self::StrictWildcard { .. }))
            .or_else(|| {
                app_meta
                    .command_aliases
                    .iter()
                    .find(|command| match command {
                        Self::Literal { term, .. } => term.eq_ci(input),
                        Self::StrictWildcard { .. } => false,
                    })
            })
            .cloned()
            .map(CommandMatches::from)
            .unwrap_or_default()
    }
}

#[async_trait(?Send)]
impl Autocomplete for CommandAlias {
    async fn autocomplete(input: &str, app_meta: &AppMeta) -> Vec<AutocompleteSuggestion> {
        app_meta
            .command_aliases
            .iter()
            .filter_map(|command| match command {
                Self::Literal { term, summary, .. } => {
                    if term.starts_with_ci(input) {
                        Some(AutocompleteSuggestion::new(
                            term.to_string(),
                            summary.to_string(),
                        ))
                    } else {
                        None
                    }
                }
                Self::StrictWildcard { .. } => None,
            })
            .collect()
    }
}

impl fmt::Display for CommandAlias {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match self {
            Self::Literal { term, .. } => {
                write!(f, "{}", term)?;
            }
            Self::StrictWildcard { .. } => {}
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::{assert_autocomplete, AppCommand, Command, Event};
    use crate::storage::NullDataStore;
    use std::collections::HashSet;
    use tokio_test::block_on;

    #[test]
    fn literal_constructor_test() {
        let alias = CommandAlias::literal(
            "term".to_string(),
            "summary".to_string(),
            AppCommand::About.into(),
        );

        if let CommandAlias::Literal {
            term,
            summary,
            command,
        } = alias
        {
            assert_eq!("term", term);
            assert_eq!("summary", summary);
            assert_eq!(Box::new(Command::from(AppCommand::About)), command);
        } else {
            panic!("{:?}", alias);
        }
    }

    #[test]
    fn wildcard_constructor_test() {
        let alias = CommandAlias::strict_wildcard(AppCommand::About.into());

        if let CommandAlias::StrictWildcard { command } = alias {
            assert_eq!(Box::new(Command::from(AppCommand::About)), command);
        } else {
            panic!("{:?}", alias);
        }
    }

    #[test]
    fn eq_test() {
        assert_eq!(
            literal("foo", "foo", AppCommand::About.into()),
            literal("foo", "bar", AppCommand::Help.into()),
        );
        assert_ne!(
            literal("foo", "foo", AppCommand::About.into()),
            literal("bar", "foo", AppCommand::About.into()),
        );

        assert_eq!(
            strict_wildcard(AppCommand::About.into()),
            strict_wildcard(AppCommand::Help.into()),
        );
        assert_ne!(
            literal("", "", AppCommand::About.into()),
            strict_wildcard(AppCommand::About.into()),
        );
    }

    #[test]
    fn hash_test() {
        let mut set = HashSet::with_capacity(2);

        assert!(set.insert(literal("foo", "", AppCommand::About.into())));
        assert!(set.insert(literal("bar", "", AppCommand::About.into())));
        assert!(set.insert(strict_wildcard(AppCommand::About.into())));
        assert!(!set.insert(literal("foo", "", AppCommand::Help.into())));
        assert!(!set.insert(literal("FOO", "", AppCommand::Help.into())));
        assert!(!set.insert(strict_wildcard(AppCommand::Help.into())));
    }

    #[test]
    fn runnable_test_literal() {
        let about_alias = literal("about alias", "about summary", AppCommand::About.into());

        let mut app_meta = app_meta();
        app_meta.command_aliases.insert(about_alias.clone());
        app_meta.command_aliases.insert(literal(
            "help alias",
            "help summary",
            AppCommand::Help.into(),
        ));

        assert_autocomplete(
            &[("about alias", "about summary")][..],
            block_on(CommandAlias::autocomplete("a", &app_meta)),
        );

        assert_eq!(
            block_on(CommandAlias::autocomplete("a", &app_meta)),
            block_on(CommandAlias::autocomplete("A", &app_meta)),
        );

        assert_eq!(
            CommandMatches::default(),
            block_on(CommandAlias::parse_input("blah", &app_meta)),
        );

        assert_eq!(
            CommandMatches::new_canonical(about_alias.clone()),
            block_on(CommandAlias::parse_input("about alias", &app_meta)),
        );

        {
            let (about_result, about_alias_result) = (
                block_on(AppCommand::About.run("about alias", &mut app_meta)),
                block_on(about_alias.run("about alias", &mut app_meta)),
            );

            assert!(about_result.is_ok(), "{:?}", about_result);
            assert_eq!(about_result, about_alias_result);

            assert!(!app_meta.command_aliases.is_empty());
        }
    }

    #[test]
    fn runnable_test_strict_wildcard() {
        let about_alias = strict_wildcard(AppCommand::About.into());

        let mut app_meta = app_meta();
        app_meta.command_aliases.insert(about_alias.clone());
        app_meta.command_aliases.insert(literal(
            "literal alias",
            "literally a summary",
            AppCommand::Help.into(),
        ));

        // Should be caught by the wildcard, not the literal alias
        assert_eq!(
            CommandMatches::new_canonical(about_alias.clone()),
            block_on(CommandAlias::parse_input("literal alias", &app_meta)),
        );

        {
            assert_eq!(2, app_meta.command_aliases.len());

            let (about_result, about_alias_result) = (
                block_on(AppCommand::About.run("about", &mut app_meta)),
                block_on(about_alias.run("about", &mut app_meta)),
            );

            assert!(about_result.is_ok(), "{:?}", about_result);
            assert_eq!(about_result, about_alias_result);
            assert!(app_meta.command_aliases.is_empty());
        }
    }

    fn event_dispatcher(_event: Event) {}

    fn app_meta() -> AppMeta {
        AppMeta::new(NullDataStore, &event_dispatcher)
    }

    fn literal(
        term: impl Into<Cow<'static, str>>,
        summary: impl Into<Cow<'static, str>>,
        command: Command,
    ) -> CommandAlias {
        CommandAlias::Literal {
            term: term.into(),
            summary: summary.into(),
            command: Box::new(command),
        }
    }

    fn strict_wildcard(command: Command) -> CommandAlias {
        CommandAlias::StrictWildcard {
            command: Box::new(command),
        }
    }
}