use super::{asked_words, commands, identifier, model, GenerateError, Model, Program};
use crate::Record;
fn quote(text: &str) -> String {
format!("'{}'", text.replace('\'', "'\\''"))
}
pub fn bash(program: &Program<'_>, records: &[Record]) -> Result<String, GenerateError> {
let commands = commands(program)?;
let Model { flags, positionals } = model(records);
let name = program.name;
let function = format!("_{}", identifier(name));
let mut out = format!(
"# bash completion for {name} (generated by argenv; do not edit by hand)\n{function}() {{\n local cur prev cmd cmd_index i\n cur=\"${{COMP_WORDS[COMP_CWORD]}}\"\n prev=\"\"\n [[ $COMP_CWORD -gt 0 ]] && prev=\"${{COMP_WORDS[COMP_CWORD-1]}}\"\n # `--flag=value`: bash splits at `=`, so the flag is two words back.\n if [[ \"$prev\" == \"=\" ]]; then\n prev=\"${{COMP_WORDS[COMP_CWORD-2]}}\"\n elif [[ \"$cur\" == \"=\" ]]; then\n cur=\"\"\n fi\n"
);
out.push_str(" cmd=\"\"\n cmd_index=0\n");
if !commands.is_empty() {
let names = commands
.iter()
.map(|c| c.name)
.collect::<Vec<_>>()
.join("|");
out.push_str(&format!(
" for ((i = 1; i < COMP_CWORD; i++)); do\n case \"${{COMP_WORDS[i]}}\" in\n {names}) cmd=\"${{COMP_WORDS[i]}}\"; cmd_index=$i; break ;;\n esac\n done\n"
));
}
let mut value_arms = String::new();
let mut value_flags: Vec<String> = Vec::new();
for flag in flags.iter().filter(|f| f.takes_value) {
let pattern = flag
.spellings()
.iter()
.flat_map(|spelling| {
if flag.scope.is_empty() {
vec![format!("*:{spelling}")]
} else {
flag.scope
.iter()
.map(|command| format!("{command}:{spelling}"))
.collect()
}
})
.collect::<Vec<_>>()
.join("|");
value_flags.extend(flag.spellings());
if !flag.values.is_empty() {
value_arms.push_str(&format!(
" {pattern}) COMPREPLY=( $(compgen -W {} -- \"$cur\") ); return 0 ;;\n",
quote(&flag.values.join(" "))
));
} else if flag.path {
value_arms.push_str(&format!(
" {pattern}) compopt -o filenames 2>/dev/null; COMPREPLY=( $(compgen -f -- \"$cur\") ); return 0 ;;\n"
));
} else {
value_arms.push_str(&format!(" {pattern}) COMPREPLY=(); return 0 ;;\n"));
}
}
if !value_arms.is_empty() {
out.push_str(&format!(
" case \"$cmd:$prev\" in\n{value_arms} esac\n"
));
}
let words = |command: Option<&str>| -> String {
flags
.iter()
.filter(|f| match command {
Some(c) => f.available_for(c),
None => f.scope.is_empty(),
})
.flat_map(|f| f.spellings())
.collect::<Vec<_>>()
.join(" ")
};
out.push_str(" local flags\n case \"$cmd\" in\n");
for command in &commands {
out.push_str(&format!(
" {}) flags={} ;;\n",
command.name,
quote(&words(Some(command.name)))
));
}
out.push_str(&format!(
" *) flags={} ;;\n esac\n",
quote(&words(None))
));
out.push_str(" if [[ \"$cur\" == -* ]]; then\n COMPREPLY=( $(compgen -W \"$flags\" -- \"$cur\") )\n return 0\n fi\n");
if !commands.is_empty() {
let names = commands
.iter()
.map(|c| c.name)
.collect::<Vec<_>>()
.join(" ");
out.push_str(&format!(
" if [[ -z \"$cmd\" ]]; then\n COMPREPLY=( $(compgen -W {} -- \"$cur\") )\n return 0\n fi\n",
quote(&names)
));
}
let mut positional_arms = String::new();
for positional in &positionals {
for command in commands.iter().filter(|c| positional.available_for(c.name)) {
let arm = if let Some(words) = asked_words(program, command.name, positional.index) {
let line = words.iter().map(|w| quote(w)).collect::<Vec<_>>().join(" ");
format!("COMPREPLY=( $(compgen -W \"$({line} 2>/dev/null)\" -- \"$cur\") )")
} else if !positional.values.is_empty() {
format!(
"COMPREPLY=( $(compgen -W {} -- \"$cur\") )",
quote(&positional.values.join(" "))
)
} else if positional.path {
"compopt -o filenames 2>/dev/null; COMPREPLY=( $(compgen -f -- \"$cur\") )"
.to_string()
} else {
continue;
};
positional_arms.push_str(&format!(
" {}:{}) {arm} ;;\n",
command.name, positional.index
));
}
}
if !positional_arms.is_empty() {
out.push_str(" local pos=0 skip=0 w\n for ((i = cmd_index + 1; i < COMP_CWORD; i++)); do\n w=\"${COMP_WORDS[i]}\"\n if [[ $skip -eq 1 ]]; then skip=0; continue; fi\n case \"$w\" in\n");
if !value_flags.is_empty() {
out.push_str(&format!(
" {}) skip=1 ;;\n",
value_flags.join("|")
));
}
out.push_str(" -*) ;;\n *) pos=$((pos + 1)) ;;\n esac\n done\n case \"$cmd:$pos\" in\n");
out.push_str(&positional_arms);
out.push_str(" esac\n");
}
out.push_str(&format!(
" return 0\n}}\ncomplete -F {function} {name}\n"
));
Ok(out)
}