Skip to content

Option format text should replace newlines with spaces #834

Closed
@warsaw

Description

@warsaw

In Mailman 3, we write options like so:

@click.option(
    '-C', '--config', 'config_file',
    envvar='MAILMAN_CONFIG_FILE',
    type=click.Path(exists=True, dir_okay=False, resolve_path=True),
    help=_("""\
    Configuration file to use.  If not given, the environment variable
    MAILMAN_CONFIG_FILE is consulted and used if set.  If neither are given, a
    default configuration file is loaded."""))

This makes it possible to translate the help text, but because the source formatting is a triple quoted string, there are embedded newlines in the help text. We have to preserve the original source string text so that it can be looked up in the i18n catalog, and we can't really change the _() function to strip newlines at runtime because the source strings are extracted by an offline process that does not execute the source code.

After some pdb tracing, I've noticed that click already dedents the help text, which is great, but it also needs to substitute spaces for newlines, otherwise the wrapping of the help text isn't correct. For example, the above by default gets printed on the console like so:

$ mailman --help
...
Options:
  -C, --config PATH  Configuration file to use.  If not given, the
                     environment variable
                     MAILMAN_CONFIG_FILE is consulted
                     and used if set.  If neither are given, a
                     default
                     configuration file is loaded.

Here's a small change that makes the -C option print correctly:

    def format_options(self, ctx, formatter):
        """Writes all the options into the formatter if they exist."""
        opts = []
        for param in self.get_params(ctx):
            rv = param.get_help_record(ctx)
            if rv is not None:
                part_a, part_b = rv
                opts.append((part_a, part_b.replace('\n', ' ')))

        if opts:
            with formatter.section('Options'):
                formatter.write_dl(opts)

and now:

$ mailman --help
...
Options:
  -C, --config PATH  Configuration file to use.  If not given, the
                     environment variable MAILMAN_CONFIG_FILE is consulted
                     and used if set.  If neither are given, a default
                     configuration file is loaded.

Much better!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions