dynamic-cli 0.10.0

A framework for building configurable CLI and REPL applications from YAML/JSON configuration files
Documentation
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! REPL directives
//!
//! A REPL line starting with `:` is a framework directive; any other line is
//! an application command. The set of directives is closed for a given
//! version of the crate and described by [`ReplDirective`]. An application
//! may rename a directive, change its aliases or its description through the
//! optional `directives:` section of its configuration, but it can neither
//! add nor disable one.
//!
//! # Default directives
//!
//! | `implementation` | Name   | Aliases  | Arguments   |
//! |------------------|--------|----------|-------------|
//! | `repl_help`      | `help` | `h`, `?` | `[command]` |
//! | `repl_load`      | `load` |          | `<path>`    |
//! | `repl_quit`      | `quit` | `q`      |             |
//! | `repl_exit`      | `exit` |          |             |
//!
//! Names and aliases are written without the leading `:`; the REPL adds it.
//!
//! # Overriding a directive
//!
//! ```yaml
//! directives:
//!   - implementation: repl_help
//!     name: aide
//!     aliases: [a]
//!     description: "Afficher l'aide"
//! ```
//!
//! An entry replaces the name, the aliases and the description of the
//! directive selected by `implementation`; `aliases` defaults to an empty
//! list. Directives without an entry keep their defaults.
//! [`effective_directives`] computes the resulting table.
//!
//! # Validation
//!
//! The configuration validator rejects:
//!
//! - an unknown `implementation` (already at load time);
//! - two entries for the same `implementation`;
//! - an empty name or alias, one containing whitespace, or one starting
//!   with `:`;
//! - a name or alias used twice in the effective table, defaults included:
//!   an override cannot take `q` while `:quit` keeps it as its alias.
//!
//! Directive names are never compared with command names, since a
//! directive is always typed with its `:`. Command names and aliases, for
//! their part, may not start with `:`.

// Design: DA-030 (#92). The directive set is an enum rather than a trait:
// commands are an open set supplied by the application, directives a closed
// set that needs REPL internals (editor, history, loop control). A new
// directive is a new variant, and the exhaustive matches below make the
// compiler point at every place that must handle it.

use serde::{Deserialize, Serialize};

/// Prefix that marks a REPL line as a directive
pub(crate) const DIRECTIVE_PREFIX: char = ':';

/// Framework directive available in the REPL
///
/// Deserialized from the `implementation` field of a `directives:` entry
/// (`repl_help`, `repl_load`, `repl_quit`, `repl_exit`). An unknown value
/// fails at load time, and the error lists the accepted values.
///
/// The enum is `#[non_exhaustive]`: later versions may add directives.
///
/// # Example
///
/// ```
/// use dynamic_cli::config::ReplDirective;
///
/// assert_eq!(ReplDirective::Help.default_name(), "help");
/// assert_eq!(ReplDirective::Help.default_aliases(), &["h", "?"]);
/// assert_eq!(ReplDirective::Help.usage(), "[command]");
/// assert_eq!(ReplDirective::Help.as_str(), "repl_help");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[non_exhaustive]
pub enum ReplDirective {
    /// Show the application help, or the help of one command
    #[serde(rename = "repl_help")]
    Help,

    /// Run every line of a script file in the current session
    #[serde(rename = "repl_load")]
    Load,

    /// Save the session history, then leave the REPL
    #[serde(rename = "repl_quit")]
    Quit,

    /// Leave the REPL without saving the session history
    #[serde(rename = "repl_exit")]
    Exit,
}

impl ReplDirective {
    /// Every directive, in the order used by [`effective_directives`] and
    /// by help listings
    pub const ALL: &'static [ReplDirective] = &[
        ReplDirective::Help,
        ReplDirective::Load,
        ReplDirective::Quit,
        ReplDirective::Exit,
    ];

    /// Identifier used in the `implementation` field of the configuration
    pub fn as_str(self) -> &'static str {
        match self {
            ReplDirective::Help => "repl_help",
            ReplDirective::Load => "repl_load",
            ReplDirective::Quit => "repl_quit",
            ReplDirective::Exit => "repl_exit",
        }
    }

    /// Name used when the configuration does not override the directive
    pub fn default_name(self) -> &'static str {
        match self {
            ReplDirective::Help => "help",
            ReplDirective::Load => "load",
            ReplDirective::Quit => "quit",
            ReplDirective::Exit => "exit",
        }
    }

    /// Aliases used when the configuration does not override the directive
    pub fn default_aliases(self) -> &'static [&'static str] {
        match self {
            ReplDirective::Help => &["h", "?"],
            ReplDirective::Load => &[],
            ReplDirective::Quit => &["q"],
            ReplDirective::Exit => &[],
        }
    }

    /// Description used when the configuration does not override the
    /// directive
    pub fn default_description(self) -> &'static str {
        match self {
            ReplDirective::Help => "Show the application help, or the help of a command",
            ReplDirective::Load => "Run every line of a script file",
            ReplDirective::Quit => "Save the session history and leave",
            ReplDirective::Exit => "Leave without saving the session history",
        }
    }

    /// Arguments accepted after the directive name, as shown in help
    ///
    /// Returns only the argument part, since the name itself may be
    /// overridden; the result is empty for a directive without arguments.
    /// Arguments are fixed by the action and cannot be configured.
    pub fn usage(self) -> &'static str {
        match self {
            ReplDirective::Help => "[command]",
            ReplDirective::Load => "<path>",
            ReplDirective::Quit => "",
            ReplDirective::Exit => "",
        }
    }
}

/// Name, aliases and description of a REPL directive
///
/// Used both for the entries of the `directives:` configuration section and
/// for the complete table returned by [`effective_directives`].
///
/// # Example YAML
///
/// ```yaml
/// implementation: repl_quit
/// name: quitter
/// aliases: [q]
/// description: "Enregistrer l'historique et quitter"
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct DirectiveDefinition {
    /// Directive being defined or overridden
    pub implementation: ReplDirective,

    /// Name typed after `:` to invoke the directive
    pub name: String,

    /// Alternative names, also typed after `:`
    #[serde(default)]
    pub aliases: Vec<String>,

    /// Human-readable description for help text
    pub description: String,
}

impl DirectiveDefinition {
    /// Definition of `directive` with its default name, aliases and
    /// description
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_cli::config::{DirectiveDefinition, ReplDirective};
    ///
    /// let quit = DirectiveDefinition::default_for(ReplDirective::Quit);
    /// assert_eq!(quit.name, "quit");
    /// assert_eq!(quit.aliases, vec!["q".to_string()]);
    /// ```
    pub fn default_for(directive: ReplDirective) -> Self {
        Self {
            implementation: directive,
            name: directive.default_name().to_string(),
            aliases: directive
                .default_aliases()
                .iter()
                .map(|alias| alias.to_string())
                .collect(),
            description: directive.default_description().to_string(),
        }
    }

    /// Usage line under the effective name, e.g. `:help [command]` or
    /// `:quit`
    ///
    /// Shared by the REPL error hints and the help formatters, so both show
    /// the same line.
    pub(crate) fn usage_line(&self) -> String {
        match self.implementation.usage() {
            "" => format!("{}{}", DIRECTIVE_PREFIX, self.name),
            args => format!("{}{} {}", DIRECTIVE_PREFIX, self.name, args),
        }
    }
}

/// Complete directive table after applying the configuration overrides
///
/// Returns one definition per directive, in [`ReplDirective::ALL`] order: the
/// override whose `implementation` matches when there is one, the default
/// definition otherwise.
///
/// The configuration validator rejects two overrides of the same directive.
/// On an unvalidated list, the last override of a directive wins.
///
/// # Example
///
/// ```
/// use dynamic_cli::config::{effective_directives, DirectiveDefinition, ReplDirective};
///
/// let overrides = vec![DirectiveDefinition {
///     implementation: ReplDirective::Help,
///     name: "aide".to_string(),
///     aliases: vec![],
///     description: "Afficher l'aide".to_string(),
/// }];
///
/// let table = effective_directives(&overrides);
/// assert_eq!(table.len(), ReplDirective::ALL.len());
/// assert_eq!(table[0].name, "aide");
/// assert_eq!(table[2].name, "quit");
/// ```
pub fn effective_directives(overrides: &[DirectiveDefinition]) -> Vec<DirectiveDefinition> {
    ReplDirective::ALL
        .iter()
        .map(|&directive| {
            overrides
                .iter()
                .rev()
                .find(|entry| entry.implementation == directive)
                .cloned()
                .unwrap_or_else(|| DirectiveDefinition::default_for(directive))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    fn entry(directive: ReplDirective, name: &str, aliases: &[&str]) -> DirectiveDefinition {
        DirectiveDefinition {
            implementation: directive,
            name: name.to_string(),
            aliases: aliases.iter().map(|a| a.to_string()).collect(),
            description: format!("custom {}", name),
        }
    }

    // ------------------------------------------------------------------
    // Defaults
    // ------------------------------------------------------------------

    #[test]
    fn test_all_lists_each_variant_once() {
        let unique: HashSet<_> = ReplDirective::ALL.iter().collect();
        assert_eq!(unique.len(), ReplDirective::ALL.len());
        assert_eq!(ReplDirective::ALL.len(), 4);
    }

    #[test]
    fn test_every_directive_has_default_name_and_description() {
        for &directive in ReplDirective::ALL {
            assert!(!directive.default_name().is_empty(), "{:?}", directive);
            assert!(
                !directive.default_description().is_empty(),
                "{:?}",
                directive
            );
            assert!(directive.as_str().starts_with("repl_"), "{:?}", directive);
        }
    }

    #[test]
    fn test_default_values_per_directive() {
        assert_eq!(ReplDirective::Help.default_name(), "help");
        assert_eq!(ReplDirective::Help.default_aliases(), &["h", "?"]);
        assert_eq!(ReplDirective::Help.usage(), "[command]");

        assert_eq!(ReplDirective::Load.default_name(), "load");
        assert!(ReplDirective::Load.default_aliases().is_empty());
        assert_eq!(ReplDirective::Load.usage(), "<path>");

        assert_eq!(ReplDirective::Quit.default_name(), "quit");
        assert_eq!(ReplDirective::Quit.default_aliases(), &["q"]);
        assert_eq!(ReplDirective::Quit.usage(), "");

        assert_eq!(ReplDirective::Exit.default_name(), "exit");
        assert!(ReplDirective::Exit.default_aliases().is_empty());
        assert_eq!(ReplDirective::Exit.usage(), "");
    }

    #[test]
    fn test_default_names_and_aliases_are_disjoint_and_valid() {
        let mut seen = HashSet::new();
        for &directive in ReplDirective::ALL {
            let tokens = std::iter::once(directive.default_name())
                .chain(directive.default_aliases().iter().copied());
            for token in tokens {
                assert!(!token.is_empty());
                assert!(!token.starts_with(':'));
                assert!(!token.chars().any(char::is_whitespace));
                assert!(seen.insert(token), "'{}' used twice", token);
            }
        }
    }

    #[test]
    fn test_usage_has_no_surrounding_whitespace() {
        for &directive in ReplDirective::ALL {
            assert_eq!(directive.usage(), directive.usage().trim());
        }
    }

    #[test]
    fn test_default_for_matches_accessors() {
        for &directive in ReplDirective::ALL {
            let def = DirectiveDefinition::default_for(directive);
            assert_eq!(def.implementation, directive);
            assert_eq!(def.name, directive.default_name());
            assert_eq!(def.aliases, directive.default_aliases());
            assert_eq!(def.description, directive.default_description());
        }
    }

    #[test]
    fn test_usage_line_defaults() {
        let lines: Vec<_> = ReplDirective::ALL
            .iter()
            .map(|&d| DirectiveDefinition::default_for(d).usage_line())
            .collect();
        assert_eq!(
            lines,
            vec![":help [command]", ":load <path>", ":quit", ":exit"]
        );
    }

    #[test]
    fn test_usage_line_follows_overridden_name() {
        assert_eq!(
            entry(ReplDirective::Help, "aide", &[]).usage_line(),
            ":aide [command]"
        );
        assert_eq!(
            entry(ReplDirective::Exit, "sortir", &[]).usage_line(),
            ":sortir"
        );
    }

    // ------------------------------------------------------------------
    // Serde
    // ------------------------------------------------------------------

    #[test]
    fn test_serde_identifiers_match_as_str() {
        for &directive in ReplDirective::ALL {
            let yaml = serde_yaml::to_string(&directive).unwrap();
            assert_eq!(yaml.trim(), directive.as_str());
            let back: ReplDirective = serde_yaml::from_str(directive.as_str()).unwrap();
            assert_eq!(back, directive);
        }
    }

    #[test]
    fn test_deserialize_definition_aliases_default_empty() {
        let yaml = r#"
implementation: repl_exit
name: sortir
description: "Sortir sans enregistrer"
"#;
        let def: DirectiveDefinition = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(def.implementation, ReplDirective::Exit);
        assert_eq!(def.name, "sortir");
        assert!(def.aliases.is_empty());
    }

    #[test]
    fn test_deserialize_definition_requires_name_and_description() {
        let no_name = "implementation: repl_help\ndescription: x\n";
        assert!(serde_yaml::from_str::<DirectiveDefinition>(no_name).is_err());
        let no_description = "implementation: repl_help\nname: aide\n";
        assert!(serde_yaml::from_str::<DirectiveDefinition>(no_description).is_err());
    }

    #[test]
    fn test_deserialize_unknown_implementation_lists_valid_values() {
        let yaml = "implementation: repl_history\nname: hist\ndescription: x\n";
        let err = serde_yaml::from_str::<DirectiveDefinition>(yaml)
            .unwrap_err()
            .to_string();
        assert!(err.contains("repl_history"), "{}", err);
        for &directive in ReplDirective::ALL {
            assert!(err.contains(directive.as_str()), "{}", err);
        }
    }

    // ------------------------------------------------------------------
    // Merge
    // ------------------------------------------------------------------

    #[test]
    fn test_effective_directives_without_override() {
        let table = effective_directives(&[]);
        let expected: Vec<_> = ReplDirective::ALL
            .iter()
            .map(|&d| DirectiveDefinition::default_for(d))
            .collect();
        assert_eq!(table, expected);
    }

    #[test]
    fn test_effective_directives_partial_override() {
        let help = entry(ReplDirective::Help, "aide", &[]);
        let table = effective_directives(std::slice::from_ref(&help));

        assert_eq!(table.len(), ReplDirective::ALL.len());
        assert_eq!(table[0], help);
        // Overriding replaces the aliases: `h` and `?` are gone.
        assert!(table[0].aliases.is_empty());
        for (def, &directive) in table.iter().zip(ReplDirective::ALL).skip(1) {
            assert_eq!(*def, DirectiveDefinition::default_for(directive));
        }
    }

    #[test]
    fn test_effective_directives_full_override_keeps_all_order() {
        // Overrides given in reverse order; the table follows `ALL`.
        let overrides = vec![
            entry(ReplDirective::Exit, "sortir", &[]),
            entry(ReplDirective::Quit, "quitter", &["q"]),
            entry(ReplDirective::Load, "charger", &["c"]),
            entry(ReplDirective::Help, "aide", &["a", "?"]),
        ];
        let table = effective_directives(&overrides);

        let names: Vec<_> = table.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(names, vec!["aide", "charger", "quitter", "sortir"]);
        let order: Vec<_> = table.iter().map(|d| d.implementation).collect();
        assert_eq!(order, ReplDirective::ALL);
    }

    #[test]
    fn test_effective_directives_last_duplicate_wins() {
        let overrides = vec![
            entry(ReplDirective::Quit, "first", &[]),
            entry(ReplDirective::Quit, "second", &[]),
        ];
        let table = effective_directives(&overrides);
        assert_eq!(table[2].name, "second");
    }
}