Click: Add Custom Formatter System

Created on 15 Apr 2016  路  3Comments  路  Source: pallets/click

Right now there is just one way to format everything and it does not make everybody happy. Also it makes it hard for us to change it without potentially breaking things. So I propose the following:

  • add a context setting to override a formatter class
  • that formatter has attributes and methods to customize how things are emitted
  • we have two classes for this: a default formatter that we keep improving and a legacy formatter that is as it looked like in click 5 which is super stable if you need a stable target

Things this would be used for:

  • usage rendering
  • wrapping of text
  • colorization flags
  • maximum width / minimum width of help output
  • indentation style of help
  • default value rendering etc.
  • error messages

Most helpful comment

@kx-chen and I were looking into this, and we've compiled our findings for what currently uses formatting as well as the requests that users have made over time: https://hackmd.io/@0yFPGIsmRoWxZudVa0s2_Q/B1XOcq3gP

All 3 comments

Formatter class is an anti-pattern. Better export all settings as a tree and pass it to template engine.

@kx-chen and I were looking into this, and we've compiled our findings for what currently uses formatting as well as the requests that users have made over time: https://hackmd.io/@0yFPGIsmRoWxZudVa0s2_Q/B1XOcq3gP

After looking at the very helpful list of APIs from @amy-lei and browsing the source code, I might have some ideas on how a more central formatter could be structured. Though I am sure that there will be a lot of details to figure out...

One could have a central formatter class which would take the command itself and the context and arguments. This formatter could then have methods to generate usage and help messages when supplied with the command and context as arguments, practically replacing the Command.format_{} methods which have many hard-coded strings.

Similar formatters could exist for Option, handling Option.get_help_record and ParamType.get_missing_message, and exceptions, handling the ClickException.format_message method. In the latter case, the ClickException could only contain error information while formatting, with a default or user-defined formatter, is handled where the exception is caught in BaseCommand.main.

This approach would provide a clean separation between commands and output formatting and could even allow for localised strings in the CLI (this is quite common on macOS). However, it does require supporting new errors, parameter types, etc, explicitly in the formatter instead of just providing formatting methods on the classes themselves. This does potentially increase the burden of maintenance.

To conclude, I can understand why you'd want to keep things as is, with hard-coded section titles, indents, messages, etc.

Was this page helpful?
0 / 5 - 0 ratings