`ctx.color` is ignored in `ClickException.show()`
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
-
python test.py -
python test.py --ansi -
python test.py &> test.log; cat test.log -
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
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!
I'm at the PyCon sprints and can take on working on this