1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47#[non_exhaustive]
48pub enum Shell {
49 Bash,
51 Elvish,
53 Fish,
55 Nushell,
57 PowerShell,
59 Zsh,
61}
62
63impl Shell {
64 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 pub const NAMES: &'static [&'static str] =
78 &["bash", "elvish", "fish", "nushell", "powershell", "zsh"];
79
80 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 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 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 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#[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
170pub(crate) struct Node {
172 pub name: String,
174 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 pub fn bin_name(&self) -> &str {
206 &self.path[0]
207 }
208
209 pub fn ident(&self) -> String {
211 self.path
212 .iter()
213 .map(|x| ident(x))
214 .collect::<Vec<_>>()
215 .join("__")
216 }
217
218 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
228pub(crate) fn ident(s: &str) -> String {
230 s.chars()
231 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
232 .collect()
233}
234
235pub(crate) fn first_line(s: &str) -> &str {
237 s.lines().next().unwrap_or("").trim()
238}
239
240pub(crate) enum ValueCompletion {
242 Values(Vec<PossibleValue>),
244 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 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#[cfg(doctest)]
283#[doc = include_str!("../README.md")]
284struct ReadmeDoctests;