diff --git a/quantumclient/shell.py b/quantumclient/shell.py index 5f5eccdc8..c4195ba5c 100644 --- a/quantumclient/shell.py +++ b/quantumclient/shell.py @@ -278,6 +278,24 @@ class QuantumShell(App): return parser + def _bash_completion(self): + """ + Prints all of the commands and options to stdout so that the + quantum's bash-completion script doesn't have to hard code them. + """ + commands = set() + options = set() + for option, _action in self.parser._option_string_actions.items(): + options.add(option) + for command_name, command in self.command_manager: + commands.add(command_name) + cmd_factory = command.load() + cmd = cmd_factory(self, None) + cmd_parser = cmd.get_parser('') + for option, _action in cmd_parser._option_string_actions.items(): + options.add(option) + print ' '.join(commands | options) + def run(self, argv): """Equivalent to the main program for the application. @@ -289,6 +307,9 @@ class QuantumShell(App): command_pos = -1 help_pos = -1 for arg in argv: + if arg == 'bash-completion': + self._bash_completion() + return 0 if arg in COMMANDS[self.api_version]: if command_pos == -1: command_pos = index diff --git a/tools/quantum.bash_completion b/tools/quantum.bash_completion new file mode 100644 index 000000000..45db025af --- /dev/null +++ b/tools/quantum.bash_completion @@ -0,0 +1,27 @@ +_quantum_opts="" # lazy init +_quantum_flags="" # lazy init +_quantum_opts_exp="" # lazy init +_quantum() +{ + local cur prev nbc cflags + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + prev="${COMP_WORDS[COMP_CWORD-1]}" + + if [ "x$_quantum_opts" == "x" ] ; then + nbc="`quantum bash-completion | sed -e "s/\s-h\s/\s/"`" + _quantum_opts="`echo "$nbc" | sed -e "s/--[a-z0-9_-]*//g" -e "s/\s\s*/ /g"`" + _quantum_flags="`echo " $nbc" | sed -e "s/ [^-][^-][a-z0-9_-]*//g" -e "s/\s\s*/ /g"`" + _quantum_opts_exp="`echo "$_quantum_opts" | sed -e "s/\s/|/g"`" + fi + + if [[ " ${COMP_WORDS[@]} " =~ " "($_quantum_opts_exp)" " && "$prev" != "help" ]] ; then + COMPLETION_CACHE=~/.quantumclient/*/*-cache + cflags="$_quantum_flags "$(cat $COMPLETION_CACHE 2> /dev/null | tr '\n' ' ') + COMPREPLY=($(compgen -W "${cflags}" -- ${cur})) + else + COMPREPLY=($(compgen -W "${_quantum_opts}" -- ${cur})) + fi + return 0 +} +complete -F _quantum quantum