def test_get_help_width(self):
     """Verify that get_help_width() reflects _help_width."""
     default_help_width = _helpers._DEFAULT_HELP_WIDTH  # Save.
     self.assertEqual(80, _helpers._DEFAULT_HELP_WIDTH)
     self.assertEqual(_helpers._DEFAULT_HELP_WIDTH, flags.get_help_width())
     _helpers._DEFAULT_HELP_WIDTH = 10
     self.assertEqual(_helpers._DEFAULT_HELP_WIDTH, flags.get_help_width())
     _helpers._DEFAULT_HELP_WIDTH = default_help_width  # restore
Exemple #2
0
def _wrap_lines(lines, wrapper=None):
    """Wraps a multiline string.

  Args:
    lines: str, a multiline string to wrap.
    wrapper: textwrap.TextWrapper, the wrapper to use for wrapping and
        formatting.

  Returns:
    The formatted string.
  """
    if wrapper is None:
        wrapper = textwrap.TextWrapper(break_on_hyphens=False,
                                       break_long_words=False,
                                       width=flags.get_help_width())
    result = '\n'.join([wrapper.fill(line) for line in lines.splitlines()])
    if lines.endswith('\n'):
        result += '\n'
    return result
Exemple #3
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.

  Raises:
    SystemExit: to indicate exiting the program.
  """
    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.doc_to_help(doc.replace('%s', GetAppBasename()))
        stdfile.write(flags.text_wrap(help_msg, flags.get_help_width()))
        stdfile.write('\n\n\n')
    if not doc or doc.find('%s') == -1:
        synopsis = 'USAGE: ' + GetSynopsis()
        stdfile.write(
            flags.text_wrap(synopsis, flags.get_help_width(), '       ', ''))
        stdfile.write('\n\n\n')
    # Special case just 'help' registered, that means run as 'tool --help'.
    if len(GetCommandList()) == 1:
        cmd_names = []
    else:
        cmd_names = [
            cmd_name for cmd_name, cmd in GetCommandList().items()
            if not cmd._hidden
        ]  # pylint: disable=protected-access
        cmd_names.sort()
        # Show list of commands
        if show_cmd is None or show_cmd == 'help':
            stdfile.write('Any of the following commands:\n')
            doc = ', '.join(cmd_names)
            stdfile.write(flags.text_wrap(doc, flags.get_help_width(), '  '))
            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 = []
    # 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:  # pylint: disable=broad-except
            cmd_help = "Internal error for command '%s': %s." % (name,
                                                                 str(error))
        cmd_help = cmd_help.strip()
        all_names = ', '.join([command.CommandGetName()] +
                              (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.text_wrap(all_names, flags.get_help_width()))
            stdfile.write('\n')
            prefix1 = prefix
        else:
            prefix1 = all_names.ljust(GetMaxCommandLength() + 2)
        if cmd_help:
            stdfile.write(
                flags.text_wrap(cmd_help, flags.get_help_width(), 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:
                stdfile.write('%sFlags for %s:\n' % (prefix, name))
                stdfile.write(cmd_flags.get_help(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.main_module_help())
        else:
            stdfile.write(FLAGS.get_help())
        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)
def write_break():
  """Writes a line break followed by a line of '-' and two more line breaks."""
  write('')
  write(''.join(['-' for _ in range(0, flags.get_help_width(), 1)]))
  write('')