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

Don't use Ansi Colors if not supported. #523

Merged
merged 4 commits into from
Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions detect_secrets/util/color.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
from enum import Enum
from os import getenv
from sys import stdout


def supports_ansi_colors() -> bool:
return (getenv('CLICOLOR', '1') != '0' and stdout.isatty())\
or getenv('CLICOLOR_FORCE', '0') != '0'


class AnsiColor(Enum):
Expand All @@ -11,6 +18,9 @@ class AnsiColor(Enum):


def colorize(text: str, color: AnsiColor) -> str:
if not supports_ansi_colors():
return text

return '\x1b{}{}\x1b{}'.format(
color.value,
text,
Expand Down
44 changes: 44 additions & 0 deletions tests/util/color_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from sys import stdout

from detect_secrets.util.color import AnsiColor
from detect_secrets.util.color import colorize


def colorize_enabled(text: str, color: AnsiColor) -> str:
return '\x1b{}{}\x1b{}'.format(
color.value,
text,
AnsiColor.RESET.value,
)


def expect_enabled(text: str):
for color in AnsiColor:
expected = colorize_enabled(text, color)
assert colorize(text, color) == expected


def expect_disabled(text: str):
for color in AnsiColor:
assert colorize(text, color) == text


def test_colorize_enabled_terminal_disabled_piped(monkeypatch):
monkeypatch.setenv('CLICOLOR', '1')

if stdout.isatty():
expect_enabled('abc')
else:
expect_disabled('abc')


def test_colorize_enabled_force(monkeypatch):
monkeypatch.setenv('CLICOLOR_FORCE', '1')

expect_enabled('abc')


def test_colorize_disabled(monkeypatch):
monkeypatch.setenv('CLICOLOR', '0')

expect_disabled('abc')