clap_utilities/
command_factory_extra.rs

1use crate::{completion_generator, CompletionGenerator};
2use clap::CommandFactory;
3use clap_complete::{generate, Shell};
4use pipe_trait::Pipe;
5use std::{io::Write, process::ExitCode, str};
6
7/// Additional methods for [`CommandFactory`].
8pub trait CommandFactoryExtra: CommandFactory {
9    /// Get completion content.
10    fn get_completion<Completion, Name>(name: Name, shell: Shell) -> Completion
11    where
12        Completion: Write + Default,
13        Name: Into<String>,
14    {
15        let mut completion = Completion::default();
16        let mut command = Self::command();
17        generate(shell, &mut command, name, &mut completion);
18        completion
19    }
20
21    /// Get completion string.
22    fn get_completion_string(
23        name: impl Into<String>,
24        shell: Shell,
25    ) -> Result<String, str::Utf8Error> {
26        Self::get_completion::<Vec<u8>, _>(name, shell)
27            .pipe_as_ref(str::from_utf8)
28            .map(ToString::to_string)
29    }
30
31    /// Generate a shell completion file.
32    fn generate_completion(
33        generator: CompletionGenerator,
34    ) -> Result<(), completion_generator::Error> {
35        generator.run::<Self>()
36    }
37
38    /// Create and run the completion generator.
39    fn run_completion_generator() -> ExitCode {
40        CompletionGenerator::main::<Self>()
41    }
42}
43
44impl<App: CommandFactory> CommandFactoryExtra for App {}