Skip to content

Commit

Permalink
added option to strip colors on piped output
Browse files Browse the repository at this point in the history
  • Loading branch information
SilenZcience committed Jan 15, 2024
1 parent da52ab8 commit 33dde02
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 18 deletions.
7 changes: 5 additions & 2 deletions cat_win/cat.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,15 @@

working_dir = os.path.dirname(os.path.realpath(__file__))

coloramaInit()
cconfig = CConfig(working_dir)
config = Config(working_dir)

default_color_dic = cconfig.load_config()
color_dic = default_color_dic.copy()
const_dic = config.load_config()

coloramaInit(strip=(not os.isatty(sys.stdout.fileno()) and const_dic[DKW.STRIP_COLOR_ON_PIPE]))

arg_parser = ArgParser(const_dic[DKW.DEFAULT_FILE_ENCODING])
converter = Converter()
holder = Holder()
Expand Down Expand Up @@ -995,7 +996,9 @@ def init_colors() -> None:
"""
# do not use colors if requested, or output will be piped anyways
global color_dic
if holder.args_id[ARGS_NOCOL] or not sys.stdout.isatty() or sys.stdout.closed:

if holder.args_id[ARGS_NOCOL] or sys.stdout.closed or \
(not os.isatty(sys.stdout.fileno()) and const_dic[DKW.STRIP_COLOR_ON_PIPE]):
color_dic = dict.fromkeys(color_dic, '')
else:
color_dic = default_color_dic.copy()
Expand Down
1 change: 1 addition & 0 deletions cat_win/const/defaultconstants.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ class DKW:
DEFAULT_COMMAND_LINE = 'default_command_line'
DEFAULT_FILE_ENCODING = 'default_file_encoding'
LARGE_FILE_SIZE = 'large_file_size'
STRIP_COLOR_ON_PIPE = 'strip_color_on_pipe'
76 changes: 62 additions & 14 deletions cat_win/persistence/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class Config:
default_dic = {DKW.DEFAULT_COMMAND_LINE: '',
DKW.DEFAULT_FILE_ENCODING: 'utf-8',
DKW.LARGE_FILE_SIZE: 1024 * 1024 * 100, # 100 Megabytes
DKW.STRIP_COLOR_ON_PIPE: True,
}

elements = list(default_dic.keys())
Expand All @@ -40,6 +41,63 @@ def __init__(self, working_dir: str) -> None:
self.longest_char_count = 30
self.rows = 3

@staticmethod
def convert_config_element(element: str, element_type: type):
"""
Parameters:
element (str):
the element to convert
element_type (type):
the type the element should have
Returns:
(element_type):
whatever the element got converted to
"""
if element_type == bool:
if element.upper() in ['FALSE', 'NO', 'N', '0']:
return False
return True

return element_type(element)

@staticmethod
def is_valid_value(value: str, value_type: type) -> bool:
"""
check if a given value is a valid argument for an element
in the constant dict.
Parameters:
value (str):
the value to check
value_type (type):
the type the value should have
Returns
(bool):
indicates whether the value is valid.
"""
if value == '':
return False
try:
value_type(value)
if value_type in [int, float]:
return value_type(value) >= 0.0
if value_type == bool:
return value.upper() in [
'TRUE',
'YES',
'Y',
'1',
'FALSE',
'NO',
'N',
'0',
]
return bool(value)
except ValueError:
return False

def get_cmd(self) -> list:
"""
split the default command line string correctly into a parameter list
Expand All @@ -60,8 +118,9 @@ def load_config(self) -> dict:
config_colors = self.config_parser['CONSTS']
for element in self.elements:
try:
type_def = type(self.default_dic[element])
self.const_dic[element] = type_def(config_colors[element])
self.const_dic[element] = Config.convert_config_element(
config_colors[element],
type(self.default_dic[element]))
except KeyError:
self.const_dic[element] = self.default_dic[element]
except KeyError:
Expand Down Expand Up @@ -111,19 +170,8 @@ def save_config(self) -> None:
print(f"Successfully selected element '{keyword}'")
print(f"The current value of '{keyword}' is '{self.const_dic[keyword]}'")

def is_valid_value(value: str) -> bool:
type_def = type(self.default_dic[keyword])
try:
type_def(value)
try:
return type_def(value) >= 0
except TypeError:
return bool(value)
except ValueError:
return False

value = ''
while not is_valid_value(value):
while not Config.is_valid_value(value, type(self.default_dic[keyword])):
if value != '':
print(f"Something went wrong. Invalid option '{value}'.")
try:
Expand Down
4 changes: 2 additions & 2 deletions cat_win/tests/mocks/std.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ class StdOutMock(io.StringIO):
# def reconfigure(self, encoding = None) -> None:
# return

# def fileno(self) -> int:
# return 0
def fileno(self) -> int:
return 1


class StdOutMockIsAtty(io.StringIO):
Expand Down

0 comments on commit 33dde02

Please sign in to comment.