Skip to content

Commit

Permalink
Merge pull request #109 from JoshuaRLi/remove-bashcolor-singleton
Browse files Browse the repository at this point in the history
replace BashColor singleton with colorize function
  • Loading branch information
KevinHock authored Dec 22, 2018
2 parents 50febd3 + 65a6919 commit 1415b4b
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 83 deletions.
40 changes: 20 additions & 20 deletions detect_secrets/core/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
from .baseline import format_baseline_for_output
from .baseline import merge_results
from .bidirectional_iterator import BidirectionalIterator
from .color import BashColor
from .color import Color
from .color import AnsiColor
from .color import colorize
from .potential_secret import PotentialSecret


Expand Down Expand Up @@ -130,17 +130,17 @@ def compare_baselines(old_baseline_filename, new_baseline_filename):
if is_removed:
plugins_used = old_baseline['plugins_used']
header = header.format(
BashColor.color('Status:', Color.BOLD),
colorize('Status:', AnsiColor.BOLD),
'>> {} <<'.format(
BashColor.color('REMOVED', Color.RED),
colorize('REMOVED', AnsiColor.RED),
),
)
else:
plugins_used = new_baseline['plugins_used']
header = header.format(
BashColor.color('Status:', Color.BOLD),
colorize('Status:', AnsiColor.BOLD),
'>> {} <<'.format(
BashColor.color('ADDED', Color.LIGHT_GREEN),
colorize('ADDED', AnsiColor.LIGHT_GREEN),
),
)

Expand Down Expand Up @@ -345,14 +345,14 @@ def _print_context( # pragma: no cover
:raises: SecretNotFoundOnSpecifiedLineError
"""
print('{} {} {} {}\n{} {}\n{} {}'.format(
BashColor.color('Secret: ', Color.BOLD),
BashColor.color(str(count), Color.PURPLE),
BashColor.color('of', Color.BOLD),
BashColor.color(str(total), Color.PURPLE),
BashColor.color('Filename: ', Color.BOLD),
BashColor.color(filename, Color.PURPLE),
BashColor.color('Secret Type:', Color.BOLD),
BashColor.color(secret['type'], Color.PURPLE),
colorize('Secret: ', AnsiColor.BOLD),
colorize(str(count), AnsiColor.PURPLE),
colorize('of', AnsiColor.BOLD),
colorize(str(total), AnsiColor.PURPLE),
colorize('Filename: ', AnsiColor.BOLD),
colorize(filename, AnsiColor.PURPLE),
colorize('Secret Type:', AnsiColor.BOLD),
colorize(secret['type'], AnsiColor.PURPLE),
))
if additional_header_lines:
print(additional_header_lines)
Expand Down Expand Up @@ -497,19 +497,19 @@ def _get_secret_with_context(
raise

output[index_of_secret_in_output] = '{}'.format(
BashColor.color(
colorize(
output[index_of_secret_in_output],
Color.BOLD,
AnsiColor.BOLD,
),
)

# Adding line numbers
return '\n'.join(
map(
lambda x: '{}:{}'.format(
BashColor.color(
colorize(
str(int(x[0]) + start_line),
Color.LIGHT_GREEN,
AnsiColor.LIGHT_GREEN,
),
x[1],
),
Expand Down Expand Up @@ -562,11 +562,11 @@ def _highlight_secret(secret_line, secret_lineno, secret, filename, plugin_setti
end_of_secret = index_of_secret + len(raw_secret)
return '{}{}{}'.format(
secret_line[:index_of_secret],
BashColor.color(
colorize(
# copy the secret out of the line because .lower() from secret
# generator may be different from the original value:
secret_line[index_of_secret:end_of_secret],
Color.RED_BACKGROUND,
AnsiColor.RED_BACKGROUND,
),
secret_line[index_of_secret + len(raw_secret):],
)
Expand Down
42 changes: 8 additions & 34 deletions detect_secrets/core/color.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,18 @@
from enum import Enum


class Color(Enum):
NORMAL = '[0m'
class AnsiColor(Enum):
RESET = '[0m'
BOLD = '[1m'

RED = '[91m'
RED_BACKGROUND = '[41m'
LIGHT_GREEN = '[92m'
PURPLE = '[95m'


class _BashColor(object):

PREFIX = '\033'

def __init__(self):
self.DISABLED = False

def enable_color(self):
self.DISABLED = False

def disable_color(self):
self.DISABLED = True

def color(self, text, color):
"""
:type text: str
:param text: the text to colorize
:type color: Color
:param color: the color to make the text
:returns: colored string
"""
if self.DISABLED:
return text

return self.PREFIX + color.value + text + \
self.PREFIX + Color.NORMAL.value


BashColor = _BashColor()
def colorize(text, color):
return '\x1b{}{}\x1b{}'.format(
color.value,
text,
AnsiColor.RESET.value,
)
8 changes: 8 additions & 0 deletions testing/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import re

# https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
_ansi_escape = re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]')


def uncolor(text):
return _ansi_escape.sub('', text)
30 changes: 9 additions & 21 deletions tests/core/audit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
import pytest

from detect_secrets.core import audit
from detect_secrets.core.color import BashColor
from testing.factories import potential_secret_factory
from testing.mocks import mock_printer as mock_printer_base
from testing.util import uncolor


class TestAuditBaseline(object):
Expand Down Expand Up @@ -287,12 +287,6 @@ def leapfrog_baseline(self):

class TestCompareBaselines(object):

def setup(self):
BashColor.disable_color()

def teardown(self):
BashColor.enable_color()

def test_raises_error_if_comparing_same_file(self):
with pytest.raises(audit.RedundantComparisonError):
audit.compare_baselines('foo/bar', 'foo/bar')
Expand All @@ -318,29 +312,29 @@ def test_compare(self, mock_printer):
buffer = ''

# This comes first, because it's found at line 1.
assert headers[0] == textwrap.dedent("""
assert uncolor(headers[0]) == textwrap.dedent("""
Secret: 1 of 4
Filename: test_data/each_secret.py
Secret Type: Hex High Entropy String
Status: >> ADDED <<
""")[1:]

assert headers[1] == textwrap.dedent("""
assert uncolor(headers[1]) == textwrap.dedent("""
Secret: 2 of 4
Filename: test_data/each_secret.py
Secret Type: Base64 High Entropy String
Status: >> REMOVED <<
""")[1:]

# These files come after, because filenames are sorted first
assert headers[2] == textwrap.dedent("""
assert uncolor(headers[2]) == textwrap.dedent("""
Secret: 3 of 4
Filename: test_data/short_files/first_line.py
Secret Type: Hex High Entropy String
Status: >> REMOVED <<
""")[1:]

assert headers[3] == textwrap.dedent("""
assert uncolor(headers[3]) == textwrap.dedent("""
Secret: 4 of 4
Filename: test_data/short_files/last_line.ini
Secret Type: Hex High Entropy String
Expand Down Expand Up @@ -463,12 +457,6 @@ def new_baseline(self):

class TestPrintContext(object):

def setup(self):
BashColor.disable_color()

def teardown(self):
BashColor.enable_color()

def run_logic(self, secret=None, secret_lineno=15, settings=None):
# Setup default arguments
if not secret:
Expand Down Expand Up @@ -537,7 +525,7 @@ def test_basic(self, mock_printer):

assert sed_call.call_args[0][0] == 'sed -n 10,20p filenameA'.split()

assert mock_printer.message == textwrap.dedent("""
assert uncolor(mock_printer.message) == textwrap.dedent("""
Secret: 1 of 2
Filename: filenameA
Secret Type: Private Key
Expand Down Expand Up @@ -570,7 +558,7 @@ def test_secret_at_top_of_file(self, mock_printer):

assert sed_call.call_args[0][0] == 'sed -n 1,6p filenameA'.split()

assert mock_printer.message == textwrap.dedent("""
assert uncolor(mock_printer.message) == textwrap.dedent("""
Secret: 1 of 2
Filename: filenameA
Secret Type: Private Key
Expand Down Expand Up @@ -598,7 +586,7 @@ def test_secret_not_found(self, mock_printer):
).json(),
)

assert mock_printer.message == textwrap.dedent("""
assert uncolor(mock_printer.message) == textwrap.dedent("""
Secret: 1 of 2
Filename: filenameA
Secret Type: Private Key
Expand Down Expand Up @@ -628,7 +616,7 @@ def test_secret_in_yaml_file(self, mock_printer):
],
)

assert mock_printer.message == textwrap.dedent("""
assert uncolor(mock_printer.message) == textwrap.dedent("""
Secret: 1 of 2
Filename: filenameB
Secret Type: Hex High Entropy String
Expand Down
12 changes: 4 additions & 8 deletions tests/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@

from detect_secrets import main as main_module
from detect_secrets.core import audit as audit_module
from detect_secrets.core.color import BashColor
from detect_secrets.main import main
from testing.factories import secrets_collection_factory
from testing.mocks import Any
from testing.mocks import mock_printer
from testing.util import uncolor


class TestMain(object):
Expand Down Expand Up @@ -60,7 +60,7 @@ def test_scan_string_basic(self, mock_baseline_initialize):
main_module,
) as printer_shim:
assert main('scan --string'.split()) == 0
assert printer_shim.message == textwrap.dedent("""
assert uncolor(printer_shim.message) == textwrap.dedent("""
AWSKeyDetector : False
Base64HighEntropyString: False (3.459)
BasicAuthDetector : False
Expand All @@ -77,7 +77,7 @@ def test_scan_string_cli_overrides_stdin(self):
main_module,
) as printer_shim:
assert main('scan --string 012345'.split()) == 0
assert printer_shim.message == textwrap.dedent("""
assert uncolor(printer_shim.message) == textwrap.dedent("""
AWSKeyDetector : False
Base64HighEntropyString: False (2.585)
BasicAuthDetector : False
Expand Down Expand Up @@ -198,8 +198,6 @@ def test_old_baseline_ignored_with_update_flag(
],
)
def test_audit_short_file(self, filename, expected_output):
BashColor.disable_color()

with mock_stdin(), mock_printer(
# To extract the baseline output
main_module,
Expand Down Expand Up @@ -227,7 +225,7 @@ def test_audit_short_file(self, filename, expected_output):
) as printer_shim:
main('audit will_be_mocked'.split())

assert printer_shim.message == textwrap.dedent("""
assert uncolor(printer_shim.message) == textwrap.dedent("""
Secret: 1 of 1
Filename: {}
Secret Type: {}
Expand All @@ -241,8 +239,6 @@ def test_audit_short_file(self, filename, expected_output):
expected_output,
)

BashColor.enable_color()

def test_audit_diff_not_enough_files(self):
assert main('audit --diff fileA'.split()) == 1

Expand Down

0 comments on commit 1415b4b

Please sign in to comment.