build-bash-completion 14.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/python
#

# Copyright (C) 2009 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


import optparse
import os
import sys
import re
from cStringIO import StringIO

from ganeti import constants
from ganeti import cli
from ganeti import utils

# _autoconf 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 _autoconf


class ShellWriter:
  """Helper class to write scripts with indentation.

  """
  INDENT_STR = "  "

  def __init__(self, fh):
    self._fh = fh
    self._indent = 0

  def IncIndent(self):
    """Increase indentation level by 1.

    """
    self._indent += 1

  def DecIndent(self):
    """Decrease indentation level by 1.

    """
    assert self._indent > 0
    self._indent -= 1

  def Write(self, txt, *args):
    """Write line to output file.

    """
    self._fh.write(self._indent * self.INDENT_STR)

    if args:
      self._fh.write(txt % args)
    else:
      self._fh.write(txt)

    self._fh.write("\n")


def WritePreamble(sw):
  """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.")

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

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

  sw.Write("_ganeti_jobs() {")
  sw.IncIndent()
  try:
    # FIXME: this is really going into the internals of the job queue
106
107
    sw.Write(("local jlist=$( shopt -s nullglob &&"
              " cd %s 2>/dev/null && echo job-* || : )"),
108
             utils.ShellQuote(constants.QUEUE_DIR))
109
    sw.Write('echo "${jlist//job-/}"')
110
111
112
113
  finally:
    sw.DecIndent()
  sw.Write("}")

114
115
116
117
118
119
120
121
122
123
124
125
126
127
  for (fnname, paths) in [
      ("os", constants.OS_SEARCH_PATH),
      ("iallocator", constants.IALLOCATOR_SEARCH_PATH),
      ]:
    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("}")
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187

  # 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("}")

  # 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("}")

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
  # Params: <long options with equal sign> <all options>
  # Result variable: $optcur
  sw.Write("_ganeti_checkopt() {")
  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")

    sw.Write("return 1")
  finally:
    sw.DecIndent()
  sw.Write("}")

214

215
216
def WriteCompReply(sw, args, cur="\"$cur\""):
  sw.Write("""COMPREPLY=( $(compgen %s -- %s) )""", args, cur)
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
  sw.Write("return")


class CompletionWriter:
  """Command completion writer class.

  """
  def __init__(self, arg_offset, opts, args):
    self.arg_offset = arg_offset
    self.opts = opts
    self.args = args

    for opt in opts:
      opt.all_names = sorted(opt._short_opts + opt._long_opts)

  def _FindFirstArgument(self, sw):
    ignore = []
    skip_one = []

    for opt in self.opts:
      if opt.takes_value():
        # Ignore value
        for i in opt.all_names:
240
241
          if i.startswith("--"):
            ignore.append("%s=*" % utils.ShellQuote(i))
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
          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)

      if not suggest:
        suggest = opt.choices

275
276
277
278
279
      if (isinstance(suggest, (int, long)) and
          suggest in cli.OPT_COMPL_ALL):
        key = suggest
      elif suggest:
        key = " ".join(sorted(suggest))
280
      else:
281
        key = ""
282

283
      values.setdefault(key, []).extend(opt.all_names)
284
285
286
287
288

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

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    cur = "\"$optcur\""

    wrote_opt = False

    for (suggest, allnames) in values.iteritems():
      longnames = [i for i in allnames if i.startswith("--")]

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

      sw.Write("%s _ganeti_checkopt %s %s; then", condcmd,
               utils.ShellQuote("|".join(["%s=*" % i for i in longnames])),
               utils.ShellQuote("|".join(allnames)))
      sw.IncIndent()
      try:
306
307
308
309
310
311
312
313
314
315
316
317
318
        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)
        elif suggest == cli.OPT_COMPL_ONE_IALLOCATOR:
          WriteCompReply(sw, "-W \"$(_ganeti_iallocator)\"", cur=cur)
        else:
          WriteCompReply(sw, "-W %s" % utils.ShellQuote(suggest), cur=cur)
319
320
321
322
323
324
325
326
327
      finally:
        sw.DecIndent()

      wrote_opt = True

    if wrote_opt:
      sw.Write("fi")

    return
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
  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

      # Write some debug comments
      for idx, arg in enumerate(self.args):
        sw.Write("# %s: %r", idx, arg)

      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)"
        elif isinstance(arg, cli.ArgJobId):
          choices = "$(_ganeti_jobs)"
        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
381
382
383
        elif isinstance(arg, cli.ArgHost):
          choices = ""
          compgenargs.append("-A hostname")
384
385
386
387
388
        else:
          raise Exception("Unknown argument type %r" % arg)

        if arg.min == 1 and arg.max == 1:
          cmpcode = """"$arg_idx" == %d""" % (last_arg_end)
389
        elif arg.min <= arg.max:
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
          cmpcode = (""""$arg_idx" -ge %d && "$arg_idx" -lt %d""" %
                     (last_arg_end, last_arg_end + arg.max))
        elif arg.max is None:
          cmpcode = """"$arg_idx" -ge %d""" % (last_arg_end)
        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:
              sw.Write("compgenargs=%s", utils.ShellQuote(" ".join(compgenargs)))
          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)


def WriteCompletion(sw, scriptname, funcname,
                    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

  """
  sw.Write("%s() {", funcname)
  sw.IncIndent()
  try:
450
    sw.Write("local "
451
             ' cur="${COMP_WORDS[COMP_CWORD]}"'
452
             ' prev="${COMP_WORDS[COMP_CWORD-1]}"'
453
             ' i first_arg_idx choices compgenargs arg_idx optcur')
454
455
456
457

    # Useful for debugging:
    #sw.Write("echo cur=\"$cur\" prev=\"$prev\"")
    #sw.Write("set | grep ^COMP_")
458
459
460
461
462
463
464
465
466
467
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

    sw.Write("COMPREPLY=()")

    if opts is not None and args is not None:
      assert not commands
      CompletionWriter(0, opts, args).WriteTo(sw)

    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")

      # We're doing options and arguments to commands
      sw.Write("""case "${COMP_WORDS[1]}" in""")
      for cmd, (_, argdef, optdef, _, _) in commands.iteritems():
        if not (argdef or optdef):
          continue

        # TODO: Group by arguments and options
        sw.Write("%s)", utils.ShellQuote(cmd))
        sw.IncIndent()
        try:
          CompletionWriter(1, optdef, argdef).WriteTo(sw)
        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")
  except AttributeError, err:
    raise Exception("Script %s doesn't have 'commands' attribute" %
                    filename)

  # Use aliases
  aliases = getattr(module, "aliases", {})
  if aliases:
    commands = commands.copy()
    for name, target in aliases.iteritems():
      commands[name] = commands[target]

  return commands


def main():
  buf = StringIO()
  sw = ShellWriter(buf)

  WritePreamble(sw)

  # gnt-* scripts
  for scriptname in _autoconf.GNT_SCRIPTS:
    filename = "scripts/%s" % scriptname

    WriteCompletion(sw, scriptname,
                    GetFunctionName(scriptname),
540
541
                    commands=GetCommands(filename,
                                         utils.LoadModule(filename)))
542
543

  # Burnin script
544
  burnin = utils.LoadModule("tools/burnin")
545
546
547
548
549
550
551
552
  WriteCompletion(sw, "%s/burnin" % constants.TOOLSDIR, "_ganeti_burnin",
                  opts=burnin.OPTIONS, args=burnin.ARGUMENTS)

  print buf.getvalue()


if __name__ == "__main__":
  main()