From 21cec11eb005e77917a7263a0f164a80deca0e04 Mon Sep 17 00:00:00 2001 From: Alexander Popov Date: Mon, 22 Apr 2024 01:39:17 +0300 Subject: [PATCH] Like grep, colorize the output only if stdout is connected to a terminal Nice. With this, if you redirect the output of kernel-hardening-checker to a file, it doesn't contain the ANSI escape sequences for colorizing. --- kernel_hardening_checker/engine.py | 4 +++- kernel_hardening_checker/test_engine.py | 16 ++++++++-------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/kernel_hardening_checker/engine.py b/kernel_hardening_checker/engine.py index 00344fe..56aa80f 100644 --- a/kernel_hardening_checker/engine.py +++ b/kernel_hardening_checker/engine.py @@ -11,12 +11,14 @@ This module is the engine of checks. # pylint: disable=missing-class-docstring,missing-function-docstring # pylint: disable=line-too-long,invalid-name,too-many-branches +import sys + GREEN_COLOR = '\x1b[32m' RED_COLOR = '\x1b[31m' COLOR_END = '\x1b[0m' def colorize_result(input_text): - if input_text is None: + if input_text is None or not sys.stdout.isatty(): return input_text if input_text.startswith('OK'): color = GREEN_COLOR diff --git a/kernel_hardening_checker/test_engine.py b/kernel_hardening_checker/test_engine.py index 4db8f21..2901449 100644 --- a/kernel_hardening_checker/test_engine.py +++ b/kernel_hardening_checker/test_engine.py @@ -450,8 +450,8 @@ class TestEngine(unittest.TestCase): stdout_result, [ '\ -CONFIG_NAME_1 |kconfig| expected_1 |decision_1| reason_1 | \x1b[32mOK: name_2 is "expected_2"\x1b[0m\ -CONFIG_NAME_4 |kconfig| expected_4 |decision_4| reason_4 | \x1b[31mFAIL: name_5 is not "expected_5"\x1b[0m\ +CONFIG_NAME_1 |kconfig| expected_1 |decision_1| reason_1 | OK: name_2 is "expected_2"\ +CONFIG_NAME_4 |kconfig| expected_4 |decision_4| reason_4 | FAIL: name_5 is not "expected_5"\ ' ] ) @@ -461,16 +461,16 @@ CONFIG_NAME_4 |kconfig| expected_4 |decision_4| re stdout_result, [ '\ - <<< OR >>> | \x1b[32mOK: name_2 is "expected_2"\x1b[0m\n\ -CONFIG_NAME_1 |kconfig| expected_1 |decision_1| reason_1 | \x1b[31mFAIL: "UNexpected_1"\x1b[0m\n\ -name_2 |cmdline| expected_2 |decision_2| reason_2 | \x1b[32mOK\x1b[0m\n\ + <<< OR >>> | OK: name_2 is "expected_2"\n\ +CONFIG_NAME_1 |kconfig| expected_1 |decision_1| reason_1 | FAIL: "UNexpected_1"\n\ +name_2 |cmdline| expected_2 |decision_2| reason_2 | OK\n\ name_3 |sysctl | expected_3 |decision_3| reason_3 | None\ '\ '\ - <<< AND >>> | \x1b[31mFAIL: name_5 is not "expected_5"\x1b[0m\n\ + <<< AND >>> | FAIL: name_5 is not "expected_5"\n\ CONFIG_NAME_4 |kconfig| expected_4 |decision_4| reason_4 | None\n\ -name_5 |cmdline| expected_5 |decision_5| reason_5 | \x1b[31mFAIL: "UNexpected_5"\x1b[0m\n\ -name_6 |sysctl | expected_6 |decision_6| reason_6 | \x1b[32mOK\x1b[0m\ +name_5 |cmdline| expected_5 |decision_5| reason_5 | FAIL: "UNexpected_5"\n\ +name_6 |sysctl | expected_6 |decision_6| reason_6 | OK\ ' ] ) -- 2.31.1