4 # Copyright (C) 2009 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 """Script to generate bash_completion script for Ganeti.
26 # pylint: disable-msg=C0103
27 # [C0103] Invalid name build-bash-completion
31 from cStringIO import StringIO
33 from ganeti import constants
34 from ganeti import cli
35 from ganeti import utils
36 from ganeti import build
38 # _autoconf shouldn't be imported from anywhere except constants.py, but we're
39 # making an exception here because this script is only used at build time.
40 from ganeti import _autoconf
44 """Helper class to write scripts with indentation.
49 def __init__(self, fh):
54 """Increase indentation level by 1.
60 """Decrease indentation level by 1.
63 assert self._indent > 0
66 def Write(self, txt, *args):
67 """Write line to output file.
70 self._fh.write(self._indent * self.INDENT_STR)
73 self._fh.write(txt % args)
80 def WritePreamble(sw):
81 """Writes the script preamble.
83 Helper functions should be written here.
86 sw.Write("# This script is automatically generated at build time.")
87 sw.Write("# Do not modify manually.")
89 sw.Write("_ganeti_dbglog() {")
92 sw.Write("if [[ -n \"$GANETI_COMPL_LOG\" ]]; then")
99 sw.Write("echo \"$@\"")
103 sw.Write("} >> $GANETI_COMPL_LOG")
111 sw.Write("_ganeti_nodes() {")
114 node_list_path = os.path.join(constants.DATA_DIR, "ssconf_node_list")
115 sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(node_list_path))
120 sw.Write("_ganeti_instances() {")
123 instance_list_path = os.path.join(constants.DATA_DIR,
124 "ssconf_instance_list")
125 sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(instance_list_path))
130 sw.Write("_ganeti_jobs() {")
133 # FIXME: this is really going into the internals of the job queue
134 sw.Write(("local jlist=$( shopt -s nullglob &&"
135 " cd %s 2>/dev/null && echo job-* || : )"),
136 utils.ShellQuote(constants.QUEUE_DIR))
137 sw.Write('echo "${jlist//job-/}"')
142 for (fnname, paths) in [
143 ("os", constants.OS_SEARCH_PATH),
144 ("iallocator", constants.IALLOCATOR_SEARCH_PATH),
146 sw.Write("_ganeti_%s() {", fnname)
149 # FIXME: Make querying the master for all OSes cheap
151 sw.Write("( shopt -s nullglob && cd %s 2>/dev/null && echo * || : )",
152 utils.ShellQuote(path))
157 # Params: <offset> <options with values> <options without values>
158 # Result variable: $first_arg_idx
159 sw.Write("_ganeti_find_first_arg() {")
162 sw.Write("local w i")
164 sw.Write("first_arg_idx=")
165 sw.Write("for (( i=$1; i < COMP_CWORD; ++i )); do")
168 sw.Write("w=${COMP_WORDS[$i]}")
171 sw.Write("""if [[ -n "$2" && "$w" == @($2) ]]; then let ++i""")
174 sw.Write("""elif [[ -n "$3" && "$w" == @($3) ]]; then :""")
176 # Ah, we found the first argument
177 sw.Write("else first_arg_idx=$i; break;")
186 # Params: <list of options separated by space>
187 # Input variable: $first_arg_idx
188 # Result variables: $arg_idx, $choices
189 sw.Write("_ganeti_list_options() {")
192 sw.Write("""if [[ -z "$first_arg_idx" ]]; then""")
195 sw.Write("arg_idx=0")
196 # Show options only if the current word starts with a dash
197 sw.Write("""if [[ "$cur" == -* ]]; then""")
200 sw.Write("choices=$1")
209 # Calculate position of current argument
210 sw.Write("arg_idx=$(( COMP_CWORD - first_arg_idx ))")
216 # Params: <long options with equal sign> <all options>
217 # Result variable: $optcur
218 sw.Write("_ganeti_checkopt() {")
221 sw.Write("""if [[ -n "$1" && "$cur" == @($1) ]]; then""")
224 sw.Write("optcur=\"${cur#--*=}\"")
228 sw.Write("""elif [[ -n "$2" && "$prev" == @($2) ]]; then""")
231 sw.Write("optcur=\"$cur\"")
237 sw.Write("_ganeti_dbglog optcur=\"'$optcur'\"")
244 # Params: <compgen options>
245 # Result variable: $COMPREPLY
246 sw.Write("_ganeti_compgen() {")
249 sw.Write("""COMPREPLY=( $(compgen "$@") )""")
250 sw.Write("_ganeti_dbglog COMPREPLY=\"${COMPREPLY[@]}\"")
256 def WriteCompReply(sw, args, cur="\"$cur\""):
257 sw.Write("_ganeti_compgen %s -- %s", args, cur)
261 class CompletionWriter:
262 """Command completion writer class.
265 def __init__(self, arg_offset, opts, args):
266 self.arg_offset = arg_offset
271 # While documented, these variables aren't seen as public attributes by
272 # pylint. pylint: disable-msg=W0212
273 opt.all_names = sorted(opt._short_opts + opt._long_opts)
275 def _FindFirstArgument(self, sw):
279 for opt in self.opts:
280 if opt.takes_value():
282 for i in opt.all_names:
283 if i.startswith("--"):
284 ignore.append("%s=*" % utils.ShellQuote(i))
285 skip_one.append(utils.ShellQuote(i))
287 ignore.extend([utils.ShellQuote(i) for i in opt.all_names])
289 ignore = sorted(utils.UniqueSequence(ignore))
290 skip_one = sorted(utils.UniqueSequence(skip_one))
292 if ignore or skip_one:
293 # Try to locate first argument
294 sw.Write("_ganeti_find_first_arg %s %s %s",
296 utils.ShellQuote("|".join(skip_one)),
297 utils.ShellQuote("|".join(ignore)))
299 # When there are no options the first argument is always at position
301 sw.Write("first_arg_idx=%s", self.arg_offset + 1)
303 def _CompleteOptionValues(self, sw):
305 # "values" -> [optname1, optname2, ...]
308 for opt in self.opts:
309 if not opt.takes_value():
312 # Only static choices implemented so far (e.g. no node list)
313 suggest = getattr(opt, "completion_suggest", None)
316 suggest = opt.choices
318 if (isinstance(suggest, (int, long)) and
319 suggest in cli.OPT_COMPL_ALL):
322 key = " ".join(sorted(suggest))
326 values.setdefault(key, []).extend(opt.all_names)
328 # Don't write any code if there are no option values
336 for (suggest, allnames) in values.iteritems():
337 longnames = [i for i in allnames if i.startswith("--")]
344 sw.Write("%s _ganeti_checkopt %s %s; then", condcmd,
345 utils.ShellQuote("|".join(["%s=*" % i for i in longnames])),
346 utils.ShellQuote("|".join(allnames)))
349 if suggest == cli.OPT_COMPL_MANY_NODES:
350 # TODO: Implement comma-separated values
351 WriteCompReply(sw, "-W ''", cur=cur)
352 elif suggest == cli.OPT_COMPL_ONE_NODE:
353 WriteCompReply(sw, "-W \"$(_ganeti_nodes)\"", cur=cur)
354 elif suggest == cli.OPT_COMPL_ONE_INSTANCE:
355 WriteCompReply(sw, "-W \"$(_ganeti_instances)\"", cur=cur)
356 elif suggest == cli.OPT_COMPL_ONE_OS:
357 WriteCompReply(sw, "-W \"$(_ganeti_os)\"", cur=cur)
358 elif suggest == cli.OPT_COMPL_ONE_IALLOCATOR:
359 WriteCompReply(sw, "-W \"$(_ganeti_iallocator)\"", cur=cur)
360 elif suggest == cli.OPT_COMPL_INST_ADD_NODES:
361 sw.Write("local tmp= node1= pfx= curvalue=\"${optcur#*:}\"")
363 sw.Write("if [[ \"$optcur\" == *:* ]]; then")
366 sw.Write("node1=\"${optcur%%:*}\"")
368 sw.Write("if [[ \"$COMP_WORDBREAKS\" != *:* ]]; then")
371 sw.Write("pfx=\"$node1:\"")
379 sw.Write("_ganeti_dbglog pfx=\"'$pfx'\" curvalue=\"'$curvalue'\""
380 " node1=\"'$node1'\"")
382 sw.Write("for i in $(_ganeti_nodes); do")
385 sw.Write("if [[ -z \"$node1\" ]]; then")
388 sw.Write("tmp=\"$tmp $i $i:\"")
391 sw.Write("elif [[ \"$i\" != \"$node1\" ]]; then")
394 sw.Write("tmp=\"$tmp $i\"")
402 WriteCompReply(sw, "-P \"$pfx\" -W \"$tmp\"", cur="\"$curvalue\"")
404 WriteCompReply(sw, "-W %s" % utils.ShellQuote(suggest), cur=cur)
415 def _CompleteArguments(self, sw):
416 if not (self.opts or self.args):
419 all_option_names = []
420 for opt in self.opts:
421 all_option_names.extend(opt.all_names)
422 all_option_names.sort()
424 # List options if no argument has been specified yet
425 sw.Write("_ganeti_list_options %s",
426 utils.ShellQuote(" ".join(all_option_names)))
429 last_idx = len(self.args) - 1
431 varlen_arg_idx = None
434 # Write some debug comments
435 for idx, arg in enumerate(self.args):
436 sw.Write("# %s: %r", idx, arg)
438 sw.Write("compgenargs=")
440 for idx, arg in enumerate(self.args):
441 assert arg.min is not None and arg.min >= 0
442 assert not (idx < last_idx and arg.max is None)
444 if arg.min != arg.max or arg.max is None:
445 if varlen_arg_idx is not None:
446 raise Exception("Only one argument can have a variable length")
451 if isinstance(arg, cli.ArgUnknown):
453 elif isinstance(arg, cli.ArgSuggest):
454 choices = utils.ShellQuote(" ".join(arg.choices))
455 elif isinstance(arg, cli.ArgInstance):
456 choices = "$(_ganeti_instances)"
457 elif isinstance(arg, cli.ArgNode):
458 choices = "$(_ganeti_nodes)"
459 elif isinstance(arg, cli.ArgJobId):
460 choices = "$(_ganeti_jobs)"
461 elif isinstance(arg, cli.ArgFile):
463 compgenargs.append("-f")
464 elif isinstance(arg, cli.ArgCommand):
466 compgenargs.append("-c")
467 elif isinstance(arg, cli.ArgHost):
469 compgenargs.append("-A hostname")
471 raise Exception("Unknown argument type %r" % arg)
473 if arg.min == 1 and arg.max == 1:
474 cmpcode = """"$arg_idx" == %d""" % (last_arg_end)
475 elif arg.max is None:
476 cmpcode = """"$arg_idx" -ge %d""" % (last_arg_end)
477 elif arg.min <= arg.max:
478 cmpcode = (""""$arg_idx" -ge %d && "$arg_idx" -lt %d""" %
479 (last_arg_end, last_arg_end + arg.max))
481 raise Exception("Unable to generate argument position condition")
483 last_arg_end += arg.min
485 if choices or compgenargs:
491 sw.Write("""%s [[ %s ]]; then""", condcmd, cmpcode)
495 sw.Write("""choices="$choices "%s""", choices)
497 sw.Write("compgenargs=%s",
498 utils.ShellQuote(" ".join(compgenargs)))
508 WriteCompReply(sw, """-W "$choices" $compgenargs""")
510 # $compgenargs exists only if there are arguments
511 WriteCompReply(sw, '-W "$choices"')
513 def WriteTo(self, sw):
514 self._FindFirstArgument(sw)
515 self._CompleteOptionValues(sw)
516 self._CompleteArguments(sw)
519 def WriteCompletion(sw, scriptname, funcname,
521 opts=None, args=None):
522 """Writes the completion code for one command.
524 @type sw: ShellWriter
525 @param sw: Script writer
526 @type scriptname: string
527 @param scriptname: Name of command line program
528 @type funcname: string
529 @param funcname: Shell function name
531 @param commands: List of all subcommands in this program
534 sw.Write("%s() {", funcname)
538 ' cur="${COMP_WORDS[COMP_CWORD]}"'
539 ' prev="${COMP_WORDS[COMP_CWORD-1]}"'
540 ' i first_arg_idx choices compgenargs arg_idx optcur')
542 sw.Write("_ganeti_dbglog cur=\"$cur\" prev=\"$prev\"")
543 sw.Write("[[ -n \"$GANETI_COMPL_LOG\" ]] &&"
544 " _ganeti_dbglog \"$(set | grep ^COMP_)\"")
546 sw.Write("COMPREPLY=()")
548 if opts is not None and args is not None:
550 CompletionWriter(0, opts, args).WriteTo(sw)
553 sw.Write("""if [[ "$COMP_CWORD" == 1 ]]; then""")
556 # Complete the command name
559 utils.ShellQuote(" ".join(sorted(commands.keys())))))
564 # We're doing options and arguments to commands
565 sw.Write("""case "${COMP_WORDS[1]}" in""")
566 for cmd, (_, argdef, optdef, _, _) in commands.iteritems():
567 if not (argdef or optdef):
570 # TODO: Group by arguments and options
571 sw.Write("%s)", utils.ShellQuote(cmd))
574 CompletionWriter(1, optdef, argdef).WriteTo(sw)
584 sw.Write("complete -F %s -o filenames %s",
585 utils.ShellQuote(funcname),
586 utils.ShellQuote(scriptname))
589 def GetFunctionName(name):
590 return "_" + re.sub(r"[^a-z0-9]+", "_", name.lower())
593 def GetCommands(filename, module):
594 """Returns the commands defined in a module.
596 Aliases are also added as commands.
600 commands = getattr(module, "commands")
601 except AttributeError:
602 raise Exception("Script %s doesn't have 'commands' attribute" %
605 # Add the implicit "--help" option
606 help_option = cli.cli_option("-h", "--help", default=False,
609 for (_, _, optdef, _, _) in commands.itervalues():
610 if help_option not in optdef:
611 optdef.append(help_option)
612 if cli.DEBUG_OPT not in optdef:
613 optdef.append(cli.DEBUG_OPT)
616 aliases = getattr(module, "aliases", {})
618 commands = commands.copy()
619 for name, target in aliases.iteritems():
620 commands[name] = commands[target]
627 sw = ShellWriter(buf)
632 for scriptname in _autoconf.GNT_SCRIPTS:
633 filename = "scripts/%s" % scriptname
635 WriteCompletion(sw, scriptname,
636 GetFunctionName(scriptname),
637 commands=GetCommands(filename,
638 build.LoadModule(filename)))
641 burnin = build.LoadModule("tools/burnin")
642 WriteCompletion(sw, "%s/burnin" % constants.TOOLSDIR, "_ganeti_burnin",
643 opts=burnin.OPTIONS, args=burnin.ARGUMENTS)
648 if __name__ == "__main__":