Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jan-golda opened this issue Feb 14, 2022 · 2 comments · May be fixed by #2273
Open

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

jan-golda opened this issue Feb 14, 2022 · 2 comments · May be fixed by #2273
Milestone

Comments

@jan-golda
Copy link

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
@jan-golda
Copy link
Author

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!

@dzcode
Copy link
Contributor

dzcode commented May 2, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants