Skip to main content

argument_completions/
lib.rs

1//! Shell completion generation for [`argument`] based command line interfaces.
2//!
3//! This crate generates static completion scripts from a [`Cli`](argument::Cli)
4//! description.  The following shells are supported: bash, elvish, fish,
5//! nushell, PowerShell and zsh.
6//!
7//! ```
8//! use argument::{Cli, Opt, ValueHint};
9//! use argument_completions::Shell;
10//!
11//! #[derive(Copy, Clone)]
12//! enum Arg {
13//!     Output,
14//! }
15//!
16//! static CLI: Cli<Arg> = Cli::new("demo").opts(&[Opt::new(Arg::Output)
17//!     .short('o')
18//!     .long("output")
19//!     .value("FILE")
20//!     .value_hint(ValueHint::FilePath)
21//!     .help("Output file")]);
22//!
23//! let script = Shell::Bash.generate(&CLI, "demo");
24//! assert!(script.contains("complete -F _demo"));
25//! ```
26//!
27//! To offer completions at runtime (eg: via `--generate-completion SHELL`),
28//! use [`Shell::NAMES`] as possible values and parse the shell with
29//! [`str::parse`].
30use std::fmt;
31use std::fs;
32use std::io;
33use std::path::{Path, PathBuf};
34use std::str::FromStr;
35
36use argument::{ArgumentInfo, CommandInfo, OptionInfo, PossibleValue, ValueHint};
37
38mod bash;
39mod elvish;
40mod fish;
41mod nushell;
42mod powershell;
43mod zsh;
44
45/// The supported shells.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47#[non_exhaustive]
48pub enum Shell {
49    /// GNU bash (3.2 and later)
50    Bash,
51    /// Elvish
52    Elvish,
53    /// fish
54    Fish,
55    /// Nushell
56    Nushell,
57    /// PowerShell
58    PowerShell,
59    /// Z shell
60    Zsh,
61}
62
63impl Shell {
64    /// All supported shells.
65    pub const ALL: &'static [Shell] = &[
66        Shell::Bash,
67        Shell::Elvish,
68        Shell::Fish,
69        Shell::Nushell,
70        Shell::PowerShell,
71        Shell::Zsh,
72    ];
73
74    /// The names of all supported shells.
75    ///
76    /// This can be used with [`Opt::possible_values`](argument::Opt::possible_values).
77    pub const NAMES: &'static [&'static str] =
78        &["bash", "elvish", "fish", "nushell", "powershell", "zsh"];
79
80    /// The name of the shell.
81    pub fn name(self) -> &'static str {
82        match self {
83            Shell::Bash => "bash",
84            Shell::Elvish => "elvish",
85            Shell::Fish => "fish",
86            Shell::Nushell => "nushell",
87            Shell::PowerShell => "powershell",
88            Shell::Zsh => "zsh",
89        }
90    }
91
92    /// The conventional file name of the completion script.
93    pub fn file_name(self, bin_name: &str) -> String {
94        match self {
95            Shell::Bash => format!("{}.bash", bin_name),
96            Shell::Elvish => format!("{}.elv", bin_name),
97            Shell::Fish => format!("{}.fish", bin_name),
98            Shell::Nushell => format!("{}.nu", bin_name),
99            Shell::PowerShell => format!("_{}.ps1", bin_name),
100            Shell::Zsh => format!("_{}", bin_name),
101        }
102    }
103
104    /// Generates the completion script for the given command.
105    ///
106    /// `bin_name` is the name of the executable that is completed.
107    pub fn generate(self, cmd: &dyn CommandInfo, bin_name: &str) -> String {
108        let root = Node::new(cmd, bin_name, Vec::new());
109        match self {
110            Shell::Bash => bash::generate(&root),
111            Shell::Elvish => elvish::generate(&root),
112            Shell::Fish => fish::generate(&root),
113            Shell::Nushell => nushell::generate(&root),
114            Shell::PowerShell => powershell::generate(&root),
115            Shell::Zsh => zsh::generate(&root),
116        }
117    }
118
119    /// Generates the completion script into the given directory.
120    ///
121    /// The file is named after [`file_name`](Self::file_name) and the path
122    /// to the written file is returned.
123    pub fn generate_to(
124        self,
125        cmd: &dyn CommandInfo,
126        bin_name: &str,
127        dir: &Path,
128    ) -> io::Result<PathBuf> {
129        let path = dir.join(self.file_name(bin_name));
130        fs::write(&path, self.generate(cmd, bin_name))?;
131        Ok(path)
132    }
133}
134
135impl fmt::Display for Shell {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        f.write_str(self.name())
138    }
139}
140
141/// Error returned when parsing an unknown shell name.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct UnknownShellError(String);
144
145impl fmt::Display for UnknownShellError {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        write!(
148            f,
149            "unknown shell '{}' (supported: {})",
150            self.0,
151            Shell::NAMES.join(", ")
152        )
153    }
154}
155
156impl std::error::Error for UnknownShellError {}
157
158impl FromStr for Shell {
159    type Err = UnknownShellError;
160
161    fn from_str(s: &str) -> Result<Shell, UnknownShellError> {
162        Shell::ALL
163            .iter()
164            .copied()
165            .find(|x| x.name() == s)
166            .ok_or_else(|| UnknownShellError(s.to_string()))
167    }
168}
169
170/// A normalized command tree that the generators work with.
171pub(crate) struct Node {
172    /// The name of the command (the binary name for the root).
173    pub name: String,
174    /// The names of the commands from the binary to this command.
175    pub path: Vec<String>,
176    pub about: Option<&'static str>,
177    pub options: Vec<OptionInfo>,
178    pub arguments: Vec<ArgumentInfo>,
179    pub children: Vec<Node>,
180}
181
182impl Node {
183    fn new(cmd: &dyn CommandInfo, name: &str, parent_path: Vec<String>) -> Node {
184        let mut path = parent_path;
185        path.push(name.to_string());
186        Node {
187            name: name.to_string(),
188            about: cmd.about(),
189            options: cmd
190                .options()
191                .into_iter()
192                .filter(|x| !x.is_hidden())
193                .collect(),
194            arguments: cmd.arguments(),
195            children: cmd
196                .commands()
197                .into_iter()
198                .map(|sub| Node::new(sub, sub.name(), path.clone()))
199                .collect(),
200            path,
201        }
202    }
203
204    /// The binary name.
205    pub fn bin_name(&self) -> &str {
206        &self.path[0]
207    }
208
209    /// An identifier for this command that is safe to use in function names.
210    pub fn ident(&self) -> String {
211        self.path
212            .iter()
213            .map(|x| ident(x))
214            .collect::<Vec<_>>()
215            .join("__")
216    }
217
218    /// Iterates over this node and all descendants (depth first).
219    pub fn walk(&self) -> Vec<&Node> {
220        let mut rv = vec![self];
221        for child in &self.children {
222            rv.extend(child.walk());
223        }
224        rv
225    }
226}
227
228/// Converts a name into something that is safe for function names.
229pub(crate) fn ident(s: &str) -> String {
230    s.chars()
231        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
232        .collect()
233}
234
235/// Returns the first line of a help text.
236pub(crate) fn first_line(s: &str) -> &str {
237    s.lines().next().unwrap_or("").trim()
238}
239
240/// The completion of a value.
241pub(crate) enum ValueCompletion {
242    /// One of the given values.
243    Values(Vec<PossibleValue>),
244    /// A hint.
245    Hint(ValueHint),
246}
247
248impl ValueCompletion {
249    pub fn for_option(opt: &OptionInfo) -> ValueCompletion {
250        let values = opt.possible_values();
251        if values.is_empty() {
252            ValueCompletion::Hint(opt.value_hint())
253        } else {
254            ValueCompletion::Values(values)
255        }
256    }
257
258    pub fn for_argument(arg: &ArgumentInfo) -> ValueCompletion {
259        let values = arg.possible_values();
260        if values.is_empty() {
261            ValueCompletion::Hint(arg.value_hint())
262        } else {
263            ValueCompletion::Values(values)
264        }
265    }
266
267    /// Returns `true` if the shell should fall back to completing files.
268    pub fn completes_files(&self) -> bool {
269        matches!(
270            self,
271            ValueCompletion::Hint(
272                ValueHint::Unknown
273                    | ValueHint::AnyPath
274                    | ValueHint::FilePath
275                    | ValueHint::ExecutablePath
276            )
277        )
278    }
279}
280
281// the examples of the readme are tested
282#[cfg(doctest)]
283#[doc = include_str!("../README.md")]
284struct ReadmeDoctests;