Skip to content

ctx.color is ignored in ClickException.show() #2193

@jan-golda

Description

@jan-golda

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:

ctx = get_current_context(silent=True)

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

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