mod bash;
mod fish;
mod man;
mod nushell;
mod zsh;
use crate::Record;
pub use bash::bash;
pub use fish::fish;
pub use man::man_page;
pub use nushell::nushell;
pub use zsh::zsh;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Command<'a> {
pub name: &'a str,
pub summary: &'a str,
}
#[derive(Clone, Copy, Debug)]
pub struct Program<'a> {
pub name: &'a str,
pub version: &'a str,
pub about: &'a str,
pub commands: &'a [Command<'a>],
pub exit_status: &'a [(&'a str, &'a str)],
pub see_also: &'a [&'a str],
pub date: &'a str,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GenerateError {
InvalidName(String),
}
impl std::fmt::Display for GenerateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GenerateError::InvalidName(name) => write!(
f,
"`{name}` is not a plain name (letters, digits and `_ . -` only), so it cannot \
be written into a shell completion"
),
}
}
}
impl std::error::Error for GenerateError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Shell {
Bash,
Zsh,
Fish,
Nushell,
}
impl Shell {
pub const ALL: [Shell; 4] = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::Nushell];
pub const fn token(self) -> &'static str {
match self {
Shell::Bash => "bash",
Shell::Zsh => "zsh",
Shell::Fish => "fish",
Shell::Nushell => "nushell",
}
}
pub fn parse(token: &str) -> Option<Shell> {
match token {
"bash" => Some(Shell::Bash),
"zsh" => Some(Shell::Zsh),
"fish" => Some(Shell::Fish),
"nushell" | "nu" => Some(Shell::Nushell),
_ => None,
}
}
}
pub fn completions(
shell: Shell,
program: &Program<'_>,
records: &[Record],
) -> Result<String, GenerateError> {
match shell {
Shell::Bash => bash(program, records),
Shell::Zsh => zsh(program, records),
Shell::Fish => fish(program, records),
Shell::Nushell => nushell(program, records),
}
}
#[derive(Clone, Debug)]
pub(crate) struct Flag {
pub long: Option<String>,
pub short: Option<String>,
pub takes_value: bool,
pub value_name: String,
pub values: Vec<String>,
pub path: bool,
pub negatable: bool,
pub summary: String,
pub default: Option<String>,
pub env: Vec<String>,
pub group: String,
pub scope: Vec<String>,
}
impl Flag {
pub fn available_for(&self, command: &str) -> bool {
self.scope.is_empty() || self.scope.iter().any(|s| s == command)
}
pub fn spellings(&self) -> Vec<String> {
let mut out = Vec::new();
if let Some(s) = &self.short {
out.push(format!("-{s}"));
}
if let Some(l) = &self.long {
out.push(format!("--{l}"));
if self.negatable {
out.push(format!("--no-{l}"));
}
}
out
}
}
#[derive(Clone, Debug)]
pub(crate) struct Positional {
pub index: usize,
pub name: String,
pub values: Vec<String>,
pub path: bool,
pub required: bool,
pub summary: String,
pub scope: Vec<String>,
}
impl Positional {
pub fn available_for(&self, command: &str) -> bool {
self.scope.iter().any(|s| s == command)
}
}
pub(crate) fn is_plain(token: &str) -> bool {
!token.is_empty()
&& token.chars().all(|c| {
c.is_ascii_alphanumeric()
|| matches!(c, '_' | '.' | '-' | ':' | '/' | '+' | '=' | '@' | ',')
})
}
pub(crate) fn is_name(token: &str) -> bool {
is_plain(token) && !token.starts_with('-')
}
pub(crate) fn one_line(text: &str) -> String {
text.split(|c: char| c.is_whitespace() || c.is_control())
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
pub(crate) struct Model {
pub flags: Vec<Flag>,
pub positionals: Vec<Positional>,
}
pub(crate) fn model(records: &[Record]) -> Model {
let mut flags = Vec::new();
let mut positionals = Vec::new();
for record in records {
let Some(arg) = &record.arg else { continue };
let values: Vec<String> = if matches!(record.ty.as_str(), "enum" | "list") {
record
.allowed
.iter()
.filter(|v| is_plain(v))
.cloned()
.collect()
} else {
Vec::new()
};
let summary = one_line(record.summary.as_deref().unwrap_or(""));
let scope: Vec<String> = record
.subcommands
.iter()
.filter(|s| is_name(s))
.cloned()
.collect();
if let Some(position) = arg.position {
positionals.push(Positional {
index: usize::from(position),
name: arg
.value_name
.clone()
.filter(|n| is_plain(n))
.unwrap_or_else(|| record.key.to_uppercase()),
values,
path: record.ty == "path",
required: record.required,
summary,
scope,
});
continue;
}
let long = arg.long.clone().filter(|l| is_name(l));
let short = arg
.short
.clone()
.filter(|s| s.chars().count() == 1 && is_name(s));
if long.is_none() && short.is_none() {
continue;
}
flags.push(Flag {
long,
short,
takes_value: arg.arity > 0,
value_name: arg
.value_name
.clone()
.filter(|n| is_plain(n))
.unwrap_or_else(|| "VALUE".to_string()),
values,
path: record.ty == "path",
negatable: arg.negatable,
summary,
default: record.default.as_ref().and_then(|v| match v {
serde_json::Value::String(text) => Some(text.clone()),
serde_json::Value::Number(n) => Some(n.to_string()),
_ => None,
}),
env: record
.env_names()
.iter()
.filter(|n| is_plain(n))
.map(|n| (*n).to_string())
.collect(),
group: record
.group
.clone()
.unwrap_or_else(|| "options".to_string()),
scope,
});
}
positionals.sort_by_key(|p| p.index);
Model { flags, positionals }
}
pub(crate) fn commands<'a>(program: &Program<'a>) -> Result<Vec<Command<'a>>, GenerateError> {
if !is_name(program.name) {
return Err(GenerateError::InvalidName(program.name.to_string()));
}
program
.commands
.iter()
.map(|c| {
if is_name(c.name) {
Ok(*c)
} else {
Err(GenerateError::InvalidName(c.name.to_string()))
}
})
.collect()
}
pub(crate) fn identifier(name: &str) -> String {
name.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect()
}