completion.py 15.6 KB
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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 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 381 382 383 384 385 386 387 388 389 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 450 451 452 453 454 455 456 457 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
# Copyright (C) 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Provides tab completion functionality for CLIs built with Fire."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import copy
import inspect

from fire import inspectutils
import six


def Script(name, component, default_options=None, shell='bash'):
  if shell == 'fish':
    return _FishScript(name, _Commands(component), default_options)
  return _BashScript(name, _Commands(component), default_options)


def _BashScript(name, commands, default_options=None):
  """Returns a Bash script registering a completion function for the commands.

  Args:
    name: The first token in the commands, also the name of the command.
    commands: A list of all possible commands that tab completion can complete
        to. Each command is a list or tuple of the string tokens that make up
        that command.
    default_options: A dict of options that can be used with any command. Use
        this if there are flags that can always be appended to a command.
  Returns:
    A string which is the Bash script. Source the bash script to enable tab
    completion in Bash.
  """
  default_options = default_options or set()
  global_options, options_map, subcommands_map = _GetMaps(
      name, commands, default_options
  )

  bash_completion_template = """# bash completion support for {name}
# DO NOT EDIT.
# This script is autogenerated by fire/completion.py.

_complete-{identifier}()
{{
  local cur prev opts lastcommand
  COMPREPLY=()
  prev="${{COMP_WORDS[COMP_CWORD-1]}}"
  cur="${{COMP_WORDS[COMP_CWORD]}}"
  lastcommand=$(get_lastcommand)

  opts="{default_options}"
  GLOBAL_OPTIONS="{global_options}"

{checks}

  COMPREPLY=( $(compgen -W "${{opts}}" -- ${{cur}}) )
  return 0
}}

get_lastcommand()
{{
  local lastcommand i

  lastcommand=
  for ((i=0; i < ${{#COMP_WORDS[@]}}; ++i)); do
    if [[ ${{COMP_WORDS[i]}} != -* ]] && [[ -n ${{COMP_WORDS[i]}} ]] && [[
      ${{COMP_WORDS[i]}} != $cur ]]; then
      lastcommand=${{COMP_WORDS[i]}}
    fi
  done

  echo $lastcommand
}}

filter_options()
{{
  local opts
  opts=""
  for opt in "$@"
  do
    if ! option_already_entered $opt; then
      opts="$opts $opt"
    fi
  done

  echo $opts
}}

option_already_entered()
{{
  local opt
  for opt in ${{COMP_WORDS[@]:0:COMP_CWORD}}
  do
    if [ $1 == $opt ]; then
      return 0
    fi
  done
  return 1
}}

is_prev_global()
{{
  local opt
  for opt in $GLOBAL_OPTIONS
  do
    if [ $opt == $prev ]; then
      return 0
    fi
  done
  return 1
}}

complete -F _complete-{identifier} {command}
"""

  check_wrapper = """
  case "${{lastcommand}}" in
  {lastcommand_checks}
  esac"""

  lastcommand_check_template = """
    {command})
      {opts_assignment}
      opts=$(filter_options $opts)
    ;;"""

  opts_assignment_subcommand_template = """
      if is_prev_global; then
        opts="${{GLOBAL_OPTIONS}}"
      else
        opts="{options} ${{GLOBAL_OPTIONS}}"
      fi"""

  opts_assignment_main_command_template = """
      opts="{options} ${{GLOBAL_OPTIONS}}" """

  def _GetOptsAssignmentTemplate(command):
    if command == name:
      return opts_assignment_main_command_template
    else:
      return opts_assignment_subcommand_template

  lines = []
  for command in set(subcommands_map.keys()).union(set(options_map.keys())):
    opts_assignment = _GetOptsAssignmentTemplate(command).format(
        options=' '.join(
            sorted(options_map[command].union(subcommands_map[command]))
        ),
    )
    lines.append(
        lastcommand_check_template.format(
            command=command,
            opts_assignment=opts_assignment)
    )
  lastcommand_checks = '\n'.join(lines)

  checks = check_wrapper.format(
      lastcommand_checks=lastcommand_checks,
  )

  return (
      bash_completion_template.format(
          name=name,
          command=name,
          checks=checks,
          default_options=' '.join(default_options),
          identifier=name.replace('/', '').replace('.', '').replace(',', ''),
          global_options=' '.join(global_options),
      )
  )


def _FishScript(name, commands, default_options=None):
  """Returns a Fish script registering a completion function for the commands.

  Args:
    name: The first token in the commands, also the name of the command.
    commands: A list of all possible commands that tab completion can complete
        to. Each command is a list or tuple of the string tokens that make up
        that command.
    default_options: A dict of options that can be used with any command. Use
        this if there are flags that can always be appended to a command.
  Returns:
    A string which is the Fish script. Source the fish script to enable tab
    completion in Fish.
  """
  default_options = default_options or set()
  global_options, options_map, subcommands_map = _GetMaps(
      name, commands, default_options
  )

  fish_source = """function __fish_using_command
    set cmd (commandline -opc)
    for i in (seq (count $cmd) 1)
        switch $cmd[$i]
        case "-*"
        case "*"
            if [ $cmd[$i] = $argv[1] ]
                return 0
            else
                return 1
            end
        end
    end
    return 1
end

function __option_entered_check
    set cmd (commandline -opc)
    for i in (seq (count $cmd))
        switch $cmd[$i]
        case "-*"
            if [ $cmd[$i] = $argv[1] ]
                return 1
            end
        end
    end
    return 0
end

function __is_prev_global
    set cmd (commandline -opc)
    set global_options {global_options}
    set prev (count $cmd)

    for opt in $global_options
        if [ "--$opt" = $cmd[$prev] ]
            echo $prev
            return 0
        end
    end
    return 1
end

"""

  subcommand_template = ("complete -c {name} -n '__fish_using_command "
                         "{command}' -f -a {subcommand}\n")
  flag_template = ("complete -c {name} -n "
                   "'__fish_using_command {command};{prev_global_check} and "
                   "__option_entered_check --{option}' -l {option}\n")

  prev_global_check = ' and __is_prev_global;'
  for command in set(subcommands_map.keys()).union(set(options_map.keys())):
    for subcommand in subcommands_map[command]:
      fish_source += subcommand_template.format(
          name=name,
          command=command,
          subcommand=subcommand,
      )

    for option in options_map[command].union(global_options):
      check_needed = command != name
      fish_source += flag_template.format(
          name=name,
          command=command,
          prev_global_check=prev_global_check if check_needed else '',
          option=option.lstrip('--'),
      )

  return fish_source.format(
      global_options=' '.join(
          '"{option}"'.format(option=option)
          for option in global_options
      )
  )


def MemberVisible(component, name, member, class_attrs=None, verbose=False):
  """Returns whether a member should be included in auto-completion or help.

  Determines whether a member of an object with the specified name should be
  included in auto-completion or help text(both usage and detailed help).

  If the member name starts with '__', it will always be excluded. If it
  starts with only one '_', it will be included for all non-string types. If
  verbose is True, the members, including the private members, are included.

  When not in verbose mode, some modules and functions are excluded as well.

  Args:
    component: The component containing the member.
    name: The name of the member.
    member: The member itself.
    class_attrs: (optional) If component is a class, provide this as:
      inspectutils.GetClassAttrsDict(component). If not provided, it will be
      computed.
    verbose: Whether to include private members.
  Returns
    A boolean value indicating whether the member should be included.
  """
  if isinstance(name, six.string_types) and name.startswith('__'):
    return False
  if verbose:
    return True
  if member in (absolute_import, division, print_function):
    return False
  if isinstance(member, type(absolute_import)) and six.PY34:
    return False
  if inspect.ismodule(member) and member is six:
    # TODO(dbieber): Determine more generally which modules to hide.
    return False
  if inspect.isclass(component):
    # If class_attrs has not been provided, compute it.
    if class_attrs is None:
      class_attrs = inspectutils.GetClassAttrsDict(class_attrs) or {}
    class_attr = class_attrs.get(name)
    if class_attr and class_attr.kind in ('method', 'property'):
      # methods and properties should be accessed on instantiated objects,
      # not uninstantiated classes.
      return False
  if (six.PY2 and inspect.isfunction(component)
      and name in ('func_closure', 'func_code', 'func_defaults',
                   'func_dict', 'func_doc', 'func_globals', 'func_name')):
    return False
  if (six.PY2 and inspect.ismethod(component)
      and name in ('im_class', 'im_func', 'im_self')):
    return False
  if isinstance(name, six.string_types):
    return not name.startswith('_')
  return True  # Default to including the member


def VisibleMembers(component, class_attrs=None, verbose=False):
  """Returns a list of the members of the given component.

  If verbose is True, then members starting with _ (normally ignored) are
  included.

  Args:
    component: The component whose members to list.
    class_attrs: (optional) If component is a class, you may provide this as:
      inspectutils.GetClassAttrsDict(component). If not provided, it will be
      computed. If provided, this determines how class members will be treated
      for visibility. In particular, methods are generally hidden for
      non-instantiated classes, but if you wish them to be shown (e.g. for
      completion scripts) then pass in a different class_attr for them.
    verbose: Whether to include private members.
  Returns:
    A list of tuples (member_name, member) of all members of the component.
  """
  if isinstance(component, dict):
    members = component.items()
  else:
    members = inspect.getmembers(component)

  # If class_attrs has not been provided, compute it.
  if class_attrs is None:
    class_attrs = inspectutils.GetClassAttrsDict(component)
  return [
      (member_name, member) for member_name, member in members
      if MemberVisible(component, member_name, member, class_attrs=class_attrs,
                       verbose=verbose)
  ]


def _CompletionsFromArgs(fn_args):
  """Takes a list of fn args and returns a list of the fn's completion strings.

  Args:
    fn_args: A list of the args accepted by a function.
  Returns:
    A list of possible completion strings for that function.
  """
  completions = []
  for arg in fn_args:
    arg = arg.replace('_', '-')
    completions.append('--{arg}'.format(arg=arg))
  return completions


def Completions(component, verbose=False):
  """Gives possible Fire command completions for the component.

  A completion is a string that can be appended to a command to continue that
  command. These are used for TAB-completions in Bash for Fire CLIs.

  Args:
    component: The component whose completions to list.
    verbose: Whether to include all completions, even private members.
  Returns:
    A list of completions for a command that would so far return the component.
  """
  if inspect.isroutine(component) or inspect.isclass(component):
    spec = inspectutils.GetFullArgSpec(component)
    return _CompletionsFromArgs(spec.args + spec.kwonlyargs)

  if isinstance(component, (tuple, list)):
    return [str(index) for index in range(len(component))]

  if inspect.isgenerator(component):
    # TODO(dbieber): There are currently no commands available for generators.
    return []

  return [
      _FormatForCommand(member_name)
      for member_name, _ in VisibleMembers(component, verbose=verbose)
  ]


def _FormatForCommand(token):
  """Replaces underscores with hyphens, unless the token starts with a token.

  This is because we typically prefer hyphens to underscores at the command
  line, but we reserve hyphens at the start of a token for flags. This becomes
  relevant when --verbose is activated, so that things like __str__ don't get
  transformed into --str--, which would get confused for a flag.

  Args:
    token: The token to transform.
  Returns:
    The transformed token.
  """
  if not isinstance(token, six.string_types):
    token = str(token)

  if token.startswith('_'):
    return token

  return token.replace('_', '-')


def _Commands(component, depth=3):
  """Yields tuples representing commands.

  To use the command from Python, insert '.' between each element of the tuple.
  To use the command from the command line, insert ' ' between each element of
  the tuple.

  Args:
    component: The component considered to be the root of the yielded commands.
    depth: The maximum depth with which to traverse the member DAG for commands.
  Yields:
    Tuples, each tuple representing one possible command for this CLI.
    Only traverses the member DAG up to a depth of depth.
  """
  if inspect.isroutine(component) or inspect.isclass(component):
    for completion in Completions(component, verbose=False):
      yield (completion,)
  if inspect.isroutine(component):
    return  # Don't descend into routines.

  if depth < 1:
    return

  # By setting class_attrs={} we don't hide methods in completion.
  for member_name, member in VisibleMembers(component, class_attrs={},
                                            verbose=False):
    # TODO(dbieber): Also skip components we've already seen.
    member_name = _FormatForCommand(member_name)

    yield (member_name,)

    for command in _Commands(member, depth - 1):
      yield (member_name,) + command


def _IsOption(arg):
  return arg.startswith('-')


def _GetMaps(name, commands, default_options):
  """Returns sets of subcommands and options for each command.

  Args:
    name: The first token in the commands, also the name of the command.
    commands: A list of all possible commands that tab completion can complete
        to. Each command is a list or tuple of the string tokens that make up
        that command.
    default_options: A dict of options that can be used with any command. Use
        this if there are flags that can always be appended to a command.
  Returns:
    global_options: A set of all options of the first token of the command.
    subcommands_map: A dict storing set of subcommands for each
        command/subcommand.
    options_map: A dict storing set of options for each subcommand.
  """
  global_options = copy.copy(default_options)
  options_map = collections.defaultdict(lambda: copy.copy(default_options))
  subcommands_map = collections.defaultdict(set)

  for command in commands:
    if len(command) == 1:
      if _IsOption(command[0]):
        global_options.add(command[0])
      else:
        subcommands_map[name].add(command[0])

    elif command:
      subcommand = command[-2]
      arg = _FormatForCommand(command[-1])

      if _IsOption(arg):
        args_map = options_map
      else:
        args_map = subcommands_map

      args_map[subcommand].add(arg)
      args_map[subcommand.replace('_', '-')].add(arg)

  return global_options, options_map, subcommands_map