command-line-like option completion -- options with values
558852
private static CompletionProvider optionCompletion(CompletionProvider provider) {
        return (code, cursor, anchor) -> {
            Matcher ovm = OPTION_VALUE_PATTERN.matcher(code);
            if (ovm.matches()) {
                String flag = ovm.group("flag");
                List<CompletionProvider> ps = ARG_OPTIONS.entrySet().stream()
                        .filter(es -> es.getKey().startsWith(flag))
                        .map(es -> es.getValue())
                        .collect(toList());
                if (ps.size() == 1) {
                    int pastSpace = ovm.start("val");
                    List<Suggestion> result = ps.get(0).completionSuggestions(
                            ovm.group("val"), cursor - pastSpace, anchor);
                    anchor[0] += pastSpace;
                    return result;
                }
            }
            Matcher om = OPTION_PATTERN.matcher(code);
            if (om.matches()) {
                int pastSpace = om.start("flag");
                List<Suggestion> result = provider.completionSuggestions(
                        om.group("flag"), cursor - pastSpace, anchor);
                if (!om.group("dd").isEmpty()) {
                    result = result.stream()
                            .map(sug -> new Suggestion() {
                                @Override
                                public String continuation() {
                                    return "-" + sug.continuation();
                                }

                                @Override
                                public boolean matchesType() {
                                    return false;
                                }
                            })
                            .collect(toList());
                    --pastSpace;
                }
                anchor[0] += pastSpace;
                return result;
            }
            Matcher opp = OPTION_PRE_PATTERN.matcher(code);
            if (opp.matches()) {
                int pastSpace = opp.end();
                List<Suggestion> result = provider.completionSuggestions(
                        "", cursor - pastSpace, anchor);
                anchor[0] += pastSpace;
                return result;
            }
            return Collections.emptyList();
        };
    }
649253
def common_cli_output_options(f):
    """"""

    @click.option(
        "-d",
        "--debug",
        default=False,
        is_flag=True,
        help="Produce debug output during processing.",
    )
    @click.option(
        "-F",
        "--output-format",
        default="pretty",
        type=click.Choice(["pretty", "json", "pretty_json"]),
        help="Determines how output is formatted. This is only supported by a "
        "subset of the commands at the moment (e.g. list).",
    )
    @click.option(
        "-v",
        "--verbose",
        is_flag=True,
        default=False,
        help="Produce more output during processing.",
    )
    @click.pass_context
    @functools.wraps(f)
    def wrapper(ctx, *args, **kwargs):
        # pylint: disable=missing-docstring
        opts = config.get_or_create_options(ctx)
        opts.debug = kwargs.pop("debug")
        opts.output = kwargs.pop("output_format")
        opts.verbose = kwargs.pop("verbose")
        kwargs["opts"] = opts
        return ctx.invoke(f, *args, **kwargs)

    return wrapper
1332181
def parse_args(self, flags, namespace):
    """"""
    flag_value_map = self._create_flag_value_map(flags)

    mutex_map = defaultdict(list)
    for args, kwargs in self._unnormalized_option_registrations_iter():
      self._validate(args, kwargs)
      dest = self.parse_dest(*args, **kwargs)

      # Compute the values provided on the command line for this option.  Note that there may be
      # multiple values, for any combination of the following reasons:
      #   - The user used the same flag multiple times.
      #   - The user specified a boolean flag (--foo) and its inverse (--no-foo).
      #   - The option has multiple names, and the user used more than one of them.
      #
      # We also check if the option is deprecated, but we only do so if the option is explicitly
      # specified as a command-line flag, so we don't spam users with deprecated option values
      # specified in config, which isn't something they control.
      implicit_value = kwargs.get('implicit_value')
      if implicit_value is None and kwargs.get('type') == bool:
        implicit_value = True  # Allows --foo to mean --foo=true.

      flag_vals = []

      def add_flag_val(v):
        if v is None:
          if implicit_value is None:
            raise ParseError('Missing value for command line flag {} in {}'.format(
              arg, self._scope_str()))
          else:
            flag_vals.append(implicit_value)
        else:
          flag_vals.append(v)

      for arg in args:
        # If the user specified --no-foo on the cmd line, treat it as if the user specified
        # --foo, but with the inverse value.
        if kwargs.get('type') == bool:
          inverse_arg = self._inverse_arg(arg)
          if inverse_arg in flag_value_map:
            flag_value_map[arg] = [self._invert(v) for v in flag_value_map[inverse_arg]]
            implicit_value = self._invert(implicit_value)
            del flag_value_map[inverse_arg]

        if arg in flag_value_map:
          for v in flag_value_map[arg]:
            add_flag_val(v)
          del flag_value_map[arg]

      # Get the value for this option, falling back to defaults as needed.
      try:
        val = self._compute_value(dest, kwargs, flag_vals)
      except ParseError as e:
        # Reraise a new exception with context on the option being processed at the time of error.
        # Note that other exception types can be raised here that are caught by ParseError (e.g.
        # BooleanConversionError), hence we reference the original exception type as type(e).
        raise type(e)(
          'Error computing value for {} in {} (may also be from PANTS_* environment variables).'
          '\nCaused by:\n{}'.format(', '.join(args), self._scope_str(), traceback.format_exc())
        )

      # If the option is explicitly given, check deprecation and mutual exclusion.
      if val.rank > RankedValue.HARDCODED:
        self._check_deprecated(dest, kwargs)

        mutex_dest = kwargs.get('mutually_exclusive_group')
        if mutex_dest:
          mutex_map[mutex_dest].append(dest)
          dest = mutex_dest
        else:
          mutex_map[dest].append(dest)

        if len(mutex_map[dest]) > 1:
          raise self.MutuallyExclusiveOptionError(
            "Can only provide one of the mutually exclusive options {}".format(mutex_map[dest]))

      setattr(namespace, dest, val)

    # See if there are any unconsumed flags remaining.
    if flag_value_map:
      raise ParseError('Unrecognized command line flags on {}: {}'.format(
        self._scope_str(), ', '.join(flag_value_map.keys())))

    return namespace
376888
function getOptions(conf) {
  var parts = [];
  if(!conf.expansions && !conf.flags) {
    return parts;
  }
  var start = conf.start, end = conf.end;
  var sre = /^-[a-zA-Z0-9]$/, lre = /^--/;
  var chars = '';
  var lng = [];
  var opts = this.cmd._options, z, arg, names, i, options = [];
  for(z in opts) {
    arg = opts[z];
    if(arg.isFlag()) {
      names = arg.names();
      for(i = 0;i < names.length;i++) {
        if(conf.expansions && sre.test(names[i])) {
          chars += names[i].substr(1);
        }else if(conf.flags && !conf.combine && lre.test(names[i])) {
          lng.push(start + names[i] + end);
        }
      }
      if(conf.combine) {
        if(conf.no) {
          names = flutil.getNoExpansions(names);
        }
        lng.push(start + names.join('|') + end);
      }
    }else if(arg.isOption()){
      if(conf.options) {
        options.push(start + getOptionValue(arg, conf) + end);
      }
    }
  }
  var expansions = chars.length ? start + HYPHEN + chars + end : '';
  var commands = Object.keys(this.cmd._commands).length > 0;
  if(commands && conf.command && conf.prepend) {
    parts.push(conf.scommand
      + this.messages.usage.command + conf.ecommand);
  }
  if(expansions) {
    parts.push(expansions);
  }
  if(lng.length) {
    parts.push(lng.join(' '));
  }
  if(options.length) {
    parts.push(options.join(' '));
  }
  if(commands && conf.command && !conf.prepend) {
    parts.push(conf.scommand
      + this.messages.usage.command + conf.ecommand);
  }
  if(conf.args) {
    parts.push(conf.sargs
      + this.messages.usage.args + conf.eargs);
  }
  return parts;
}
1109320
def autocomplete():
    
    # Don't complete if user hasn't sourced bash_completion file.
    if 'PIP_AUTO_COMPLETE' not in os.environ:
        return
    cwords = os.environ['COMP_WORDS'].split()[1:]
    cword = int(os.environ['COMP_CWORD'])
    try:
        current = cwords[cword - 1]
    except IndexError:
        current = ''

    subcommands = [cmd for cmd, summary in get_summaries()]
    options = []
    # subcommand
    try:
        subcommand_name = [w for w in cwords if w in subcommands][0]
    except IndexError:
        subcommand_name = None

    parser = create_main_parser()
    # subcommand options
    if subcommand_name:
        # special case: 'help' subcommand has no options
        if subcommand_name == 'help':
            sys.exit(1)
        # special case: list locally installed dists for show and uninstall
        should_list_installed = (
            subcommand_name in ['show', 'uninstall'] and
            not current.startswith('-')
        )
        if should_list_installed:
            installed = []
            lc = current.lower()
            for dist in get_installed_distributions(local_only=True):
                if dist.key.startswith(lc) and dist.key not in cwords[1:]:
                    installed.append(dist.key)
            # if there are no dists installed, fall back to option completion
            if installed:
                for dist in installed:
                    print(dist)
                sys.exit(1)

        subcommand = commands_dict[subcommand_name]()

        for opt in subcommand.parser.option_list_all:
            if opt.help != optparse.SUPPRESS_HELP:
                for opt_str in opt._long_opts + opt._short_opts:
                    options.append((opt_str, opt.nargs))

        # filter out previously specified options from available options
        prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
        options = [(x, v) for (x, v) in options if x not in prev_opts]
        # filter options by current input
        options = [(k, v) for k, v in options if k.startswith(current)]
        # get completion type given cwords and available subcommand options
        completion_type = get_path_completion_type(
            cwords, cword, subcommand.parser.option_list_all,
        )
        # get completion files and directories if ``completion_type`` is
        # ``<file>``, ``<dir>`` or ``<path>``
        if completion_type:
            options = auto_complete_paths(current, completion_type)
            options = ((opt, 0) for opt in options)
        for option in options:
            opt_label = option[0]
            # append '=' to options which require args
            if option[1] and option[0][:2] == "--":
                opt_label += '='
            print(opt_label)
    else:
        # show main parser options only when necessary

        opts = [i.option_list for i in parser.option_groups]
        opts.append(parser.option_list)
        opts = (o for it in opts for o in it)
        if current.startswith('-'):
            for opt in opts:
                if opt.help != optparse.SUPPRESS_HELP:
                    subcommands += opt._long_opts + opt._short_opts
        else:
            # get completion type given cwords and all available options
            completion_type = get_path_completion_type(cwords, cword, opts)
            if completion_type:
                subcommands = auto_complete_paths(current, completion_type)

        print(' '.join([x for x in subcommands if x.startswith(current)]))
    sys.exit(1)
1262268
function(option, values) {

      // Start an opts collector
      var opts = [];

      // Add in ignores if they exist
      if (!_.isEmpty(values)) {
        _.forEach(values, function(value) {
          opts.push(option);
          opts.push(value);
        });
      }

      // Return as common deliminated string
      return opts.join(';');

    }
891849
def _PreParse(self, key, value):
        """"""
        if key == "Command":
            return re.sub(r"(\[\[.+?\]\])", self._Completion, value)
        else:
            return value
685454
def command_with_options(self):
        """"""
        if 'args' in self.config:
            return ' '.join((self.command, self.config['args']))
        return self.command
148172
def shell_config_cmd(argv):
    ""
    shell = supported_shell()
    if shell:
        print(pew_site / 'shell_config' / ('init.' + shell))
    else:
        err('Completions and prompts are unavailable for %s' %
            repr(os.environ.get('SHELL', '')))
406998
def argument(value, options = {})
      return unless @shell.applicable?(options)
      value = value.to_s
      if @shell.requires_escaping?(value)
        value = @shell.escape_value(value)
      end
      @command << ' ' << value
      @last_arg = :argument
    end
928484
def to_args(self):
        
        def has_value(name, value):
            """ Test for non-null option values.
            """
            null_values = ("False", "None", "[]", '""', "''", "0")
            if not value or value in null_values:
                return False
            if name in _arg_defaults:
                if str(value) == str(_arg_defaults[name]):
                    return False
            return True

        def filter_opt(name, value):
            """ Filter out preset and null-valued options.
            """
            if name in ("add_preset", "del_preset", "desc", "note"):
                return False
            return has_value(name, value)

        def argify(name, value):
            """ Convert sos option notation to command line arguments.
            """
            # Handle --verbosity specially
            if name.startswith("verbosity"):
                arg = "-" + int(value) * "v"
                return arg

            name = name.replace("_", "-")

            value = ",".join(value) if _is_seq(value) else value

            if value is not True:
                opt = "%s %s" % (name, value)
            else:
                opt = name

            arg = "--" + opt if len(opt) > 1 else "-" + opt
            return arg

        opt_items = sorted(self.dict().items(), key=lambda x: x[0])
        return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)]
805804
def _opt_to_args(cls, opt, val):
        
        no_value = (
            "alloptions", "all-logs", "batch", "build", "debug",
            "experimental", "list-plugins", "list-presets", "list-profiles",
            "noreport", "quiet", "verify"
        )
        count = ("verbose",)
        if opt in no_value:
            return ["--%s" % opt]
        if opt in count:
            return ["--%s" % opt for d in range(0, int(val))]
        return ["--" + opt + "=" + val]
160544
def configured_options(self):
        """"""
        stdout_lines = self._check_output(['config', '--list']).splitlines()
        return {key: value for key, value in [line.split('=') for line in stdout_lines]}
1165492
def get_complete(command):
    

    assert isinstance(command, click.Command)

    def complete_(self, text, line, begidx, endidx):  # pylint: disable=unused-argument
        # Parse the args
        args = shlex.split(line[:begidx])
        # Strip of the first item which is the name of the command
        args = args[1:]

        # Then pass them on to the get_choices method that click uses for completion
        return list(get_choices(command, command.name, args, text))

    complete_.__name__ = 'complete_%s' % command.name
    return complete_
511075
def _fetch_options(self, merge):
        """"""
        cmd = tuple()
        for option in FETCH_DEFAULTS:
            value = merge.get(option, self.defaults.get(option))
            if value:
                cmd += ("--%s" % option, str(value))
        return cmd
1225964
function(start, end, options) {
    var values = [], i;
    for (i = start; i < end; i++) {
      if (options && options.skip) {
        if (i % options.skip === 0) {
          values.push(i);
        } else {
          values.push(undefined);
        }
      } else {
        values.push(i);
      }
    }
    return values;
  }
852828
def _complete_exit(self, cmd, args, text):
        """"""
        if args:
            return
        return [ x for x in { 'root', 'all', } \
                if x.startswith(text) ]