Skip to main content

dynamic_cli/plugin/
system.rs

1//! Built-in system plugin for `dynamic-cli`
2//!
3//! Provides [`SystemPlugin`], a ready-made plugin 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::plugin::Plugin;
14use crate::Result;
15use std::collections::HashMap;
16use std::sync::Arc;
17
18// ============================================================================
19// SystemPlugin
20// ============================================================================
21
22/// Built-in plugin 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 plugin 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`][crate::help::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 plugin = 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 plugin = SystemPlugin::new();
92/// assert_eq!(plugin.name(), "system");
93///
94/// let handlers = plugin.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 plugin 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 plugin = SystemPlugin::new().with_config(config);
156    /// assert_eq!(plugin.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 {
219                    config: config.clone(),
220                }),
221            ),
222            (
223                "system_version".to_string(),
224                Box::new(SystemVersionHandler { config }),
225            ),
226            (
227                "system_exit".to_string(),
228                Box::new(SystemExitHandler { exit_fn }),
229            ),
230        ]
231    }
232}
233
234// ============================================================================
235// System handlers (private)
236// ============================================================================
237
238/// Handler for `system_help` — prints app-level or per-command help.
239struct SystemHelpHandler {
240    config: Option<CommandsConfig>,
241}
242
243impl CommandHandler for SystemHelpHandler {
244    fn execute(
245        &self,
246        _ctx: &mut dyn ExecutionContext,
247        args: &HashMap<String, String>,
248    ) -> Result<()> {
249        let formatter = DefaultHelpFormatter::new();
250
251        match self.config.as_ref() {
252            Some(cfg) => {
253                if let Some(command) = args.get("command") {
254                    print!("{}", formatter.format_command(cfg, command));
255                } else {
256                    print!("{}", formatter.format_app(cfg));
257                }
258            }
259            None => {
260                println!("Help is not available (no configuration loaded).");
261            }
262        }
263        Ok(())
264    }
265}
266
267/// Handler for `system_version` — prints the app version from config metadata.
268struct SystemVersionHandler {
269    config: Option<CommandsConfig>,
270}
271
272impl CommandHandler for SystemVersionHandler {
273    fn execute(
274        &self,
275        _ctx: &mut dyn ExecutionContext,
276        _args: &HashMap<String, String>,
277    ) -> Result<()> {
278        match self.config.as_ref() {
279            Some(cfg) => println!("{}", cfg.metadata.version),
280            None => println!("(version unknown)"),
281        }
282        Ok(())
283    }
284}
285
286/// Handler for `system_exit` — invokes the shutdown callback and exits.
287///
288/// The callback is set via [`SystemPlugin::with_exit_fn`]. The default
289/// callback calls `std::process::exit(0)`.
290struct SystemExitHandler {
291    /// Shutdown callback — runs before the process exits.
292    exit_fn: Arc<dyn Fn() + Send + Sync>,
293}
294
295impl CommandHandler for SystemExitHandler {
296    fn execute(
297        &self,
298        _ctx: &mut dyn ExecutionContext,
299        _args: &HashMap<String, String>,
300    ) -> Result<()> {
301        // Run the shutdown sequence supplied by the application.
302        // The default implementation calls std::process::exit(0).
303        (self.exit_fn)();
304        // Unreachable in production (exit_fn terminates the process),
305        // but required for the return type in test configurations
306        // where exit_fn does not call std::process::exit.
307        Ok(())
308    }
309}
310
311// ============================================================================
312// Tests
313// ============================================================================
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use crate::config::schema::{CommandsConfig, Metadata};
319    use std::any::Any;
320
321    // -------------------------------------------------------------------------
322    // Test fixtures
323    // -------------------------------------------------------------------------
324
325    #[derive(Default)]
326    struct TestContext;
327
328    impl ExecutionContext for TestContext {
329        fn as_any(&self) -> &dyn Any {
330            self
331        }
332        fn as_any_mut(&mut self) -> &mut dyn Any {
333            self
334        }
335    }
336
337    fn test_config() -> CommandsConfig {
338        CommandsConfig {
339            metadata: Metadata {
340                version: "2.0.0".to_string(),
341                prompt: "testapp".to_string(),
342                prompt_suffix: " > ".to_string(),
343            },
344            commands: vec![],
345            global_options: vec![],
346        }
347    }
348
349    // -------------------------------------------------------------------------
350    // Metadata
351    // -------------------------------------------------------------------------
352
353    #[test]
354    fn test_system_plugin_metadata() {
355        let p = SystemPlugin::new();
356        assert_eq!(p.name(), "system");
357        assert!(!p.version().is_empty());
358        assert!(!p.description().is_empty());
359    }
360
361    #[test]
362    fn test_system_plugin_default() {
363        let p = SystemPlugin::default();
364        assert_eq!(p.name(), "system");
365    }
366
367    #[test]
368    fn test_system_plugin_handler_names() {
369        let handlers = SystemPlugin::new().handlers();
370        let names: Vec<&str> = handlers.iter().map(|(n, _)| n.as_str()).collect();
371        assert!(names.contains(&"system_help"));
372        assert!(names.contains(&"system_version"));
373        assert!(names.contains(&"system_exit"));
374        assert_eq!(handlers.len(), 3);
375    }
376
377    // -------------------------------------------------------------------------
378    // with_config
379    // -------------------------------------------------------------------------
380
381    #[test]
382    fn test_system_plugin_with_config() {
383        let plugin = SystemPlugin::new().with_config(test_config());
384        assert!(plugin.config.is_some());
385        assert_eq!(plugin.config.unwrap().metadata.version, "2.0.0");
386    }
387
388    #[test]
389    fn test_system_version_handler_with_config() {
390        let plugin = SystemPlugin::new().with_config(test_config());
391        let handlers = plugin.handlers();
392        let (name, handler) = handlers
393            .iter()
394            .find(|(n, _)| n == "system_version")
395            .unwrap();
396        assert_eq!(name, "system_version");
397        let mut ctx = TestContext;
398        assert!(handler.execute(&mut ctx, &HashMap::new()).is_ok());
399    }
400
401    #[test]
402    fn test_system_version_handler_without_config() {
403        let handlers = SystemPlugin::new().handlers();
404        let (_, handler) = handlers
405            .iter()
406            .find(|(n, _)| n == "system_version")
407            .unwrap();
408        let mut ctx = TestContext;
409        assert!(handler.execute(&mut ctx, &HashMap::new()).is_ok());
410    }
411
412    #[test]
413    fn test_system_help_handler_with_config() {
414        let plugin = SystemPlugin::new().with_config(test_config());
415        let handlers = plugin.handlers();
416        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_help").unwrap();
417        let mut ctx = TestContext;
418        assert!(handler.execute(&mut ctx, &HashMap::new()).is_ok());
419    }
420
421    #[test]
422    fn test_system_help_handler_with_command_arg() {
423        let plugin = SystemPlugin::new().with_config(test_config());
424        let handlers = plugin.handlers();
425        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_help").unwrap();
426        let mut ctx = TestContext;
427        let mut args = HashMap::new();
428        args.insert("command".to_string(), "nonexistent".to_string());
429        assert!(handler.execute(&mut ctx, &args).is_ok());
430    }
431
432    #[test]
433    fn test_system_help_handler_without_config() {
434        let handlers = SystemPlugin::new().handlers();
435        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_help").unwrap();
436        let mut ctx = TestContext;
437        assert!(handler.execute(&mut ctx, &HashMap::new()).is_ok());
438    }
439
440    // -------------------------------------------------------------------------
441    // Shutdown callback
442    // -------------------------------------------------------------------------
443
444    #[test]
445    fn test_system_exit_default_callback_is_set() {
446        // Verify that SystemPlugin::new() initialises exit_fn without panicking.
447        // The default callback (process::exit) cannot be invoked in tests;
448        // we only check that the plugin builds and exposes the handler.
449        let plugin = SystemPlugin::new();
450        let handlers = plugin.handlers();
451        assert!(handlers.iter().any(|(n, _)| n == "system_exit"));
452    }
453
454    #[test]
455    fn test_system_exit_custom_callback_invoked() {
456        use std::sync::atomic::{AtomicBool, Ordering};
457
458        let called = Arc::new(AtomicBool::new(false));
459        let called_clone = called.clone();
460
461        let plugin = SystemPlugin::new().with_exit_fn(move || {
462            called_clone.store(true, Ordering::SeqCst);
463            // Does NOT call std::process::exit — safe in tests.
464        });
465
466        let handlers = plugin.handlers();
467        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_exit").unwrap();
468
469        let mut ctx = TestContext;
470        let result = handler.execute(&mut ctx, &HashMap::new());
471
472        assert!(result.is_ok());
473        assert!(
474            called.load(Ordering::SeqCst),
475            "shutdown callback was not invoked"
476        );
477    }
478
479    #[test]
480    fn test_system_exit_callback_ignores_args() {
481        use std::sync::atomic::{AtomicBool, Ordering};
482
483        let called = Arc::new(AtomicBool::new(false));
484        let called_clone = called.clone();
485
486        let plugin = SystemPlugin::new().with_exit_fn(move || {
487            called_clone.store(true, Ordering::SeqCst);
488        });
489
490        let handlers = plugin.handlers();
491        let (_, handler) = handlers.iter().find(|(n, _)| n == "system_exit").unwrap();
492
493        let mut ctx = TestContext;
494        let mut args = HashMap::new();
495        args.insert("unexpected_arg".to_string(), "value".to_string());
496
497        assert!(handler.execute(&mut ctx, &args).is_ok());
498        assert!(called.load(Ordering::SeqCst));
499    }
500
501    #[test]
502    fn test_with_exit_fn_is_send_sync() {
503        fn assert_send_sync<T: Send + Sync>(_: T) {}
504        let plugin = SystemPlugin::new().with_exit_fn(|| {});
505        assert_send_sync(plugin);
506    }
507}