Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6a1f945

Browse files
committed
Add color utility.
1 parent e98d2e1 commit 6a1f945

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

pre_commit/color.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
import sys
3+
4+
RED = '\033[41m'
5+
GREEN = '\033[42m'
6+
NORMAL = '\033[0m'
7+
8+
9+
def format_color(text, color, use_color):
10+
"""Format text with color.
11+
12+
Args:
13+
text - Text to be formatted with color if `use_color`
14+
color - The color start string
15+
use_color - Whether or not to color
16+
"""
17+
if not use_color:
18+
return text
19+
else:
20+
return u'{0}{1}{2}'.format(color, text, NORMAL)
21+
22+
23+
def use_color(setting):
24+
"""Choose whether to use color based on the command argument.
25+
26+
Args:
27+
setting - Either `auto`, `always`, or `never`
28+
"""
29+
return (
30+
setting == 'always' or
31+
(setting == 'auto' and sys.stdout.isatty())
32+
)

tests/color_test.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
import mock
3+
import pytest
4+
import sys
5+
6+
from pre_commit.color import format_color
7+
from pre_commit.color import GREEN
8+
from pre_commit.color import use_color
9+
10+
11+
@pytest.mark.parametrize(('in_text', 'in_color', 'in_use_color', 'expected'), (
12+
('foo', GREEN, True, '{0}foo\033[0m'.format(GREEN)),
13+
('foo', GREEN, False, 'foo'),
14+
))
15+
def test_format_color(in_text, in_color, in_use_color, expected):
16+
ret = format_color(in_text, in_color, in_use_color)
17+
assert ret == expected
18+
19+
20+
def test_use_color_never():
21+
assert use_color('never') is False
22+
23+
24+
def test_use_color_always():
25+
assert use_color('always') is True
26+
27+
28+
def test_use_color_no_tty():
29+
with mock.patch.object(sys.stdout, 'isatty', return_value=False):
30+
assert use_color('auto') is False
31+
32+
33+
def test_use_color_tty():
34+
with mock.patch.object(sys.stdout, 'isatty', return_value=True):
35+
assert use_color('auto') is True

0 commit comments

Comments
 (0)