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
43 def WritePreamble(sw):
44 """Writes the script preamble.
46 Helper functions should be written here.
49 sw.Write("# This script is automatically generated at build time.")
50 sw.Write("# Do not modify manually.")
52 sw.Write("_ganeti_dbglog() {")
55 sw.Write("if [[ -n \"$GANETI_COMPL_LOG\" ]]; then")
62 sw.Write("echo \"$@\"")
66 sw.Write("} >> $GANETI_COMPL_LOG")
74 sw.Write("_ganeti_nodes() {")
77 node_list_path = os.path.join(constants.DATA_DIR, "ssconf_node_list")
78 sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(node_list_path))
83 sw.Write("_ganeti_instances() {")
86 instance_list_path = os.path.join(constants.DATA_DIR,
87 "ssconf_instance_list")
88 sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(instance_list_path))
93 sw.Write("_ganeti_jobs() {")
96 # FIXME: this is really going into the internals of the job queue
97 sw.Write(("local jlist=$( shopt -s nullglob &&"
98 " cd %s 2>/dev/null && echo job-* || : )"),
99 utils.ShellQuote(constants.QUEUE_DIR))
100 sw.Write('echo "${jlist//job-/}"')
105 for (fnname, paths) in [
106 ("os", constants.OS_SEARCH_PATH),
107 ("iallocator", constants.IALLOCATOR_SEARCH_PATH),
109 sw.Write("_ganeti_%s() {", fnname)
112 # FIXME: Make querying the master for all OSes cheap
114 sw.Write("( shopt -s nullglob && cd %s 2>/dev/null && echo * || : )",
115 utils.ShellQuote(path))
120 # Params: <offset> <options with values> <options without values>
121 # Result variable: $first_arg_idx
122 sw.Write("_ganeti_find_first_arg() {")
125 sw.Write("local w i")
127 sw.Write("first_arg_idx=")
128 sw.Write("for (( i=$1; i < COMP_CWORD; ++i )); do")
131 sw.Write("w=${COMP_WORDS[$i]}")
134 sw.Write("""if [[ -n "$2" && "$w" == @($2) ]]; then let ++i""")
137 sw.Write("""elif [[ -n "$3" && "$w" == @($3) ]]; then :""")
139 # Ah, we found the first argument
140 sw.Write("else first_arg_idx=$i; break;")
149 # Params: <list of options separated by space>
150 # Input variable: $first_arg_idx
151 # Result variables: $arg_idx, $choices
152 sw.Write("_ganeti_list_options() {")
155 sw.Write("""if [[ -z "$first_arg_idx" ]]; then""")
158 sw.Write("arg_idx=0")
159 # Show options only if the current word starts with a dash
160 sw.Write("""if [[ "$cur" == -* ]]; then""")
163 sw.Write("choices=$1")
172 # Calculate position of current argument
173 sw.Write("arg_idx=$(( COMP_CWORD - first_arg_idx ))")
179 # Params: <long options with equal sign> <all options>
180 # Result variable: $optcur
181 sw.Write("_ganeti_checkopt() {")
184 sw.Write("""if [[ -n "$1" && "$cur" == @($1) ]]; then""")
187 sw.Write("optcur=\"${cur#--*=}\"")
191 sw.Write("""elif [[ -n "$2" && "$prev" == @($2) ]]; then""")
194 sw.Write("optcur=\"$cur\"")
200 sw.Write("_ganeti_dbglog optcur=\"'$optcur'\"")
207 # Params: <compgen options>
208 # Result variable: $COMPREPLY
209 sw.Write("_ganeti_compgen() {")
212 sw.Write("""COMPREPLY=( $(compgen "$@") )""")
213 sw.Write("_ganeti_dbglog COMPREPLY=\"${COMPREPLY[@]}\"")
219 def WriteCompReply(sw, args, cur="\"$cur\""):
220 sw.Write("_ganeti_compgen %s -- %s", args, cur)
224 class CompletionWriter:
225 """Command completion writer class.
228 def __init__(self, arg_offset, opts, args):
229 self.arg_offset = arg_offset
234 # While documented, these variables aren't seen as public attributes by
235 # pylint. pylint: disable-msg=W0212
236 opt.all_names = sorted(opt._short_opts + opt._long_opts)
238 def _FindFirstArgument(self, sw):
242 for opt in self.opts:
243 if opt.takes_value():
245 for i in opt.all_names:
246 if i.startswith("--"):
247 ignore.append("%s=*" % utils.ShellQuote(i))
248 skip_one.append(utils.ShellQuote(i))
250 ignore.extend([utils.ShellQuote(i) for i in opt.all_names])
252 ignore = sorted(utils.UniqueSequence(ignore))
253 skip_one = sorted(utils.UniqueSequence(skip_one))
255 if ignore or skip_one:
256 # Try to locate first argument
257 sw.Write("_ganeti_find_first_arg %s %s %s",
259 utils.ShellQuote("|".join(skip_one)),
260 utils.ShellQuote("|".join(ignore)))
262 # When there are no options the first argument is always at position
264 sw.Write("first_arg_idx=%s", self.arg_offset + 1)
266 def _CompleteOptionValues(self, sw):
268 # "values" -> [optname1, optname2, ...]
271 for opt in self.opts:
272 if not opt.takes_value():
275 # Only static choices implemented so far (e.g. no node list)
276 suggest = getattr(opt, "completion_suggest", None)
278 # our custom option type
279 if opt.type == "bool":
280 suggest = ["yes", "no"]
283 suggest = opt.choices
285 if (isinstance(suggest, (int, long)) and
286 suggest in cli.OPT_COMPL_ALL):
289 key = " ".join(sorted(suggest))
293 values.setdefault(key, []).extend(opt.all_names)
295 # Don't write any code if there are no option values
303 for (suggest, allnames) in values.iteritems():
304 longnames = [i for i in allnames if i.startswith("--")]
311 sw.Write("%s _ganeti_checkopt %s %s; then", condcmd,
312 utils.ShellQuote("|".join(["%s=*" % i for i in longnames])),
313 utils.ShellQuote("|".join(allnames)))
316 if suggest == cli.OPT_COMPL_MANY_NODES:
317 # TODO: Implement comma-separated values
318 WriteCompReply(sw, "-W ''", cur=cur)
319 elif suggest == cli.OPT_COMPL_ONE_NODE:
320 WriteCompReply(sw, "-W \"$(_ganeti_nodes)\"", cur=cur)
321 elif suggest == cli.OPT_COMPL_ONE_INSTANCE:
322 WriteCompReply(sw, "-W \"$(_ganeti_instances)\"", cur=cur)
323 elif suggest == cli.OPT_COMPL_ONE_OS:
324 WriteCompReply(sw, "-W \"$(_ganeti_os)\"", cur=cur)
325 elif suggest == cli.OPT_COMPL_ONE_IALLOCATOR:
326 WriteCompReply(sw, "-W \"$(_ganeti_iallocator)\"", cur=cur)
327 elif suggest == cli.OPT_COMPL_INST_ADD_NODES:
328 sw.Write("local tmp= node1= pfx= curvalue=\"${optcur#*:}\"")
330 sw.Write("if [[ \"$optcur\" == *:* ]]; then")
333 sw.Write("node1=\"${optcur%%:*}\"")
335 sw.Write("if [[ \"$COMP_WORDBREAKS\" != *:* ]]; then")
338 sw.Write("pfx=\"$node1:\"")
346 sw.Write("_ganeti_dbglog pfx=\"'$pfx'\" curvalue=\"'$curvalue'\""
347 " node1=\"'$node1'\"")
349 sw.Write("for i in $(_ganeti_nodes); do")
352 sw.Write("if [[ -z \"$node1\" ]]; then")
355 sw.Write("tmp=\"$tmp $i $i:\"")
358 sw.Write("elif [[ \"$i\" != \"$node1\" ]]; then")
361 sw.Write("tmp=\"$tmp $i\"")
369 WriteCompReply(sw, "-P \"$pfx\" -W \"$tmp\"", cur="\"$curvalue\"")
371 WriteCompReply(sw, "-W %s" % utils.ShellQuote(suggest), cur=cur)
382 def _CompleteArguments(self, sw):
383 if not (self.opts or self.args):
386 all_option_names = []
387 for opt in self.opts:
388 all_option_names.extend(opt.all_names)
389 all_option_names.sort()
391 # List options if no argument has been specified yet
392 sw.Write("_ganeti_list_options %s",
393 utils.ShellQuote(" ".join(all_option_names)))
396 last_idx = len(self.args) - 1
398 varlen_arg_idx = None
401 # Write some debug comments
402 for idx, arg in enumerate(self.args):
403 sw.Write("# %s: %r", idx, arg)
405 sw.Write("compgenargs=")
407 for idx, arg in enumerate(self.args):
408 assert arg.min is not None and arg.min >= 0
409 assert not (idx < last_idx and arg.max is None)
411 if arg.min != arg.max or arg.max is None:
412 if varlen_arg_idx is not None:
413 raise Exception("Only one argument can have a variable length")
418 if isinstance(arg, cli.ArgUnknown):
420 elif isinstance(arg, cli.ArgSuggest):
421 choices = utils.ShellQuote(" ".join(arg.choices))
422 elif isinstance(arg, cli.ArgInstance):
423 choices = "$(_ganeti_instances)"
424 elif isinstance(arg, cli.ArgNode):
425 choices = "$(_ganeti_nodes)"
426 elif isinstance(arg, cli.ArgJobId):
427 choices = "$(_ganeti_jobs)"
428 elif isinstance(arg, cli.ArgOs):
429 choices = "$(_ganeti_os)"
430 elif isinstance(arg, cli.ArgFile):
432 compgenargs.append("-f")
433 elif isinstance(arg, cli.ArgCommand):
435 compgenargs.append("-c")
436 elif isinstance(arg, cli.ArgHost):
438 compgenargs.append("-A hostname")
440 raise Exception("Unknown argument type %r" % arg)
442 if arg.min == 1 and arg.max == 1:
443 cmpcode = """"$arg_idx" == %d""" % (last_arg_end)
444 elif arg.max is None:
445 cmpcode = """"$arg_idx" -ge %d""" % (last_arg_end)
446 elif arg.min <= arg.max:
447 cmpcode = (""""$arg_idx" -ge %d && "$arg_idx" -lt %d""" %
448 (last_arg_end, last_arg_end + arg.max))
450 raise Exception("Unable to generate argument position condition")
452 last_arg_end += arg.min
454 if choices or compgenargs:
460 sw.Write("""%s [[ %s ]]; then""", condcmd, cmpcode)
464 sw.Write("""choices="$choices "%s""", choices)
466 sw.Write("compgenargs=%s",
467 utils.ShellQuote(" ".join(compgenargs)))
477 WriteCompReply(sw, """-W "$choices" $compgenargs""")
479 # $compgenargs exists only if there are arguments
480 WriteCompReply(sw, '-W "$choices"')
482 def WriteTo(self, sw):
483 self._FindFirstArgument(sw)
484 self._CompleteOptionValues(sw)
485 self._CompleteArguments(sw)
488 def WriteCompletion(sw, scriptname, funcname,
490 opts=None, args=None):
491 """Writes the completion code for one command.
493 @type sw: ShellWriter
494 @param sw: Script writer
495 @type scriptname: string
496 @param scriptname: Name of command line program
497 @type funcname: string
498 @param funcname: Shell function name
500 @param commands: List of all subcommands in this program
503 sw.Write("%s() {", funcname)
507 ' cur="${COMP_WORDS[COMP_CWORD]}"'
508 ' prev="${COMP_WORDS[COMP_CWORD-1]}"'
509 ' i first_arg_idx choices compgenargs arg_idx optcur')
511 sw.Write("_ganeti_dbglog cur=\"$cur\" prev=\"$prev\"")
512 sw.Write("[[ -n \"$GANETI_COMPL_LOG\" ]] &&"
513 " _ganeti_dbglog \"$(set | grep ^COMP_)\"")
515 sw.Write("COMPREPLY=()")
517 if opts is not None and args is not None:
519 CompletionWriter(0, opts, args).WriteTo(sw)
522 sw.Write("""if [[ "$COMP_CWORD" == 1 ]]; then""")
525 # Complete the command name
528 utils.ShellQuote(" ".join(sorted(commands.keys())))))
533 # We're doing options and arguments to commands
534 sw.Write("""case "${COMP_WORDS[1]}" in""")
535 for cmd, (_, argdef, optdef, _, _) in commands.iteritems():
536 if not (argdef or optdef):
539 # TODO: Group by arguments and options
540 sw.Write("%s)", utils.ShellQuote(cmd))
543 CompletionWriter(1, optdef, argdef).WriteTo(sw)
553 sw.Write("complete -F %s -o filenames %s",
554 utils.ShellQuote(funcname),
555 utils.ShellQuote(scriptname))
558 def GetFunctionName(name):
559 return "_" + re.sub(r"[^a-z0-9]+", "_", name.lower())
562 def GetCommands(filename, module):
563 """Returns the commands defined in a module.
565 Aliases are also added as commands.
569 commands = getattr(module, "commands")
570 except AttributeError:
571 raise Exception("Script %s doesn't have 'commands' attribute" %
574 # Add the implicit "--help" option
575 help_option = cli.cli_option("-h", "--help", default=False,
578 for (_, _, optdef, _, _) in commands.itervalues():
579 if help_option not in optdef:
580 optdef.append(help_option)
581 if cli.DEBUG_OPT not in optdef:
582 optdef.append(cli.DEBUG_OPT)
585 aliases = getattr(module, "aliases", {})
587 commands = commands.copy()
588 for name, target in aliases.iteritems():
589 commands[name] = commands[target]
596 sw = utils.ShellWriter(buf)
601 for scriptname in _autoconf.GNT_SCRIPTS:
602 filename = "scripts/%s" % scriptname
604 WriteCompletion(sw, scriptname,
605 GetFunctionName(scriptname),
606 commands=GetCommands(filename,
607 build.LoadModule(filename)))
610 burnin = build.LoadModule("tools/burnin")
611 WriteCompletion(sw, "%s/burnin" % constants.TOOLSDIR, "_ganeti_burnin",
612 opts=burnin.OPTIONS, args=burnin.ARGUMENTS)
617 if __name__ == "__main__":