Exemple #1
0
  def CommandGetHelp(self, unused_argv, cmd_names=None):
    """Get help for command.

    Args:
      unused_argv: Remaining command line flags and arguments after parsing
                   command (that is a copy of sys.argv at the time of the
                   function call with all parsed flags removed); unused in this
                   implementation.
      cmd_names:   By default, if help is being shown for more than one command,
                   and this command defines _all_commands_help, then
                   _all_commands_help will be displayed instead of the class
                   doc. cmd_names is used to determine the number of commands
                   being displayed and if only a single command is display then
                   the class doc is returned.

    Returns:
      __doc__ property for command function or a message stating there is no
      help.
    """
    if (type(cmd_names) is list and len(cmd_names) > 1 and
        self._all_commands_help is not None):
      return flags.DocToHelp(self._all_commands_help)
    if self._cmd_func.__doc__ is not None:
      return flags.DocToHelp(self._cmd_func.__doc__)
    else:
      return 'No help available'
Exemple #2
0
  def CommandGetHelp(self, unused_argv, cmd_names=None):
    """Get help string for command.

    Args:
      unused_argv: Remaining command line flags and arguments after parsing
                   command (that is a copy of sys.argv at the time of the
                   function call with all parsed flags removed); unused in this
                   default implementation, but may be used in subclasses.
      cmd_names:   Complete list of commands for which help is being shown at
                   the same time. This is used to determine whether to return
                   _all_commands_help, or the command's docstring.
                   (_all_commands_help is used, if not None, when help is being
                   shown for more than one command, otherwise the command's
                   docstring is used.)

    Returns:
      Help string, one of the following (by order):
        - Result of the registered 'help' function (if any)
        - Doc string of the Cmd class (if any)
        - Default fallback string
    """
    if (type(cmd_names) is list and len(cmd_names) > 1 and
        self._all_commands_help is not None):
      return flags.DocToHelp(self._all_commands_help)
    elif self.__doc__:
      return flags.DocToHelp(self.__doc__)
    else:
      return 'No help available'
Exemple #3
0
    def testDocToHelp_FlagValues(self):
        # !!!!!!!!!!!!!!!!!!!!
        # The following doc string is taken as is directly from gflags.py:FlagValues
        # The intention of this test is to verify 'live' performance
        # !!!!!!!!!!!!!!!!!!!!
        """Used as a registry for 'Flag' objects.

    A 'FlagValues' can then scan command line arguments, passing flag
    arguments through to the 'Flag' objects that it owns.  It also
    provides easy access to the flag values.  Typically only one
    'FlagValues' object is needed by an application:  gflags.FLAGS

    This class is heavily overloaded:

    'Flag' objects are registered via __setitem__:
         FLAGS['longname'] = x   # register a new flag

    The .value member of the registered 'Flag' objects can be accessed as
    members of this 'FlagValues' object, through __getattr__.  Both the
    long and short name of the original 'Flag' objects can be used to
    access its value:
         FLAGS.longname          # parsed flag value
         FLAGS.x                 # parsed flag value (short name)

    Command line arguments are scanned and passed to the registered 'Flag'
    objects through the __call__ method.  Unparsed arguments, including
    argv[0] (e.g. the program name) are returned.
         argv = FLAGS(sys.argv)  # scan command line arguments

    The original registered Flag objects can be retrieved through the use
    """
        doc = gflags.DocToHelp(self.testDocToHelp_FlagValues.__doc__)
        # Test the general outline of the converted docs
        lines = doc.splitlines()
        self.assertEqual(17, len(lines))
        empty_lines = [
            index for index in range(len(lines)) if not lines[index]
        ]
        self.assertEqual([1, 3, 5, 8, 12, 15], empty_lines)
        # test that some starting prefix is kept
        flags_lines = [
            index for index in range(len(lines))
            if lines[index].startswith('     FLAGS')
        ]
        self.assertEqual([7, 10, 11], flags_lines)
        # but other, especially common space has been removed
        space_lines = [
            index for index in range(len(lines))
            if lines[index] and lines[index][0].isspace()
        ]
        self.assertEqual([7, 10, 11, 14], space_lines)
        # No right space was kept
        rspace_lines = [
            index for index in range(len(lines))
            if lines[index] != lines[index].rstrip()
        ]
        self.assertEqual([], rspace_lines)
        # test double spaces are kept
        self.assertEqual(True, lines[2].endswith('application:  gflags.FLAGS'))
Exemple #4
0
 def CommandGetHelp(self, unused_argv, cmd_names=None):
   """Returns: Help for command."""
   cmd_help = ('Help for all or selected command:\n'
               '\t%(prog)s help [<command>]\n\n'
               'To retrieve help with global flags:\n'
               '\t%(prog)s --help\n\n'
               'To retrieve help with flags only from the main module:\n'
               '\t%(prog)s --helpshort [<command>]\n\n'
               % {'prog': GetAppBasename()})
   return flags.DocToHelp(cmd_help)
Exemple #5
0
def usage(shorthelp=0, writeto_stdout=0, detailed_error=None, exitcode=None):
    """Write __main__'s docstring to stderr with some help text.

  Args:
    shorthelp: print only flags from this module, rather than all flags.
    writeto_stdout: write help message to stdout, rather than to stderr.
    detailed_error: additional detail about why usage info was presented.
    exitcode: if set, exit with this status code after writing help.
  """
    if writeto_stdout:
        stdfile = sys.stdout
    else:
        stdfile = sys.stderr

    doc = sys.modules['__main__'].__doc__
    if not doc:
        doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
        doc = flags.TextWrap(doc, indent='       ', firstline_indent='')
    else:
        # Replace all '%s' with sys.argv[0], and all '%%' with '%'.
        num_specifiers = doc.count('%') - 2 * doc.count('%%')
        try:
            doc %= (sys.argv[0], ) * num_specifiers
        except (OverflowError, TypeError, ValueError):
            # Just display the docstring as-is.
            pass
        if help_text_wrap:
            doc = flags.TextWrap(flags.DocToHelp(doc))
    if shorthelp:
        flag_str = FLAGS.MainModuleHelp()
    else:
        flag_str = str(FLAGS)
    try:
        stdfile.write(doc)
        if flag_str:
            stdfile.write('\nflags:\n')
            stdfile.write(flag_str)
        stdfile.write('\n')
        if detailed_error is not None:
            stdfile.write('\n%s\n' % detailed_error)
    except IOError as e:
        # We avoid printing a huge backtrace if we get EPIPE, because
        # "foo.par --help | less" is a frequent use case.
        if e.errno != errno.EPIPE:
            raise
    if exitcode is not None:
        sys.exit(exitcode)
Exemple #6
0
def main():
    args = FLAGS(sys.argv)[1:]
    if FLAGS.version:
        print('Immaculater CLI Version %s' % __version__)
        sys.exit(0)
    if FLAGS.help:
        doc = sys.modules[_get_username_and_password.__module__].__doc__
        help_msg = flags.DocToHelp(doc.replace('%s', sys.argv[0]))
        _print(flags.TextWrap(help_msg, flags.GetHelpWidth()))
        _print('\n')
        _print(FLAGS.GetHelp())
        sys.exit(0)
    username, password = _get_username_and_password()
    if not args:
        _repl(username=username, password=password)
        sys.exit(0)
    if FLAGS.single_command:
        args = [u' '.join(pipes.quote(x) for x in args)]
    sys.exit(_handle_commands(args, username=username, password=password))
Exemple #7
0
def AppcommandsUsage(shorthelp=0, writeto_stdout=0, detailed_error=None,
                     exitcode=None, show_cmd=None, show_global_flags=False):
  """Output usage or help information.

  Extracts the __doc__ string from the __main__ module and writes it to
  stderr. If that string contains a '%s' then that is replaced by the command
  pathname. Otherwise a default usage string is being generated.

  The output varies depending on the following:
  - FLAGS.help
  - FLAGS.helpshort
  - show_cmd
  - show_global_flags

  Args:
    shorthelp:      print only command and main module flags, rather than all.
    writeto_stdout: write help message to stdout, rather than to stderr.
    detailed_error: additional details about why usage info was presented.
    exitcode:       if set, exit with this status code after writing help.
    show_cmd:       show help for this command only (name of command).
    show_global_flags: show help for global flags.
  """
  if writeto_stdout:
    stdfile = sys.stdout
  else:
    stdfile = sys.stderr

  prefix = ''.rjust(GetMaxCommandLength() + 2)
  # Deal with header, containing general tool documentation
  doc = sys.modules['__main__'].__doc__
  if doc:
    help_msg = flags.DocToHelp(doc.replace('%s', sys.argv[0]))
    stdfile.write(flags.TextWrap(help_msg, flags.GetHelpWidth()))
    stdfile.write('\n\n\n')
  if not doc or doc.find('%s') == -1:
    synopsis = 'USAGE: ' + GetSynopsis()
    stdfile.write(flags.TextWrap(synopsis, flags.GetHelpWidth(), '       ',
                                 ''))
    stdfile.write('\n\n\n')
  # Special case just 'help' registered, that means run as 'tool --help'.
  if len(GetCommandList()) == 1:
    cmd_names = []
  else:
    # Show list of commands
    if show_cmd is None or show_cmd == 'help':
      cmd_names = GetCommandList().keys()
      cmd_names.sort()
      stdfile.write('Any of the following commands:\n')
      doc = ', '.join(cmd_names)
      stdfile.write(flags.TextWrap(doc, flags.GetHelpWidth(), '  '))
      stdfile.write('\n\n\n')
    # Prepare list of commands to show help for
    if show_cmd is not None:
      cmd_names = [show_cmd]  # show only one command
    elif FLAGS.help or FLAGS.helpshort or shorthelp:
      cmd_names = []
    else:
      cmd_names = GetCommandList().keys()  # show all commands
      cmd_names.sort()
  # Show the command help (none, one specific, or all)
  for name in cmd_names:
    command = GetCommandByName(name)
    try:
      cmd_help = command.CommandGetHelp(GetCommandArgv(), cmd_names=cmd_names)
    except Exception as error:
      cmd_help = "Internal error for command '%s': %s." % (name, str(error))
    cmd_help = cmd_help.strip()
    all_names = ', '.join([name] + (command.CommandGetAliases() or []))
    if len(all_names) + 1 >= len(prefix) or not cmd_help:
      # If command/alias list would reach over help block-indent
      # start the help block on a new line.
      stdfile.write(flags.TextWrap(all_names, flags.GetHelpWidth()))
      stdfile.write('\n')
      prefix1 = prefix
    else:
      prefix1 = all_names.ljust(GetMaxCommandLength() + 2)
    if cmd_help:
      stdfile.write(flags.TextWrap(cmd_help, flags.GetHelpWidth(), prefix,
                                   prefix1))
      stdfile.write('\n\n')
    else:
      stdfile.write('\n')
    # When showing help for exactly one command we show its flags
    if len(cmd_names) == 1:
      # Need to register flags for command prior to be able to use them.
      # We do not register them globally so that they do not reappear.
      # pylint: disable=protected-access
      cmd_flags = command._command_flags
      if cmd_flags.RegisteredFlags():
        stdfile.write('%sFlags for %s:\n' % (prefix, name))
        stdfile.write(cmd_flags.GetHelp(prefix+'  '))
        stdfile.write('\n\n')
  stdfile.write('\n')
  # Now show global flags as asked for
  if show_global_flags:
    stdfile.write('Global flags:\n')
    if shorthelp:
      stdfile.write(FLAGS.MainModuleHelp())
    else:
      stdfile.write(FLAGS.GetHelp())
    stdfile.write('\n')
  else:
    stdfile.write("Run '%s --help' to get help for global flags."
                  % GetAppBasename())
  stdfile.write('\n%s\n' % _UsageFooter(detailed_error, cmd_names))
  if exitcode is not None:
    sys.exit(exitcode)
Exemple #8
0
 def testDocToHelp(self):
     self.assertEqual('', gflags.DocToHelp('  '))
     self.assertEqual('', gflags.DocToHelp('  \n  '))
     self.assertEqual('a\n\nb', gflags.DocToHelp('a\n  \nb'))
     self.assertEqual('a\n\n\nb', gflags.DocToHelp('a\n  \n  \nb'))
     self.assertEqual('a b', gflags.DocToHelp('  a\nb  '))
     self.assertEqual('a b', gflags.DocToHelp('\na\nb\n'))
     self.assertEqual('a\n\nb', gflags.DocToHelp('\na\n\nb\n'))
     self.assertEqual('a b', gflags.DocToHelp('  \na\nb\n  '))
     # Different first line, one line empty - erm double new line.
     self.assertEqual('a b c\n\nd', gflags.DocToHelp('a\n  b\n  c\n\n  d'))
     self.assertEqual('a b\n      c d',
                      gflags.DocToHelp('a\n  b\n  \tc\n  d'))
     self.assertEqual('a b\n      c\n      d',
                      gflags.DocToHelp('a\n  b\n  \tc\n  \td'))