build-bash-completion 27.1 KB
Newer Older
1 2 3
#!/usr/bin/python
#

4
# Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
Klaus Aehlig's avatar
Klaus Aehlig committed
5
# All rights reserved.
6
#
Klaus Aehlig's avatar
Klaus Aehlig committed
7 8 9
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
10
#
Klaus Aehlig's avatar
Klaus Aehlig committed
11 12
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
13
#
Klaus Aehlig's avatar
Klaus Aehlig committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 30


31 32 33 34
"""Script to generate bash_completion script for Ganeti.

"""

35
# pylint: disable=C0103
36 37
# [C0103] Invalid name build-bash-completion

38
import os
39
import os.path
40
import re
41
import itertools
42
import optparse
43 44
from cStringIO import StringIO

45 46 47 48
# _constants shouldn't be imported from anywhere except constants.py, but we're
# making an exception here because this script is only used at build time.
from ganeti import _constants

49 50 51
from ganeti import constants
from ganeti import cli
from ganeti import utils
52
from ganeti import build
53
from ganeti import pathutils
54

55 56
from ganeti.tools import burnin

57 58 59 60
#: Regular expression describing desired format of option names. Long names can
#: contain lowercase characters, numbers and dashes only.
_OPT_NAME_RE = re.compile(r"^-[a-zA-Z0-9]|--[a-z][-a-z0-9]+$")

61

62
def _WriteGntLog(sw, support_debug):
63 64
  if support_debug:
    sw.Write("_gnt_log() {")
65 66
    sw.IncIndent()
    try:
67
      sw.Write("if [[ -n \"$GANETI_COMPL_LOG\" ]]; then")
68 69
      sw.IncIndent()
      try:
70 71 72 73 74 75 76 77 78
        sw.Write("{")
        sw.IncIndent()
        try:
          sw.Write("echo ---")
          sw.Write("echo \"$@\"")
          sw.Write("echo")
        finally:
          sw.DecIndent()
        sw.Write("} >> $GANETI_COMPL_LOG")
79 80
      finally:
        sw.DecIndent()
81
      sw.Write("fi")
82 83
    finally:
      sw.DecIndent()
84
    sw.Write("}")
85

86 87

def _WriteNodes(sw):
88 89 90
  sw.Write("_ganeti_nodes() {")
  sw.IncIndent()
  try:
91
    node_list_path = os.path.join(pathutils.DATA_DIR, "ssconf_node_list")
92
    sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(node_list_path))
93 94 95 96
  finally:
    sw.DecIndent()
  sw.Write("}")

97 98

def _WriteInstances(sw):
99 100 101
  sw.Write("_ganeti_instances() {")
  sw.IncIndent()
  try:
102
    instance_list_path = os.path.join(pathutils.DATA_DIR,
103
                                      "ssconf_instance_list")
104
    sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(instance_list_path))
105 106 107 108
  finally:
    sw.DecIndent()
  sw.Write("}")

109 110

def _WriteJobs(sw):
111 112 113 114
  sw.Write("_ganeti_jobs() {")
  sw.IncIndent()
  try:
    # FIXME: this is really going into the internals of the job queue
115 116
    sw.Write(("local jlist=($( shopt -s nullglob &&"
              " cd %s 2>/dev/null && echo job-* || : ))"),
117
             utils.ShellQuote(pathutils.QUEUE_DIR))
118
    sw.Write('echo "${jlist[@]/job-/}"')
119 120 121 122
  finally:
    sw.DecIndent()
  sw.Write("}")

123 124

def _WriteOSAndIAllocator(sw):
125
  for (fnname, paths) in [
126
    ("os", pathutils.OS_SEARCH_PATH),
Iustin Pop's avatar
Iustin Pop committed
127 128
    ("iallocator", constants.IALLOCATOR_SEARCH_PATH),
    ]:
129 130 131 132 133 134 135 136 137 138
    sw.Write("_ganeti_%s() {", fnname)
    sw.IncIndent()
    try:
      # FIXME: Make querying the master for all OSes cheap
      for path in paths:
        sw.Write("( shopt -s nullglob && cd %s 2>/dev/null && echo * || : )",
                 utils.ShellQuote(path))
    finally:
      sw.DecIndent()
    sw.Write("}")
139

140 141

def _WriteNodegroup(sw):
142 143 144
  sw.Write("_ganeti_nodegroup() {")
  sw.IncIndent()
  try:
145
    nodegroups_path = os.path.join(pathutils.DATA_DIR, "ssconf_nodegroups")
146 147 148 149 150
    sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(nodegroups_path))
  finally:
    sw.DecIndent()
  sw.Write("}")

151 152

def _WriteNetwork(sw):
153 154 155 156 157 158 159 160 161
  sw.Write("_ganeti_network() {")
  sw.IncIndent()
  try:
    networks_path = os.path.join(pathutils.DATA_DIR, "ssconf_networks")
    sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(networks_path))
  finally:
    sw.DecIndent()
  sw.Write("}")

162 163

def _WriteFindFirstArg(sw):
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  # Params: <offset> <options with values> <options without values>
  # Result variable: $first_arg_idx
  sw.Write("_ganeti_find_first_arg() {")
  sw.IncIndent()
  try:
    sw.Write("local w i")

    sw.Write("first_arg_idx=")
    sw.Write("for (( i=$1; i < COMP_CWORD; ++i )); do")
    sw.IncIndent()
    try:
      sw.Write("w=${COMP_WORDS[$i]}")

      # Skip option value
      sw.Write("""if [[ -n "$2" && "$w" == @($2) ]]; then let ++i""")

      # Skip
      sw.Write("""elif [[ -n "$3" && "$w" == @($3) ]]; then :""")

      # Ah, we found the first argument
      sw.Write("else first_arg_idx=$i; break;")
      sw.Write("fi")
    finally:
      sw.DecIndent()
    sw.Write("done")
  finally:
    sw.DecIndent()
  sw.Write("}")

193 194

def _WriteListOptions(sw):
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  # Params: <list of options separated by space>
  # Input variable: $first_arg_idx
  # Result variables: $arg_idx, $choices
  sw.Write("_ganeti_list_options() {")
  sw.IncIndent()
  try:
    sw.Write("""if [[ -z "$first_arg_idx" ]]; then""")
    sw.IncIndent()
    try:
      sw.Write("arg_idx=0")
      # Show options only if the current word starts with a dash
      sw.Write("""if [[ "$cur" == -* ]]; then""")
      sw.IncIndent()
      try:
        sw.Write("choices=$1")
      finally:
        sw.DecIndent()
      sw.Write("fi")
      sw.Write("return")
    finally:
      sw.DecIndent()
    sw.Write("fi")

    # Calculate position of current argument
    sw.Write("arg_idx=$(( COMP_CWORD - first_arg_idx ))")
    sw.Write("choices=")
  finally:
    sw.DecIndent()
  sw.Write("}")

225 226

def _WriteGntCheckopt(sw, support_debug):
227 228
  # Params: <long options with equal sign> <all options>
  # Result variable: $optcur
229
  sw.Write("_gnt_checkopt() {")
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  sw.IncIndent()
  try:
    sw.Write("""if [[ -n "$1" && "$cur" == @($1) ]]; then""")
    sw.IncIndent()
    try:
      sw.Write("optcur=\"${cur#--*=}\"")
      sw.Write("return 0")
    finally:
      sw.DecIndent()
    sw.Write("""elif [[ -n "$2" && "$prev" == @($2) ]]; then""")
    sw.IncIndent()
    try:
      sw.Write("optcur=\"$cur\"")
      sw.Write("return 0")
    finally:
      sw.DecIndent()
    sw.Write("fi")

248 249
    if support_debug:
      sw.Write("_gnt_log optcur=\"'$optcur'\"")
250

251 252 253 254 255
    sw.Write("return 1")
  finally:
    sw.DecIndent()
  sw.Write("}")

256 257

def _WriteGntCompgen(sw, support_debug):
258 259
  # Params: <compgen options>
  # Result variable: $COMPREPLY
260
  sw.Write("_gnt_compgen() {")
261 262 263
  sw.IncIndent()
  try:
    sw.Write("""COMPREPLY=( $(compgen "$@") )""")
264 265
    if support_debug:
      sw.Write("_gnt_log COMPREPLY=\"${COMPREPLY[@]}\"")
266 267 268 269
  finally:
    sw.DecIndent()
  sw.Write("}")

270

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
def WritePreamble(sw, support_debug):
  """Writes the script preamble.

  Helper functions should be written here.

  """
  sw.Write("# This script is automatically generated at build time.")
  sw.Write("# Do not modify manually.")

  _WriteGntLog(sw, support_debug)
  _WriteNodes(sw)
  _WriteInstances(sw)
  _WriteJobs(sw)
  _WriteOSAndIAllocator(sw)
  _WriteNodegroup(sw)
  _WriteNetwork(sw)
  _WriteFindFirstArg(sw)
  _WriteListOptions(sw)
  _WriteGntCheckopt(sw, support_debug)
  _WriteGntCompgen(sw, support_debug)


293
def WriteCompReply(sw, args, cur="\"$cur\""):
294
  sw.Write("_gnt_compgen %s -- %s", args, cur)
295 296 297
  sw.Write("return")


298
class CompletionWriter(object):
299 300 301
  """Command completion writer class.

  """
302
  def __init__(self, arg_offset, opts, args, support_debug):
303 304 305
    self.arg_offset = arg_offset
    self.opts = opts
    self.args = args
306
    self.support_debug = support_debug
307 308

    for opt in opts:
309
      # While documented, these variables aren't seen as public attributes by
310
      # pylint. pylint: disable=W0212
311 312
      opt.all_names = sorted(opt._short_opts + opt._long_opts)

313 314 315 316 317
      invalid = list(itertools.ifilterfalse(_OPT_NAME_RE.match, opt.all_names))
      if invalid:
        raise Exception("Option names don't match regular expression '%s': %s" %
                        (_OPT_NAME_RE.pattern, utils.CommaJoin(invalid)))

318 319 320 321 322 323 324 325
  def _FindFirstArgument(self, sw):
    ignore = []
    skip_one = []

    for opt in self.opts:
      if opt.takes_value():
        # Ignore value
        for i in opt.all_names:
326 327
          if i.startswith("--"):
            ignore.append("%s=*" % utils.ShellQuote(i))
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
          skip_one.append(utils.ShellQuote(i))
      else:
        ignore.extend([utils.ShellQuote(i) for i in opt.all_names])

    ignore = sorted(utils.UniqueSequence(ignore))
    skip_one = sorted(utils.UniqueSequence(skip_one))

    if ignore or skip_one:
      # Try to locate first argument
      sw.Write("_ganeti_find_first_arg %s %s %s",
               self.arg_offset + 1,
               utils.ShellQuote("|".join(skip_one)),
               utils.ShellQuote("|".join(ignore)))
    else:
      # When there are no options the first argument is always at position
      # offset + 1
      sw.Write("first_arg_idx=%s", self.arg_offset + 1)

  def _CompleteOptionValues(self, sw):
    # Group by values
    # "values" -> [optname1, optname2, ...]
    values = {}

    for opt in self.opts:
      if not opt.takes_value():
        continue

      # Only static choices implemented so far (e.g. no node list)
      suggest = getattr(opt, "completion_suggest", None)

Iustin Pop's avatar
Iustin Pop committed
358 359 360 361
      # our custom option type
      if opt.type == "bool":
        suggest = ["yes", "no"]

362 363 364
      if not suggest:
        suggest = opt.choices

365 366 367 368 369
      if (isinstance(suggest, (int, long)) and
          suggest in cli.OPT_COMPL_ALL):
        key = suggest
      elif suggest:
        key = " ".join(sorted(suggest))
370
      else:
371
        key = ""
372

373
      values.setdefault(key, []).extend(opt.all_names)
374 375 376 377 378

    # Don't write any code if there are no option values
    if not values:
      return

379 380 381 382
    cur = "\"$optcur\""

    wrote_opt = False

383
    for (suggest, allnames) in values.items():
384 385 386 387 388 389 390
      longnames = [i for i in allnames if i.startswith("--")]

      if wrote_opt:
        condcmd = "elif"
      else:
        condcmd = "if"

391
      sw.Write("%s _gnt_checkopt %s %s; then", condcmd,
392 393 394 395
               utils.ShellQuote("|".join(["%s=*" % i for i in longnames])),
               utils.ShellQuote("|".join(allnames)))
      sw.IncIndent()
      try:
396 397 398 399 400 401 402 403 404
        if suggest == cli.OPT_COMPL_MANY_NODES:
          # TODO: Implement comma-separated values
          WriteCompReply(sw, "-W ''", cur=cur)
        elif suggest == cli.OPT_COMPL_ONE_NODE:
          WriteCompReply(sw, "-W \"$(_ganeti_nodes)\"", cur=cur)
        elif suggest == cli.OPT_COMPL_ONE_INSTANCE:
          WriteCompReply(sw, "-W \"$(_ganeti_instances)\"", cur=cur)
        elif suggest == cli.OPT_COMPL_ONE_OS:
          WriteCompReply(sw, "-W \"$(_ganeti_os)\"", cur=cur)
405 406
        elif suggest == cli.OPT_COMPL_ONE_EXTSTORAGE:
          WriteCompReply(sw, "-W \"$(_ganeti_extstorage)\"", cur=cur)
407 408
        elif suggest == cli.OPT_COMPL_ONE_IALLOCATOR:
          WriteCompReply(sw, "-W \"$(_ganeti_iallocator)\"", cur=cur)
409 410
        elif suggest == cli.OPT_COMPL_ONE_NODEGROUP:
          WriteCompReply(sw, "-W \"$(_ganeti_nodegroup)\"", cur=cur)
411 412
        elif suggest == cli.OPT_COMPL_ONE_NETWORK:
          WriteCompReply(sw, "-W \"$(_ganeti_network)\"", cur=cur)
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        elif suggest == cli.OPT_COMPL_INST_ADD_NODES:
          sw.Write("local tmp= node1= pfx= curvalue=\"${optcur#*:}\"")

          sw.Write("if [[ \"$optcur\" == *:* ]]; then")
          sw.IncIndent()
          try:
            sw.Write("node1=\"${optcur%%:*}\"")

            sw.Write("if [[ \"$COMP_WORDBREAKS\" != *:* ]]; then")
            sw.IncIndent()
            try:
              sw.Write("pfx=\"$node1:\"")
            finally:
              sw.DecIndent()
            sw.Write("fi")
          finally:
            sw.DecIndent()
          sw.Write("fi")

432 433 434
          if self.support_debug:
            sw.Write("_gnt_log pfx=\"'$pfx'\" curvalue=\"'$curvalue'\""
                     " node1=\"'$node1'\"")
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

          sw.Write("for i in $(_ganeti_nodes); do")
          sw.IncIndent()
          try:
            sw.Write("if [[ -z \"$node1\" ]]; then")
            sw.IncIndent()
            try:
              sw.Write("tmp=\"$tmp $i $i:\"")
            finally:
              sw.DecIndent()
            sw.Write("elif [[ \"$i\" != \"$node1\" ]]; then")
            sw.IncIndent()
            try:
              sw.Write("tmp=\"$tmp $i\"")
            finally:
              sw.DecIndent()
            sw.Write("fi")
          finally:
            sw.DecIndent()
          sw.Write("done")

          WriteCompReply(sw, "-P \"$pfx\" -W \"$tmp\"", cur="\"$curvalue\"")
457 458
        else:
          WriteCompReply(sw, "-W %s" % utils.ShellQuote(suggest), cur=cur)
459 460 461 462 463 464 465 466 467
      finally:
        sw.DecIndent()

      wrote_opt = True

    if wrote_opt:
      sw.Write("fi")

    return
468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
  def _CompleteArguments(self, sw):
    if not (self.opts or self.args):
      return

    all_option_names = []
    for opt in self.opts:
      all_option_names.extend(opt.all_names)
    all_option_names.sort()

    # List options if no argument has been specified yet
    sw.Write("_ganeti_list_options %s",
             utils.ShellQuote(" ".join(all_option_names)))

    if self.args:
      last_idx = len(self.args) - 1
      last_arg_end = 0
      varlen_arg_idx = None
      wrote_arg = False

      sw.Write("compgenargs=")

      for idx, arg in enumerate(self.args):
        assert arg.min is not None and arg.min >= 0
        assert not (idx < last_idx and arg.max is None)

        if arg.min != arg.max or arg.max is None:
          if varlen_arg_idx is not None:
            raise Exception("Only one argument can have a variable length")
          varlen_arg_idx = idx

        compgenargs = []

        if isinstance(arg, cli.ArgUnknown):
          choices = ""
        elif isinstance(arg, cli.ArgSuggest):
          choices = utils.ShellQuote(" ".join(arg.choices))
        elif isinstance(arg, cli.ArgInstance):
          choices = "$(_ganeti_instances)"
        elif isinstance(arg, cli.ArgNode):
          choices = "$(_ganeti_nodes)"
509 510
        elif isinstance(arg, cli.ArgGroup):
          choices = "$(_ganeti_nodegroup)"
511 512
        elif isinstance(arg, cli.ArgNetwork):
          choices = "$(_ganeti_network)"
513 514
        elif isinstance(arg, cli.ArgJobId):
          choices = "$(_ganeti_jobs)"
515 516
        elif isinstance(arg, cli.ArgOs):
          choices = "$(_ganeti_os)"
517 518
        elif isinstance(arg, cli.ArgExtStorage):
          choices = "$(_ganeti_extstorage)"
519 520 521 522 523 524
        elif isinstance(arg, cli.ArgFile):
          choices = ""
          compgenargs.append("-f")
        elif isinstance(arg, cli.ArgCommand):
          choices = ""
          compgenargs.append("-c")
Michael Hanselmann's avatar
Michael Hanselmann committed
525 526 527
        elif isinstance(arg, cli.ArgHost):
          choices = ""
          compgenargs.append("-A hostname")
528 529 530 531 532
        else:
          raise Exception("Unknown argument type %r" % arg)

        if arg.min == 1 and arg.max == 1:
          cmpcode = """"$arg_idx" == %d""" % (last_arg_end)
533 534
        elif arg.max is None:
          cmpcode = """"$arg_idx" -ge %d""" % (last_arg_end)
535
        elif arg.min <= arg.max:
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
          cmpcode = (""""$arg_idx" -ge %d && "$arg_idx" -lt %d""" %
                     (last_arg_end, last_arg_end + arg.max))
        else:
          raise Exception("Unable to generate argument position condition")

        last_arg_end += arg.min

        if choices or compgenargs:
          if wrote_arg:
            condcmd = "elif"
          else:
            condcmd = "if"

          sw.Write("""%s [[ %s ]]; then""", condcmd, cmpcode)
          sw.IncIndent()
          try:
            if choices:
              sw.Write("""choices="$choices "%s""", choices)
            if compgenargs:
555 556
              sw.Write("compgenargs=%s",
                       utils.ShellQuote(" ".join(compgenargs)))
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
          finally:
            sw.DecIndent()

          wrote_arg = True

      if wrote_arg:
        sw.Write("fi")

    if self.args:
      WriteCompReply(sw, """-W "$choices" $compgenargs""")
    else:
      # $compgenargs exists only if there are arguments
      WriteCompReply(sw, '-W "$choices"')

  def WriteTo(self, sw):
    self._FindFirstArgument(sw)
    self._CompleteOptionValues(sw)
    self._CompleteArguments(sw)


577
def WriteCompletion(sw, scriptname, funcname, support_debug,
578 579 580 581 582 583 584 585 586 587 588 589 590 591
                    commands=None,
                    opts=None, args=None):
  """Writes the completion code for one command.

  @type sw: ShellWriter
  @param sw: Script writer
  @type scriptname: string
  @param scriptname: Name of command line program
  @type funcname: string
  @param funcname: Shell function name
  @type commands: list
  @param commands: List of all subcommands in this program

  """
592
  sw.Write("%s() {", funcname)
593 594
  sw.IncIndent()
  try:
595
    sw.Write("local "
596
             ' cur="${COMP_WORDS[COMP_CWORD]}"'
597 598
             ' prev="${COMP_WORDS[COMP_CWORD-1]}"'
             ' i first_arg_idx choices compgenargs arg_idx optcur')
599

600 601 602 603
    if support_debug:
      sw.Write("_gnt_log cur=\"$cur\" prev=\"$prev\"")
      sw.Write("[[ -n \"$GANETI_COMPL_LOG\" ]] &&"
               " _gnt_log \"$(set | grep ^COMP_)\"")
604 605 606 607 608

    sw.Write("COMPREPLY=()")

    if opts is not None and args is not None:
      assert not commands
609
      CompletionWriter(0, opts, args, support_debug).WriteTo(sw)
610 611 612 613 614 615 616 617 618 619 620 621 622

    else:
      sw.Write("""if [[ "$COMP_CWORD" == 1 ]]; then""")
      sw.IncIndent()
      try:
        # Complete the command name
        WriteCompReply(sw,
                       ("-W %s" %
                        utils.ShellQuote(" ".join(sorted(commands.keys())))))
      finally:
        sw.DecIndent()
      sw.Write("fi")

623 624
      # Group commands by arguments and options
      grouped_cmds = {}
625
      for cmd, (_, argdef, optdef, _, _) in commands.items():
626 627
        if not (argdef or optdef):
          continue
628
        grouped_cmds.setdefault((tuple(argdef), tuple(optdef)), set()).add(cmd)
629

630 631
      # We're doing options and arguments to commands
      sw.Write("""case "${COMP_WORDS[1]}" in""")
632 633 634
      sort_grouped = sorted(grouped_cmds.items(),
                            key=lambda (_, y): sorted(y)[0])
      for ((argdef, optdef), cmds) in sort_grouped:
635 636
        assert argdef or optdef
        sw.Write("%s)", "|".join(map(utils.ShellQuote, sorted(cmds))))
637 638
        sw.IncIndent()
        try:
639
          CompletionWriter(1, optdef, argdef, support_debug).WriteTo(sw)
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
        finally:
          sw.DecIndent()
        sw.Write(";;")
      sw.Write("esac")
  finally:
    sw.DecIndent()
  sw.Write("}")

  sw.Write("complete -F %s -o filenames %s",
           utils.ShellQuote(funcname),
           utils.ShellQuote(scriptname))


def GetFunctionName(name):
  return "_" + re.sub(r"[^a-z0-9]+", "_", name.lower())


def GetCommands(filename, module):
  """Returns the commands defined in a module.

  Aliases are also added as commands.

  """
  try:
    commands = getattr(module, "commands")
665
  except AttributeError:
666 667 668
    raise Exception("Script %s doesn't have 'commands' attribute" %
                    filename)

669 670 671 672
  # Add the implicit "--help" option
  help_option = cli.cli_option("-h", "--help", default=False,
                               action="store_true")

673
  for name, (_, _, optdef, _, _) in commands.items():
674 675
    if help_option not in optdef:
      optdef.append(help_option)
676 677 678 679 680
    for opt in cli.COMMON_OPTS:
      if opt in optdef:
        raise Exception("Common option '%s' listed for command '%s' in %s" %
                        (opt, name, filename))
      optdef.append(opt)
681

682 683 684 685
  # Use aliases
  aliases = getattr(module, "aliases", {})
  if aliases:
    commands = commands.copy()
686
    for name, target in aliases.items():
687 688 689 690 691
      commands[name] = commands[target]

  return commands


692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
def HaskellOptToOptParse(opts, kind):
  """Converts a Haskell options to Python cli_options.

  @type opts: string
  @param opts: comma-separated string with short and long options
  @type kind: string
  @param kind: type generated by Common.hs/complToText; needs to be
      kept in sync

  """
  # pylint: disable=W0142
  # since we pass *opts in a number of places
  opts = opts.split(",")
  if kind == "none":
    return cli.cli_option(*opts, action="store_true")
707
  elif kind in ["file", "string", "host", "dir", "inetaddr"]:
708
    return cli.cli_option(*opts, type="string")
709 710 711 712
  elif kind == "integer":
    return cli.cli_option(*opts, type="int")
  elif kind == "float":
    return cli.cli_option(*opts, type="float")
713 714 715 716 717 718 719 720 721
  elif kind == "onegroup":
    return cli.cli_option(*opts, type="string",
                           completion_suggest=cli.OPT_COMPL_ONE_NODEGROUP)
  elif kind == "onenode":
    return cli.cli_option(*opts, type="string",
                          completion_suggest=cli.OPT_COMPL_ONE_NODE)
  elif kind == "manyinstances":
    # FIXME: no support for many instances
    return cli.cli_option(*opts, type="string")
722 723
  elif kind.startswith("choices="):
    choices = kind[len("choices="):].split(",")
724 725 726 727
    return cli.cli_option(*opts, type="choice", choices=choices)
  else:
    # FIXME: there are many other currently unused completion types,
    # should be added on an as-needed basis
728 729 730 731 732
    raise Exception("Unhandled option kind '%s'" % kind)


#: serialised kind to arg type
_ARG_MAP = {
733
  "choices": cli.ArgChoice,
734 735 736 737 738 739 740 741 742
  "command": cli.ArgCommand,
  "file": cli.ArgFile,
  "host": cli.ArgHost,
  "jobid": cli.ArgJobId,
  "onegroup": cli.ArgGroup,
  "oneinstance": cli.ArgInstance,
  "onenode": cli.ArgNode,
  "oneos": cli.ArgOs,
  "string": cli.ArgUnknown,
743
  "suggests": cli.ArgSuggest,
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
  }


def HaskellArgToCliArg(kind, min_cnt, max_cnt):
  """Converts a Haskell options to Python _Argument.

  @type kind: string
  @param kind: type generated by Common.hs/argComplToText; needs to be
      kept in sync

  """
  min_cnt = int(min_cnt)
  if max_cnt == "none":
    max_cnt = None
  else:
    max_cnt = int(max_cnt)
  # pylint: disable=W0142
  # since we pass **kwargs
  kwargs = {"min": min_cnt, "max": max_cnt}

  if kind.startswith("choices=") or kind.startswith("suggest="):
    (kind, choices) = kind.split("=", 1)
    kwargs["choices"] = choices.split(",")

  if kind not in _ARG_MAP:
    raise Exception("Unhandled argument kind '%s'" % kind)
  else:
    return _ARG_MAP[kind](**kwargs)
772 773


774 775
def ParseHaskellOptsArgs(script, output):
  """Computes list of options/arguments from help-completion output.
776 777 778

  """
  cli_opts = []
779
  cli_args = []
780
  for line in output.splitlines():
781 782 783 784 785 786 787 788 789 790 791 792 793 794
    v = line.split(None)
    exc = lambda msg: Exception("Invalid %s output from %s: %s" %
                                (msg, script, v))
    if len(v) < 2:
      raise exc("help completion")
    if v[0].startswith("-"):
      if len(v) != 2:
        raise exc("option format")
      (opts, kind) = v
      cli_opts.append(HaskellOptToOptParse(opts, kind))
    else:
      if len(v) != 3:
        raise exc("argument format")
      (kind, min_cnt, max_cnt) = v
795 796 797 798 799 800 801 802 803 804 805 806
      cli_args.append(HaskellArgToCliArg(kind, min_cnt, max_cnt))
  return (cli_opts, cli_args)


def WriteHaskellCompletion(sw, script, htools=True, debug=True):
  """Generates completion information for a Haskell program.

  This converts completion info from a Haskell program into 'fake'
  cli_opts and then builds completion for them.

  """
  if htools:
Iustin Pop's avatar
Iustin Pop committed
807
    cmd = "./src/htools"
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    env = {"HTOOLS": script}
    script_name = script
    func_name = "htools_%s" % script
  else:
    cmd = "./" + script
    env = {}
    script_name = os.path.basename(script)
    func_name = script_name
  func_name = GetFunctionName(func_name)
  output = utils.RunCmd([cmd, "--help-completion"], env=env, cwd=".").output
  (opts, args) = ParseHaskellOptsArgs(script_name, output)
  WriteCompletion(sw, script_name, func_name, debug, opts=opts, args=args)


def WriteHaskellCmdCompletion(sw, script, debug=True):
  """Generates completion information for a Haskell multi-command program.

  This gathers the list of commands from a Haskell program and
  computes the list of commands available, then builds the sub-command
  list of options/arguments for each command, using that for building
  a unified help output.

  """
  cmd = "./" + script
  script_name = os.path.basename(script)
  func_name = script_name
  func_name = GetFunctionName(func_name)
  output = utils.RunCmd([cmd, "--help-completion"], cwd=".").output
  commands = {}
  lines = output.splitlines()
  if len(lines) != 1:
    raise Exception("Invalid lines in multi-command mode: %s" % str(lines))
  v = lines[0].split(None)
  exc = lambda msg: Exception("Invalid %s output from %s: %s" %
                              (msg, script, v))
  if len(v) != 3:
    raise exc("help completion in multi-command mode")
  if not v[0].startswith("choices="):
    raise exc("invalid format in multi-command mode '%s'" % v[0])
  for subcmd in v[0][len("choices="):].split(","):
    output = utils.RunCmd([cmd, subcmd, "--help-completion"], cwd=".").output
    (opts, args) = ParseHaskellOptsArgs(script, output)
    commands[subcmd] = (None, args, opts, None, None)
  WriteCompletion(sw, script_name, func_name, debug, commands=commands)
852 853


854
def main():
855 856 857 858 859 860 861 862 863
  parser = optparse.OptionParser(usage="%prog [--compact]")
  parser.add_option("--compact", action="store_true",
                    help=("Don't indent output and don't include debugging"
                          " facilities"))

  options, args = parser.parse_args()
  if args:
    parser.error("Wrong number of arguments")

864 865 866
  # Whether to build debug version of completion script
  debug = not options.compact

867
  buf = StringIO()
868
  sw = utils.ShellWriter(buf, indent=debug)
869

870 871 872 873 874
  # Remember original state of extglob and enable it (required for pattern
  # matching; must be enabled while parsing script)
  sw.Write("gnt_shopt_extglob=$(shopt -p extglob || :)")
  sw.Write("shopt -s extglob")

875
  WritePreamble(sw, debug)
876 877

  # gnt-* scripts
878
  for scriptname in _constants.GNT_SCRIPTS:
879 880
    filename = "scripts/%s" % scriptname

881
    WriteCompletion(sw, scriptname, GetFunctionName(scriptname), debug,
882
                    commands=GetCommands(filename,
883
                                         build.LoadModule(filename)))
884 885

  # Burnin script
886
  WriteCompletion(sw, "%s/burnin" % pathutils.TOOLSDIR, "_ganeti_burnin",
887
                  debug,
888 889
                  opts=burnin.OPTIONS, args=burnin.ARGUMENTS)

890 891 892 893
  # ganeti-cleaner
  WriteHaskellCompletion(sw, "daemons/ganeti-cleaner", htools=False,
                         debug=not options.compact)

894 895 896
  # htools
  for script in _constants.HTOOLS_PROGS:
    WriteHaskellCompletion(sw, script, htools=True, debug=debug)
897

898
  # ganeti-confd, if enabled
899
  if _constants.ENABLE_CONFD:
Iustin Pop's avatar
Iustin Pop committed
900
    WriteHaskellCompletion(sw, "src/ganeti-confd", htools=False,
901
                           debug=debug)
902

903
  # mon-collector, if monitoring is enabled
904
  if _constants.ENABLE_MOND:
Iustin Pop's avatar
Iustin Pop committed
905
    WriteHaskellCmdCompletion(sw, "src/mon-collector", debug=debug)
906

907 908 909 910
  # Reset extglob to original value
  sw.Write("[[ -n \"$gnt_shopt_extglob\" ]] && $gnt_shopt_extglob")
  sw.Write("unset gnt_shopt_extglob")

911 912 913 914 915
  print buf.getvalue()


if __name__ == "__main__":
  main()