Supports bash_completion for heatclient

bash_completion feature can improve CLI user experience, projects like
nova, keystone, and cinder already support it.

NOTE: this patch just provides simple functionality, which means cache
for IDs and names is not used (like nova).

Closes-Bug: #1260939
Change-Id: I327e884e1c5907c9ff6f31131c70aee659cca58e
This commit is contained in:
ZhiQiang Fan
2013-12-14 16:33:29 +08:00
parent 619995a3b5
commit 992d6f5350
2 changed files with 56 additions and 0 deletions

View File

@@ -199,9 +199,19 @@ class HeatShell(object):
submodule = utils.import_versioned_module(version, 'shell')
self._find_actions(subparsers, submodule)
self._find_actions(subparsers, self)
self._add_bash_completion_subparser(subparsers)
return parser
def _add_bash_completion_subparser(self, subparsers):
subparser = subparsers.add_parser(
'bash_completion',
add_help=False,
formatter_class=HelpFormatter
)
self.subcommands['bash_completion'] = subparser
subparser.set_defaults(func=self.do_bash_completion)
def _find_actions(self, subparsers, actions_module):
for attr in (a for a in dir(actions_module) if a.startswith('do_')):
# I prefer to be hypen-separated instead of underscores.
@@ -299,6 +309,9 @@ class HeatShell(object):
if args.func == self.do_help:
self.do_help(args)
return 0
elif args.func == self.do_bash_completion:
self.do_bash_completion(args)
return 0
if not args.os_username and not args.os_auth_token:
raise exc.CommandError("You must provide a username via"
@@ -374,6 +387,22 @@ class HeatShell(object):
args.func(client, args)
def do_bash_completion(self, args):
"""Prints all of the commands and options to stdout.
The heat.bash_completion script doesn't have to hard code them.
"""
commands = set()
options = set()
for sc_str, sc in self.subcommands.items():
commands.add(sc_str)
for option in list(sc._optionals._option_string_actions):
options.add(option)
commands.remove('bash-completion')
commands.remove('bash_completion')
print(' '.join(commands | options))
@utils.arg('command', metavar='<subcommand>', nargs='?',
help='Display help for <subcommand>')
def do_help(self, args):

View File

@@ -0,0 +1,27 @@
# bash completion for openstack heat
_heat_opts="" # lazy init
_heat_flags="" # lazy init
_heat_opts_exp="" # lazy init
_heat()
{
local cur prev kbc
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
if [ "x$_heat_opts" == "x" ] ; then
kbc="`heat bash-completion | sed -e "s/ -h / /"`"
_heat_opts="`echo "$kbc" | sed -e "s/--[a-z0-9_-]*//g" -e "s/[ ][ ]*/ /g"`"
_heat_flags="`echo " $kbc" | sed -e "s/ [^-][^-][a-z0-9_-]*//g" -e "s/[ ][ ]*/ /g"`"
_heat_opts_exp="`echo $_heat_opts | sed -e "s/[ ]/|/g"`"
fi
if [[ " ${COMP_WORDS[@]} " =~ " "($_heat_opts_exp)" " && "$prev" != "help" ]] ; then
COMPREPLY=($(compgen -W "${_heat_flags}" -- ${cur}))
else
COMPREPLY=($(compgen -W "${_heat_opts}" -- ${cur}))
fi
return 0
}
complete -F _heat heat