1mod bash;
45mod fish;
46mod man;
47mod nushell;
48mod zsh;
49
50use crate::Record;
51
52pub use bash::bash;
53pub use fish::fish;
54pub use man::man_page;
55pub use nushell::nushell;
56pub use zsh::zsh;
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct Command<'a> {
61 pub name: &'a str,
63 pub summary: &'a str,
65}
66
67#[derive(Clone, Copy, Debug)]
69pub struct Program<'a> {
70 pub name: &'a str,
72 pub version: &'a str,
74 pub about: &'a str,
76 pub commands: &'a [Command<'a>],
78 pub exit_status: &'a [(&'a str, &'a str)],
80 pub see_also: &'a [&'a str],
82 pub date: &'a str,
85}
86
87#[derive(Clone, Debug, PartialEq, Eq)]
89pub enum GenerateError {
90 InvalidName(String),
93}
94
95impl std::fmt::Display for GenerateError {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 match self {
98 GenerateError::InvalidName(name) => write!(
99 f,
100 "`{name}` is not a plain name (letters, digits and `_ . -` only), so it cannot \
101 be written into a shell completion"
102 ),
103 }
104 }
105}
106
107impl std::error::Error for GenerateError {}
108
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub enum Shell {
112 Bash,
114 Zsh,
116 Fish,
118 Nushell,
120}
121
122impl Shell {
123 pub const ALL: [Shell; 4] = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::Nushell];
125
126 pub const fn token(self) -> &'static str {
128 match self {
129 Shell::Bash => "bash",
130 Shell::Zsh => "zsh",
131 Shell::Fish => "fish",
132 Shell::Nushell => "nushell",
133 }
134 }
135
136 pub fn parse(token: &str) -> Option<Shell> {
138 match token {
139 "bash" => Some(Shell::Bash),
140 "zsh" => Some(Shell::Zsh),
141 "fish" => Some(Shell::Fish),
142 "nushell" | "nu" => Some(Shell::Nushell),
143 _ => None,
144 }
145 }
146}
147
148pub fn completions(
150 shell: Shell,
151 program: &Program<'_>,
152 records: &[Record],
153) -> Result<String, GenerateError> {
154 match shell {
155 Shell::Bash => bash(program, records),
156 Shell::Zsh => zsh(program, records),
157 Shell::Fish => fish(program, records),
158 Shell::Nushell => nushell(program, records),
159 }
160}
161
162#[derive(Clone, Debug)]
167pub(crate) struct Flag {
168 pub long: Option<String>,
169 pub short: Option<String>,
170 pub takes_value: bool,
171 pub value_name: String,
172 pub values: Vec<String>,
174 pub path: bool,
175 pub negatable: bool,
176 pub summary: String,
177 pub default: Option<String>,
179 pub env: Vec<String>,
180 pub group: String,
181 pub scope: Vec<String>,
183}
184
185impl Flag {
186 pub fn available_for(&self, command: &str) -> bool {
187 self.scope.is_empty() || self.scope.iter().any(|s| s == command)
188 }
189
190 pub fn spellings(&self) -> Vec<String> {
192 let mut out = Vec::new();
193 if let Some(s) = &self.short {
194 out.push(format!("-{s}"));
195 }
196 if let Some(l) = &self.long {
197 out.push(format!("--{l}"));
198 if self.negatable {
199 out.push(format!("--no-{l}"));
200 }
201 }
202 out
203 }
204}
205
206#[derive(Clone, Debug)]
208pub(crate) struct Positional {
209 pub index: usize,
211 pub name: String,
212 pub values: Vec<String>,
213 pub path: bool,
214 pub required: bool,
215 pub summary: String,
216 pub scope: Vec<String>,
217}
218
219impl Positional {
220 pub fn available_for(&self, command: &str) -> bool {
221 self.scope.iter().any(|s| s == command)
222 }
223}
224
225pub(crate) fn is_plain(token: &str) -> bool {
227 !token.is_empty()
228 && token.chars().all(|c| {
229 c.is_ascii_alphanumeric()
230 || matches!(c, '_' | '.' | '-' | ':' | '/' | '+' | '=' | '@' | ',')
231 })
232}
233
234pub(crate) fn is_name(token: &str) -> bool {
236 is_plain(token) && !token.starts_with('-')
237}
238
239pub(crate) fn one_line(text: &str) -> String {
241 text.split(|c: char| c.is_whitespace() || c.is_control())
242 .filter(|part| !part.is_empty())
243 .collect::<Vec<_>>()
244 .join(" ")
245}
246
247pub(crate) struct Model {
249 pub flags: Vec<Flag>,
250 pub positionals: Vec<Positional>,
251}
252
253pub(crate) fn model(records: &[Record]) -> Model {
254 let mut flags = Vec::new();
255 let mut positionals = Vec::new();
256 for record in records {
257 let Some(arg) = &record.arg else { continue };
258 let values: Vec<String> = if matches!(record.ty.as_str(), "enum" | "list") {
259 record
260 .allowed
261 .iter()
262 .filter(|v| is_plain(v))
263 .cloned()
264 .collect()
265 } else {
266 Vec::new()
267 };
268 let summary = one_line(record.summary.as_deref().unwrap_or(""));
269 let scope: Vec<String> = record
270 .subcommands
271 .iter()
272 .filter(|s| is_name(s))
273 .cloned()
274 .collect();
275 if let Some(position) = arg.position {
276 positionals.push(Positional {
277 index: usize::from(position),
278 name: arg
279 .value_name
280 .clone()
281 .filter(|n| is_plain(n))
282 .unwrap_or_else(|| record.key.to_uppercase()),
283 values,
284 path: record.ty == "path",
285 required: record.required,
286 summary,
287 scope,
288 });
289 continue;
290 }
291 let long = arg.long.clone().filter(|l| is_name(l));
292 let short = arg
293 .short
294 .clone()
295 .filter(|s| s.chars().count() == 1 && is_name(s));
296 if long.is_none() && short.is_none() {
297 continue;
298 }
299 flags.push(Flag {
300 long,
301 short,
302 takes_value: arg.arity > 0,
303 value_name: arg
304 .value_name
305 .clone()
306 .filter(|n| is_plain(n))
307 .unwrap_or_else(|| "VALUE".to_string()),
308 values,
309 path: record.ty == "path",
310 negatable: arg.negatable,
311 summary,
312 default: record.default.as_ref().and_then(|v| match v {
313 serde_json::Value::String(text) => Some(text.clone()),
314 serde_json::Value::Number(n) => Some(n.to_string()),
315 _ => None,
316 }),
317 env: record
318 .env_names()
319 .iter()
320 .filter(|n| is_plain(n))
321 .map(|n| (*n).to_string())
322 .collect(),
323 group: record
324 .group
325 .clone()
326 .unwrap_or_else(|| "options".to_string()),
327 scope,
328 });
329 }
330 positionals.sort_by_key(|p| p.index);
331 Model { flags, positionals }
332}
333
334pub(crate) fn commands<'a>(program: &Program<'a>) -> Result<Vec<Command<'a>>, GenerateError> {
336 if !is_name(program.name) {
337 return Err(GenerateError::InvalidName(program.name.to_string()));
338 }
339 program
340 .commands
341 .iter()
342 .map(|c| {
343 if is_name(c.name) {
344 Ok(*c)
345 } else {
346 Err(GenerateError::InvalidName(c.name.to_string()))
347 }
348 })
349 .collect()
350}
351
352pub(crate) fn identifier(name: &str) -> String {
354 name.chars()
355 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
356 .collect()
357}