use crate::case::ToSnakeCase;
use crate::complete::CompleteOptions;
pub fn complete_bash(opts: &CompleteOptions) -> String {
let usage_bin = &opts.usage_bin;
let bin = &opts.bin;
let bin_snake = bin.to_snake_case();
let spec_variable = if let Some(cache_key) = &opts.cache_key {
format!("_usage_spec_{bin_snake}_{}", cache_key.to_snake_case())
} else {
format!("_usage_spec_{bin_snake}")
};
let mut out = vec![];
let generated_comment = if let Some(source_file) = &opts.source_file {
format!("# @generated by usage-cli from {source_file}")
} else {
"# @generated by usage-cli from usage spec".to_string()
};
out.push(generated_comment);
out.push(
"# Requires bash-completion (https://github.com/scop/bash-completion), which must be\n\
# sourced before this script."
.to_string(),
);
out.push(format!(
r#"_{bin_snake}() {{
if ! type -P {usage_bin} &> /dev/null; then
echo >&2
echo "Error: {usage_bin} CLI not found. This is required for completions to work in {bin}." >&2
echo "See https://usage.jdx.dev for more information." >&2
return 1
fi
if ! declare -F _init_completion > /dev/null 2>&1; then
echo >&2
echo "Error: bash-completion is required for {bin} completions but was not loaded." >&2
echo "Install it from your package manager and source it before this script." >&2
return 1
fi"#));
let prune_stale = format!(
r#"find "$spec_dir" -maxdepth 1 -name 'usage__usage_spec_{bin_snake}_*.spec' -type f -mtime +30 -delete 2>/dev/null"#
);
let file_write_logic = if let Some(usage_cmd) = &opts.usage_cmd {
if opts.cache_key.is_some() {
format!(
r#"if [[ ! -f "$spec_file" ]]; then
{prune_stale}
{usage_cmd} >| "$spec_file"
fi"#
)
} else {
format!(r#"{usage_cmd} >| "$spec_file""#)
}
} else if let Some(spec) = &opts.spec {
let heredoc = format!(
r#"cat >| "$spec_file" <<'__USAGE_EOF__'
{spec}
__USAGE_EOF__"#,
spec = spec.to_string().trim()
);
if opts.cache_key.is_some() {
format!(
r#"if [[ ! -f "$spec_file" ]]; then
{prune_stale}
{heredoc}
fi"#
)
} else {
heredoc.to_string()
}
} else {
String::new()
};
out.push(format!(
r#"
local cur prev words cword comp_args
# `=` and `:` stay inside the word so complete-word sees `--out=a` as one word
# rather than `--out`, `=`, `a`.
_init_completion -n := -- "$@" || return
local spec_dir="${{XDG_CACHE_HOME:-$HOME/.cache}}/usage"
[[ -d "$spec_dir" ]] || mkdir -p -m 700 "$spec_dir"
local spec_file="$spec_dir/usage_{spec_variable}.spec"
{file_write_logic}
# stderr is discarded: a line that doesn't parse (`{bin} help <Tab>`) makes
# complete-word fail, and its error would be printed over the prompt.
# Complete the text before the cursor, as `$cur` holds it: with the cursor in `--out=a|X`
# the value typed so far is `a`, not `aX`.
words[cword]="$cur"
# shellcheck disable=SC2207
COMPREPLY=($(compgen -W "$(command {usage_bin} complete-word --shell bash -f "$spec_file" --cword="$cword" -- "${{words[@]}}" 2>/dev/null)" -- "$cur"))
# Readline only replaces the text after the last word break, so strip the part of
# `$cur` up to its last `:` or `=` from each candidate (what __ltrim_colon_completions
# does for `:` alone).
local breaks="${{COMP_WORDBREAKS//[^:=]/}}"
# An empty COMPREPLY is left alone: before bash 4.4 the rewrite below would turn it into
# one empty candidate.
if ((${{#COMPREPLY[@]}})) && [[ -n "$breaks" && "$cur" == *["$breaks"]* ]]; then
local break_prefix="${{cur%"${{cur##*["$breaks"]}}"}}"
COMPREPLY=("${{COMPREPLY[@]#"$break_prefix"}}")
fi
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
unset COMPREPLY
fi
return 0
}}
if [[ "${{BASH_VERSINFO[0]}}" -eq 4 && "${{BASH_VERSINFO[1]}}" -ge 4 || "${{BASH_VERSINFO[0]}}" -gt 4 ]]; then
shopt -u hostcomplete && complete -o nospace -o bashdefault -o nosort -F _{bin_snake} {bin}
else
shopt -u hostcomplete && complete -o nospace -o bashdefault -F _{bin_snake} {bin}
fi
# vim: noet ci pi sts=0 sw=4 ts=4 ft=sh
"#
));
out.join("\n")
}
pub fn complete_bash_init(usage_bin: &str) -> String {
format!(
r##"# @generated by usage-cli — auto-completion for usage shebang scripts
# Source this file from your bashrc to enable <Tab> completion for any command
# on $PATH whose first line is a `usage` shebang.
#
# Sourcing order: this script registers a `complete -D` default handler. Bash
# only allows one such handler — whichever script registers last wins. Source
# this AFTER bash-completion (e.g. `/etc/bash_completion` or
# `/usr/share/bash-completion/bash_completion`) so that bash-completion's own
# default handler is captured below and chained to for non-usage commands.
# Capture any pre-existing `complete -D` handler so we can chain to it for
# commands that aren't usage shebang scripts (e.g. bash-completion's loader).
# `complete -p -D` exits non-zero if no -D handler is set; tolerate that under
# `set -e`.
_usage_chained_default_complete=""
{{
_usage_existing_d="$(complete -p -D 2>/dev/null || true)"
if [[ "$_usage_existing_d" =~ -F[[:space:]]+([^[:space:]]+) ]]; then
_usage_chained_default_complete="${{BASH_REMATCH[1]}}"
fi
unset _usage_existing_d
}}
_usage_default_complete() {{
local cmd="${{COMP_WORDS[0]}}"
local cmdpath
if [[ "$cmd" == */* ]]; then
cmdpath="$cmd"
else
cmdpath="$(type -P "$cmd" 2>/dev/null)"
fi
if [[ -n "$cmdpath" && -f "$cmdpath" ]]; then
local first
if IFS= read -r first < "$cmdpath" 2>/dev/null && [[ "$first" == "#!"*"usage"* ]]; then
if type -P {usage_bin} &> /dev/null; then
# Bash splits `--out=a` into `--out`, `=`, `a` (`=` is in COMP_WORDBREAKS).
# Join those back into one word, using COMP_LINE to tell `--out=a` apart
# from `--out = a`, so complete-word sees the word that was typed. The whole
# line is walked, not just up to the cursor, so words after it stay apart;
# `ends` records where each joined word stops so the current one can then be
# cut at the cursor.
local words=() ends=() cword=0 i line="$COMP_LINE" word spaced
for ((i = 0; i < ${{#COMP_WORDS[@]}}; i++)); do
word="${{COMP_WORDS[i]}}"
spaced=1
[[ "$line" == [[:space:]]* ]] || spaced=0
line="${{line#"${{line%%[![:space:]]*}}"}}"
line="${{line#"$word"}}"
if ((i > 0 && !spaced)) && [[ -n "$word" ]] \
&& [[ "$word" == =* || "${{words[${{#words[@]}} - 1]}}" == *= ]]; then
words[${{#words[@]}} - 1]+="$word"
else
words+=("$word")
fi
ends[${{#words[@]}} - 1]=$((${{#COMP_LINE}} - ${{#line}}))
((i == COMP_CWORD)) && cword=$((${{#words[@]}} - 1))
done
# With the cursor in `--out=a|X`, the value typed so far is `a`, not `aX`.
local after=$((${{ends[cword]:-0}} - COMP_POINT))
if ((after > 0 && after <= ${{#words[cword]}})); then
words[cword]="${{words[cword]:0:${{#words[cword]}} - after}}"
fi
local cur="${{words[cword]}}"
local IFS=$'\n'
# stderr is discarded so a parse error isn't printed over the prompt.
# shellcheck disable=SC2207
COMPREPLY=( $(command {usage_bin} complete-word --shell bash -f "$cmdpath" --cword="$cword" -- "${{words[@]}}" 2>/dev/null) )
# Readline only replaces the text after the last `=`, so drop what precedes it.
# Guarded on a non-empty COMPREPLY: before bash 4.4, rewriting an empty array
# this way leaves one empty candidate, which would erase the typed value.
if ((${{#COMPREPLY[@]}})) && [[ "$cur" == *=* && "$COMP_WORDBREAKS" == *=* ]]; then
COMPREPLY=( "${{COMPREPLY[@]#"${{cur%"${{cur##*=}}"}}"}}" )
fi
return 0
fi
fi
fi
# Chain to whatever default handler was registered before us, if any.
if [[ -n "$_usage_chained_default_complete" ]] \
&& [[ "$_usage_chained_default_complete" != "_usage_default_complete" ]] \
&& declare -F "$_usage_chained_default_complete" >/dev/null 2>&1; then
"$_usage_chained_default_complete" "$@"
return $?
fi
if declare -F _completion_loader >/dev/null 2>&1; then
_completion_loader "$@"
return $?
fi
return 1
}}
complete -D -F _usage_default_complete -o bashdefault -o default
# vim: noet ci pi sts=0 sw=4 ts=4 ft=sh
"##
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::SPEC_KITCHEN_SINK;
use insta::assert_snapshot;
#[test]
fn test_complete_bash_init() {
assert_snapshot!(complete_bash_init("usage"));
}
#[test]
fn test_complete_bash() {
assert_snapshot!(complete_bash(&CompleteOptions {
usage_bin: "usage".to_string(),
shell: "bash".to_string(),
bin: "mycli".to_string(),
cache_key: None,
spec: None,
usage_cmd: Some("mycli complete --usage".to_string()),
source_file: None,
}));
assert_snapshot!(complete_bash(&CompleteOptions {
usage_bin: "usage".to_string(),
shell: "bash".to_string(),
bin: "mycli".to_string(),
cache_key: Some("1.2.3".to_string()),
spec: None,
usage_cmd: Some("mycli complete --usage".to_string()),
source_file: None,
}));
assert_snapshot!(complete_bash(&CompleteOptions {
usage_bin: "usage".to_string(),
shell: "bash".to_string(),
bin: "mycli".to_string(),
cache_key: None,
spec: Some(SPEC_KITCHEN_SINK.clone()),
usage_cmd: None,
source_file: None,
}));
}
}