Skip to main content

dynamic_cli/plugin/
system.rs

1//! Built-in system builtin for `dynamic-cli`
2//!
3//! Provides [`SystemPlugin`], a ready-made builtin supplying the three handlers
4//! that every `dynamic-cli` application typically needs: `system_help`,
5//! `system_version`, and `system_exit`.
6//!
7//! See [`SystemPlugin`] for usage and YAML configuration examples.
8
9use crate::config::schema::CommandsConfig;
10use crate::context::ExecutionContext;
11use crate::executor::CommandHandler;
12use crate::help::{DefaultHelpFormatter, HelpFormatter};
13use crate::parser::ParsedArgs;
14use crate::plugin::Plugin;
15use crate::Result;
16use std::sync::Arc;
17
18// ============================================================================
19// SystemPlugin
20// ============================================================================
21
22/// Built-in builtin providing standard system commands.
23///
24/// Supplies ready-made handlers for the commands that every `dynamic-cli`
25/// application typically needs. Users declare the corresponding commands in
26/// their YAML config and register the builtin once — no manual handler wiring.
27///
28/// # Provided handlers
29///
30/// | Implementation name | Behaviour |
31/// |---------------------|-----------|
32/// | `system_help`       | Prints application or per-command help via the active [`HelpFormatter`] |
33/// | `system_version`    | Prints the version from `metadata.version` in the config |
34/// | `system_exit`       | Runs the shutdown callback then exits (default: `std::process::exit(0)`) |
35///
36/// # Shutdown callback
37///
38/// `system_exit` accepts an optional callback via [`SystemPlugin::with_exit_fn`].
39/// The callback runs **before** the process exits, allowing the application to
40/// flush buffers, close connections, save state, or log a goodbye message.
41///
42/// The default callback calls `std::process::exit(0)` directly. Provide a
43/// custom one when a clean shutdown sequence is required:
44///
45/// ```no_run
46/// use dynamic_cli::plugin::SystemPlugin;
47///
48/// let builtin = SystemPlugin::new()
49///     .with_exit_fn(|| {
50///         // flush logs, close DB connections, save session…
51///         eprintln!("Goodbye.");
52///         std::process::exit(0);
53///     });
54/// ```
55///
56/// # YAML config
57///
58/// Declare the commands you want to activate:
59///
60/// ```yaml
61/// commands:
62///   - name: help
63///     implementation: system_help
64///     description: "Show help"
65///     aliases: ["h", "?"]
66///     required: false
67///     arguments: []
68///     options: []
69///
70///   - name: version
71///     implementation: system_version
72///     description: "Show version"
73///     required: false
74///     arguments: []
75///     options: []
76///
77///   - name: exit
78///     implementation: system_exit
79///     description: "Exit the application"
80///     aliases: ["quit", "q"]
81///     required: false
82///     arguments: []
83///     options: []
84/// ```
85///
86/// # Example
87///
88/// ```
89/// use dynamic_cli::plugin::{Plugin, SystemPlugin};
90///
91/// let builtin = SystemPlugin::new();
92/// assert_eq!(builtin.name(), "system");
93///
94/// let handlers = builtin.handlers();
95/// let names: Vec<&str> = handlers.iter().map(|(n, _)| n.as_str()).collect();
96/// assert!(names.contains(&"system_help"));
97/// assert!(names.contains(&"system_version"));
98/// assert!(names.contains(&"system_exit"));
99/// ```
100pub struct SystemPlugin {
101    /// Application config, needed by `system_help` and `system_version`.
102    config: Option<CommandsConfig>,
103
104    /// Shutdown callback invoked by `system_exit`.
105    ///
106    /// Defaults to `|| std::process::exit(0)`.
107    /// Override with [`SystemPlugin::with_exit_fn`] for a clean shutdown
108    /// sequence (flush buffers, close connections, save state, etc.).
109    exit_fn: Arc<dyn Fn() + Send + Sync>,
110}
111
112impl SystemPlugin {
113    /// Create a new `SystemPlugin` with the default shutdown behaviour.
114    ///
115    /// The default exit callback calls `std::process::exit(0)`. Use
116    /// [`with_exit_fn`][Self::with_exit_fn] to supply a custom shutdown
117    /// sequence.
118    ///
119    /// # Example
120    ///
121    /// ```
122    /// use dynamic_cli::plugin::{Plugin, SystemPlugin};
123    ///
124    /// let plugin = SystemPlugin::new();
125    /// assert_eq!(plugin.name(), "system");
126    /// ```
127    pub fn new() -> Self {
128        Self {
129            config: None,
130            exit_fn: Arc::new(|| std::process::exit(0)),
131        }
132    }
133
134    /// Attach a config so the system handlers can access app metadata.
135    ///
136    /// Called automatically by [`CliBuilder::build()`] when the builtin is
137    /// registered via [`CliBuilder::register_plugin`].
138    ///
139    /// # Example
140    ///
141    /// ```
142    /// use dynamic_cli::plugin::{Plugin, SystemPlugin};
143    /// use dynamic_cli::config::schema::{CommandsConfig, Metadata};
144    ///
145    /// let config = CommandsConfig {
146    ///     metadata: Metadata {
147    ///         version: "1.0.0".to_string(),
148    ///         prompt: "myapp".to_string(),
149    ///         prompt_suffix: " > ".to_string(),
150    ///     },
151    ///     commands: vec![],
152    ///     global_options: vec![],
153    /// };
154    ///
155    /// let builtin = SystemPlugin::new().with_config(config);
156    /// assert_eq!(builtin.name(), "system");
157    /// ```
158    pub fn with_config(mut self, config: CommandsConfig) -> Self {
159        self.config = Some(config);
160        self
161    }
162
163    /// Supply a custom shutdown callback for `system_exit`.
164    ///
165    /// The callback is invoked when the user runs the command bound to
166    /// `system_exit`. Use it to flush buffers, close connections, persist
167    /// state, or display a goodbye message before the process terminates.
168    ///
169    /// The callback must be `Fn() + Send + Sync + 'static`.
170    ///
171    /// # Example
172    ///
173    /// ```no_run
174    /// use dynamic_cli::plugin::SystemPlugin;
175    ///
176    /// let plugin = SystemPlugin::new()
177    ///     .with_exit_fn(|| {
178    ///         eprintln!("Saving session…");
179    ///         // close resources here
180    ///         std::process::exit(0);
181    ///     });
182    /// ```
183    pub fn with_exit_fn<F>(mut self, f: F) -> Self
184    where
185        F: Fn() + Send + Sync + 'static,
186    {
187        self.exit_fn = Arc::new(f);
188        self
189    }
190}
191
192impl Default for SystemPlugin {
193    fn default() -> Self {
194        Self::new()
195    }
196}
197
198impl Plugin for SystemPlugin {
199    fn name(&self) -> &str {
200        "system"
201    }
202
203    fn version(&self) -> &str {
204        env!("CARGO_PKG_VERSION")
205    }
206
207    fn description(&self) -> &str {
208        "Built-in system commands: help, version, exit"
209    }
210
211    fn handlers(&self) -> Vec<(String, Box<dyn CommandHandler>)> {
212        let config = self.config.clone();
213        let exit_fn = self.exit_fn.clone();
214
215        vec![
216            (
217                "system_help".to_string(),
218                Box::new(SystemHelpHandler::new(config.clone())),
219            ),
220            (
221                "system_version".to_string(),
222                Box::new(SystemVersionHandler::new(config)),
223            ),
224            (
225                "system_exit".to_string(),
226                Box::new(SystemExitHandler::new(exit_fn)),
227            ),
228        ]
229    }
230}
231
232// ============================================================================
233// System handlers (private)
234// ============================================================================
235
236/// Handler for `system_help` — prints app-level or per-command help.
237///
238/// `pub(crate)` so [`crate::plugin::builtin::HelpPlugin`] can reuse the
239/// exact same logic without duplicating it (see #44 / DD-025).
240pub(crate) struct SystemHelpHandler {
241    config: Option<CommandsConfig>,
242}
243
244impl SystemHelpHandler {
245    /// Build a new handler carrying the given (optional) config.
246    pub(crate) fn new(config: Option<CommandsConfig>) -> Self {
247        Self { config }
248    }
249}
250
251impl CommandHandler for SystemHelpHandler {
252    fn execute(&self, _ctx: &mut dyn ExecutionContext, args: &ParsedArgs) -> Result<()> {
253        let formatter = DefaultHelpFormatter::new();
254
255        match self.config.as_ref() {
256            Some(cfg) => {
257                if let Some(command) = args.get_scalar("command") {
258                    print!("{}", formatter.format_command(cfg, command));
259                } else {
260                    print!("{}", formatter.format_app(cfg));
261                }
262            }
263            None => {
264                println!("Help is not available (no configuration loaded).");
265            }
266        }
267        Ok(())
268    }
269}
270
271/// Handler for `system_version` — prints the app version from config metadata.
272///
273/// `pub(crate)` so [`crate::plugin::builtin::VersionPlugin`] can
274/// reuse the exact same logic without duplicating it (see #44 / DD-025).
275pub(crate) struct SystemVersionHandler {
276    config: Option<CommandsConfig>,
277}
278
279impl SystemVersionHandler {
280    /// Build a new handler carrying the given (optional) config.
281    pub(crate) fn new(config: Option<CommandsConfig>) -> Self {
282        Self { config }
283    }
284}
285
286impl CommandHandler for SystemVersionHandler {
287    fn execute(&self, _ctx: &mut dyn ExecutionContext, _args: &ParsedArgs) -> Result<()> {
288        match self.config.as_ref() {
289            Some(cfg) => println!("{}", cfg.metadata.version),
290            None => println!("(version unknown)"),
291        }
292        Ok(())
293    }
294}
295
296/// Handler for `system_exit` — invokes the shutdown callback and exits.
297///
298/// The callback is set via [`SystemPlugin::with_exit_fn`]. The default
299/// callback calls `std::process::exit(0)`.
300///
301/// `pub(crate)` so [`crate::plugin::builtin::ExitPlugin`] can reuse the
302/// exact same logic without duplicating it (see #44 / DD-025).
303pub(crate) struct SystemExitHandler {
304    /// Shutdown callback — runs before the process exits.
305    exit_fn: Arc<dyn Fn() + Send + Sync>,
306}
307
308impl SystemExitHandler {
309    /// Build a new handler carrying the given shutdown callback.
310    pub(crate) fn new(exit_fn: Arc<dyn Fn() + Send + Sync>) -> Self {
311        Self { exit_fn }
312    }
313}
314
315impl CommandHandler for SystemExitHandler {
316    fn execute(&self, _ctx: &mut dyn ExecutionContext, _args: &ParsedArgs) -> Result<()> {
317        // Run the shutdown sequence supplied by the application.
318        // The default implementation calls std::process::exit(0).
319        (self.exit_fn)();
320        // Unreachable in production (exit_fn terminates the process),
321        // but required for the return type in test configurations
322        // where exit_fn does not call std::process::exit.
323        Ok(())
324    }
325}
326
327// ============================================================================
328// Tests
329// ============================================================================
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use crate::config::schema::{CommandsConfig, Metadata};
335    use std::any::Any;
336    use std::collections::HashMap;
337
338    // -------------------------------------------------------------------------
339    // Test fixtures
340    // -------------------------------------------------------------------------
341
342    #[derive(Default)]
343    struct TestContext;
344
345    impl ExecutionContext for TestContext {
346        fn as_any(&self) -> &dyn Any {
347            self
348        }
349        fn as_any_mut(&mut self) -> &mut dyn Any {
350            self
351        }
352    }
353
354    fn test_config() -> CommandsConfig {
355        CommandsConfig {
356            metadata: Metadata {
357                version: "2.0.0".to_string(),
358                prompt: "testapp".to_string(),
359                prompt_suffix: " > ".to_string(),
360            },
361            commands: vec![],
362            global_options: vec![],
363        }
364    }
365
366    // -------------------------------------------------------------------------
367    // Metadata
368    // -------------------------------------------------------------------------
369
370    #[test]
371    fn test_system_plugin_metadata() {
372        let p = SystemPlugin::new();
373        assert_eq!(p.name(), "system");
374        assert!(!p.version().is_empty());
375        assert!(!p.description().is_empty());
376    }
377
378    #[test]
379    fn test_system_plugin_default() {
380        let p = SystemPlugin::default();
381        assert_eq!(p.name(), "system");
382    }
383
384    #[test]
385    fn test_system_plugin_handler_names() {
386        let handlers = SystemPlugin::new().handlers();
387        let names: Vec<&str> = handlers.iter().map(|(n, _)| n.as_str()).collect();
388        assert!(names.contains(&"system_help"));
389        assert!(names.contains(&"system_version"));
390        assert!(names.contains(&"system_exit"));
391        assert_eq!(handlers.len(), 3);
392    }
393
394    // -------------------------------------------------------------------------
395    // with_config
396    // -------------------------------------------------------------------------
397
398    #[test]
399    fn test_system_plugin_with_config() {
400        let plugin = SystemPlugin::new().with_config(test_config());
401        assert!(plugin.config.is_some());
402        assert_eq!(plugin.config.unwrap().metadata.version, "2.0.0");
403    }
404
405    #[test]
406    fn test_system_version_handler_with_config() {
407        let plugin = SystemPlugin::new().with_config(test_config());
408        let handlers = plugin.handlers();
409        let (name, handler) = handlers
410            .iter()
411            .find(|(n, _)| n == "system_version")
412            .unwrap();
413        assert_eq!(name, "system_version");
414        let mut ctx = TestContext;
415        assert!(handler
416            .execute(&mut ctx, &ParsedArgs::from_scalars(HashMap::new()))
417            .is_ok());
418    }
419
420    #[test]
421    fn test_system_version_handler_without_config() {
422        let handlers = SystemPlugin::new().handlers();
423        let (_, handler) = handlers
424            .iter()
425            .find(|(n, _)| n == "system_version")
426            .unwrap();
427        let mut ctx = TestContext;
428        assert!(handler
429            .execute(&mut ctx, &ParsedArgs::from_scalars(HashMap::new()))
430            .is_ok());
431    }
432
433    #[test]
434    fn test_system_help_handler_with_config() {
435        let plugin = SystemPlugin::new().with_config(test_config());
436        let handlers = plugin.handlers();
437        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_help").unwrap();
438        let mut ctx = TestContext;
439        assert!(handler
440            .execute(&mut ctx, &ParsedArgs::from_scalars(HashMap::new()))
441            .is_ok());
442    }
443
444    #[test]
445    fn test_system_help_handler_with_command_arg() {
446        let plugin = SystemPlugin::new().with_config(test_config());
447        let handlers = plugin.handlers();
448        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_help").unwrap();
449        let mut ctx = TestContext;
450        let mut args = HashMap::new();
451        args.insert("command".to_string(), "nonexistent".to_string());
452        let args = ParsedArgs::from_scalars(args);
453        assert!(handler.execute(&mut ctx, &args).is_ok());
454    }
455
456    #[test]
457    fn test_system_help_handler_without_config() {
458        let handlers = SystemPlugin::new().handlers();
459        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_help").unwrap();
460        let mut ctx = TestContext;
461        assert!(handler
462            .execute(&mut ctx, &ParsedArgs::from_scalars(HashMap::new()))
463            .is_ok());
464    }
465
466    // -------------------------------------------------------------------------
467    // Shutdown callback
468    // -------------------------------------------------------------------------
469
470    #[test]
471    fn test_system_exit_default_callback_is_set() {
472        // Verify that SystemPlugin::new() initialises exit_fn without panicking.
473        // The default callback (process::exit) cannot be invoked in tests;
474        // we only check that the builtin builds and exposes the handler.
475        let plugin = SystemPlugin::new();
476        let handlers = plugin.handlers();
477        assert!(handlers.iter().any(|(n, _)| n == "system_exit"));
478    }
479
480    #[test]
481    fn test_system_exit_custom_callback_invoked() {
482        use std::sync::atomic::{AtomicBool, Ordering};
483
484        let called = Arc::new(AtomicBool::new(false));
485        let called_clone = called.clone();
486
487        let plugin = SystemPlugin::new().with_exit_fn(move || {
488            called_clone.store(true, Ordering::SeqCst);
489            // Does NOT call std::process::exit — safe in tests.
490        });
491
492        let handlers = plugin.handlers();
493        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_exit").unwrap();
494
495        let mut ctx = TestContext;
496        let result = handler.execute(&mut ctx, &ParsedArgs::from_scalars(HashMap::new()));
497
498        assert!(result.is_ok());
499        assert!(
500            called.load(Ordering::SeqCst),
501            "shutdown callback was not invoked"
502        );
503    }
504
505    #[test]
506    fn test_system_exit_callback_ignores_args() {
507        use std::sync::atomic::{AtomicBool, Ordering};
508
509        let called = Arc::new(AtomicBool::new(false));
510        let called_clone = called.clone();
511
512        let plugin = SystemPlugin::new().with_exit_fn(move || {
513            called_clone.store(true, Ordering::SeqCst);
514        });
515
516        let handlers = plugin.handlers();
517        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_exit").unwrap();
518
519        let mut ctx = TestContext;
520        let mut args = HashMap::new();
521        args.insert("unexpected_arg".to_string(), "value".to_string());
522        let args = ParsedArgs::from_scalars(args);
523
524        assert!(handler.execute(&mut ctx, &args).is_ok());
525        assert!(called.load(Ordering::SeqCst));
526    }
527
528    #[test]
529    fn test_with_exit_fn_is_send_sync() {
530        fn assert_send_sync<T: Send + Sync>(_: T) {}
531        let plugin = SystemPlugin::new().with_exit_fn(|| {});
532        assert_send_sync(plugin);
533    }
534}