click icon indicating copy to clipboard operation
click copied to clipboard

`ctx.color` is ignored in `ClickException.show()`

Open jan-golda opened this issue 3 years ago • 2 comments

I have tried to set ctx.color = True as suggested in #1090 in order to enable colour output in Gitlab CI. This worked out great for normal click.secho but unfortunately it does not work for output generated via raising ClickException subclass. Essentially the echo inside ClickException.show() ignores ctx.color.

After some digging, I am almost sure this is because the get_current_context returns None, there is no context when exceptions are handled: https://github.com/pallets/click/blob/49164faca678dd476f1b11a2584fd0e1c6be70b2/src/click/globals.py#L63

Test code

import click
from click import ClickException


class CLIError(ClickException):
    def format_message(self) -> str:
        return click.style(self.message, fg='red')


@click.command()
@click.option('--ansi', is_flag=True)
@click.pass_context
def cli(ctx, ansi):
    if ansi:
        ctx.color = True

    click.secho('some output', fg='green')

    raise CLIError('some error')


if __name__ == '__main__':
    cli()

Test cases

  1. python test.py
  2. python test.py --ansi
  3. python test.py &> test.log; cat test.log
  4. python test.py --ansi &> test.log; cat test.log

Expected behaviour

In all cases except 3) there is a green some output and red some error in output.

In 3) there is no colouring.

Actual behaviour

Everything is as expected except 4) where some error is not coloured.

Environment

  • Python version: 3.7.9
  • Click version: 8.0.3

jan-golda avatar Feb 14 '22 13:02 jan-golda

If I am correct that the context is already closed while handling the exception then I guess it is not so easy to fix. In such a case, could you propose a WAR for that?

Thanks!

jan-golda avatar Feb 14 '22 13:02 jan-golda

I'm at the PyCon sprints and can take on working on this

dzcode avatar May 02 '22 23:05 dzcode