Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,14 @@ gem install deploio-cli

## Shell Completion

Enable autocompletion by adding this to your `~/.zshrc` or `~/.bashrc`, or whatever you use:
Enable autocompletion by adding the line for your shell to its rc file:

```bash
# ~/.zshrc
eval "$(deploio completion)"

# ~/.bashrc
eval "$(deploio completion --shell bash)"
```

After setup, completions work for:
Expand Down Expand Up @@ -108,7 +112,8 @@ EXECUTION
deploio run -a APP -- CMD Alias for exec

OTHER
deploio completion Generate shell completion script
deploio completion Generate zsh completion script
deploio completion -s bash Generate bash completion script
deploio version Show version

FLAGS
Expand Down Expand Up @@ -231,7 +236,8 @@ export PATH="$PWD/bin:$PATH"
to have the `deploio` command binded to the current one, and

```shell
eval "$(deploio completion)"
eval "$(deploio completion)" # zsh
eval "$(deploio completion --shell bash)" # bash
```

to refresh the autocompletion options.
Expand Down
4 changes: 4 additions & 0 deletions deploio-cli.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ Gem::Specification.new do |spec|

eval "$(deploio completion)"

or this to your ~/.bashrc:

eval "$(deploio completion --shell bash)"

MSG

spec.files = Dir.chdir(__dir__) do
Expand Down
97 changes: 97 additions & 0 deletions lib/deploio/bash_completion_generator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# frozen_string_literal: true

require_relative "completion_generator"

module Deploio
# Generates bash completion script from Thor command metadata.
# Completers are shell commands printing the candidates.
#
# @example With custom option completers
# BashCompletionGenerator.new(MyCLI, option_completers: {
# 'env' => 'echo production staging development'
# }).generate
#
class BashCompletionGenerator < CompletionGenerator
TEMPLATE_PATH = File.expand_path("templates/completion.bash.erb", __dir__)

ROOT_OPTIONS = {version: Thor::Option.new(:version, type: :boolean, aliases: "-v")}.freeze

# A command path ("" is the root, "pg:backups" a nested subcommand)
# with the candidates that can follow it.
Context = Struct.new(:path, :commands, :options, :positional, :passthrough, keyword_init: true)

private

def default_option_completers
{
"app" => "_#{program_name}_apps_list",
"size" => "echo micro mini standard",
"project" => "_#{program_name}_projects_list"
}
end

def default_positional_completers
{
"orgs:set" => "_#{program_name}_orgs_list",
"pg:info" => "_#{program_name}_pg_databases_list",
"pg:backups:capture" => "_#{program_name}_pg_databases_list",
"pg:backups:list" => "_#{program_name}_pg_databases_list",
"pg:backups:download" => "_#{program_name}_pg_databases_list"
}
end

def contexts
@contexts ||= [
Context.new(path: "", commands: main_commands.map(&:first), options: ROOT_OPTIONS),
*direct_commands.map { |name, options| leaf_context(name, all_options(options)) },
*passthrough_commands.map { |name, options| leaf_context(name, all_options(options), passthrough: true) },
*subcommands.flat_map do |name, commands, class_options, default_task, klass|
group_contexts(name, commands, class_options, default_task, klass.subcommand_classes)
end,
*nested_subcommands.flat_map do |name, commands, class_options|
group_contexts(name, commands, class_options)
end
]
end

def group_contexts(name, commands, class_options, default_task = nil, nested = {})
default_options = commands.find { |cmd_name, _, _| cmd_name == default_task }&.last || {}
group = Context.new(path: name, commands: commands.map(&:first),
options: all_options(default_options, class_options))

leaves = commands.reject { |cmd_name, _, _| nested.key?(cmd_name) }.map do |cmd_name, _, options|
leaf_context("#{name}:#{cmd_name}", all_options(options, class_options))
end

[group, *leaves]
end

def leaf_context(path, options, passthrough: false)
Context.new(path: path, commands: [], options: options,
positional: positional_completers[path], passthrough: passthrough)
end

def all_options(method_options, class_options = {})
cli_class_options.merge(class_options).merge(method_options)
end

def flags(context)
context.options.flat_map { |name, opt| option_flags(name, opt) }.uniq
end

def value_flags(context)
context.options.reject { |_, opt| opt.type == :boolean }.flat_map { |name, opt| option_flags(name, opt) }.uniq
end

def option_value_completers
contexts.flat_map { |context| context.options.to_a }.uniq(&:first).filter_map do |name, opt|
completer = option_completers[name.to_s]
[option_flags(name, opt), completer] if completer
end
end

def option_flags(name, opt)
["--#{name.to_s.tr("_", "-")}", *opt.aliases]
end
end
end
9 changes: 6 additions & 3 deletions lib/deploio/cli.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
require_relative "commands/postgresql_backups"
require_relative "commands/postgresql"
require_relative "completion_generator"
require_relative "bash_completion_generator"

module Deploio
class CLI < Thor
Expand All @@ -28,11 +29,13 @@ def completion
case options[:shell].downcase
when "zsh"
puts CompletionGenerator.new.generate
when "bash", "fish"
Output.error("#{options[:shell]} completion is not yet supported. Only zsh is available.")
when "bash"
puts BashCompletionGenerator.new.generate
when "fish"
Output.error("#{options[:shell]} completion is not yet supported. Only zsh and bash are available.")
exit 1
else
Output.error("Unknown shell: #{options[:shell]}. Supported: zsh")
Output.error("Unknown shell: #{options[:shell]}. Supported: zsh, bash")
exit 1
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/deploio/completion_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def initialize(cli_class = nil, option_completers: {}, positional_completers: {}
end

def generate
template = File.read(TEMPLATE_PATH)
template = File.read(self.class::TEMPLATE_PATH)
ERB.new(template, trim_mode: "-").result(binding)
end

Expand Down
140 changes: 140 additions & 0 deletions lib/deploio/templates/completion.bash.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Bash completion for <%= program_name %>-cli
# Auto-generated from Thor command definitions
# Enable with: eval "$(<%= program_name %> completion --shell bash)"

# Dynamic completion for organizations
_<%= program_name %>_orgs_list() {
<%= program_name %> orgs --json 2>/dev/null | ruby -rjson -e '
data = JSON.parse(STDIN.read) rescue []
data.each { |o| puts o["name"] }
' 2>/dev/null
}

# Dynamic completion for projects
_<%= program_name %>_projects_list() {
<%= program_name %> projects --json 2>/dev/null | ruby -rjson -e '
data = JSON.parse(STDIN.read) rescue []
orgs_json = `<%= program_name %> orgs --json 2>/dev/null` rescue "[]"
orgs = JSON.parse(orgs_json) rescue []
current_org = orgs.find { |o| o["current"] }&.fetch("name", nil)

data.each do |p|
name = p.dig("metadata", "name") || ""
short_name = current_org && name.start_with?("#{current_org}-") ? name.delete_prefix("#{current_org}-") : name
puts short_name
end
' 2>/dev/null
}

# Dynamic completion for apps
_<%= program_name %>_apps_list() {
<%= program_name %> apps --json 2>/dev/null | ruby -rjson -e '
data = JSON.parse(STDIN.read) rescue []
orgs_json = `<%= program_name %> orgs --json 2>/dev/null` rescue "[]"
orgs = JSON.parse(orgs_json) rescue []
current_org = orgs.find { |o| o["current"] }&.fetch("name", nil)

data.each do |a|
ns = a.dig("metadata", "namespace") || ""
name = a.dig("metadata", "name") || ""
project = current_org && ns.start_with?("#{current_org}-") ? ns.delete_prefix("#{current_org}-") : ns
puts "#{project}-#{name}"
end
' 2>/dev/null
}

# Dynamic completion for PostgreSQL databases
_<%= program_name %>_pg_databases_list() {
<%= program_name %> pg list --json 2>/dev/null | ruby -rjson -e '
data = JSON.parse(STDIN.read) rescue []
orgs_json = `<%= program_name %> orgs --json 2>/dev/null` rescue "[]"
orgs = JSON.parse(orgs_json) rescue []
current_org = orgs.find { |o| o["current"] }&.fetch("name", nil)

data.each do |db|
ns = db.dig("metadata", "namespace") || ""
name = db.dig("metadata", "name") || ""
project = current_org && ns.start_with?("#{current_org}-") ? ns.delete_prefix("#{current_org}-") : ns
puts "#{project}-#{name}"
end
' 2>/dev/null
}

# Sets the candidates following a command path in the caller's scope
_<%= program_name %>_context() {
commands="" flags="" value_flags="" positional="" passthrough=""
case "$1" in
<% contexts.each do |context| -%>
"<%= context.path %>")
<% unless context.commands.empty? -%>
commands="<%= context.commands.join(" ") %>"
<% end -%>
flags="<%= flags(context).join(" ") %>"
<% unless value_flags(context).empty? -%>
value_flags="<%= value_flags(context).join(" ") %>"
<% end -%>
<% if context.positional -%>
positional="<%= context.positional %>"
<% end -%>
<% if context.passthrough -%>
passthrough=1
<% end -%>
;;
<% end -%>
esac
}

_<%= program_name %>_option_values() {
case "$1" in
<% option_value_completers.each do |flags, completer| -%>
<%= flags.join("|") %>) <%= completer %> ;;
<% end -%>
esac
}

_<%= program_name %>_includes() {
[[ -n "$2" && " $1 " == *" $2 "* ]]
}

# Main completion function
_<%= program_name %>() {
local cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}"
local cmd="" args=0 word i
local commands flags value_flags positional passthrough
COMPREPLY=()

_<%= program_name %>_context ""
for ((i = 1; i < COMP_CWORD; i++)); do
word="${COMP_WORDS[i]}"
if [[ "$word" == "--" && -n "$passthrough" ]]; then
if ((i + 1 == COMP_CWORD)); then
COMPREPLY=($(compgen -c -- "$cur"))
else
COMPREPLY=($(compgen -f -- "$cur"))
fi
return
elif _<%= program_name %>_includes "$value_flags" "$word"; then
((++i))
elif [[ "$word" == -* ]]; then
continue
elif ((args == 0)) && _<%= program_name %>_includes "$commands" "$word"; then
cmd="${cmd:+$cmd:}$word"
_<%= program_name %>_context "$cmd"
else
((++args))
fi
done

if _<%= program_name %>_includes "$value_flags" "$prev"; then
COMPREPLY=($(compgen -W "$(_<%= program_name %>_option_values "$prev")" -- "$cur"))
elif [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "$flags" -- "$cur"))
elif ((args == 0)) && [[ -n "$commands" ]]; then
COMPREPLY=($(compgen -W "$commands" -- "$cur"))
elif ((args == 0)) && [[ -n "$positional" ]]; then
COMPREPLY=($(compgen -W "$($positional)" -- "$cur"))
fi
}

# Register the completion function
complete -F _<%= program_name %> <%= program_name %> depl
Loading
Loading