Skip to content

Commit

Permalink
refactored environment dependent variables
Browse files Browse the repository at this point in the history
  • Loading branch information
SilenZcience committed Nov 20, 2024
1 parent 10efd94 commit 5f54ffa
Show file tree
Hide file tree
Showing 14 changed files with 91 additions and 100 deletions.
6 changes: 3 additions & 3 deletions cat_win/src/argparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from cat_win.src.const.regex import RE_ENCODING, RE_Q_MATCH, RE_M_ATCH, RE_Q_FIND, RE_F_IND
from cat_win.src.const.regex import RE_Q_REPLACE, RE_R_EPLACE, RE_Q_TRUNC, RE_T_RUNC
from cat_win.src.const.regex import RE_CUT, RE_REPLACE, RE_REPLACE_COMMA
from cat_win.src.service.helper.environment import on_windows_os

IS_FILE, IS_DIR, IS_PATTERN = range(0, 3)

Expand All @@ -19,12 +20,11 @@ class ArgParser:
"""
defines the ArgParser
"""
def __init__(self, on_windows_os: bool = None,
default_file_encoding: str = 'utf-8',
def __init__(self, default_file_encoding: str = 'utf-8',
unicode_echo: bool = True,
unicode_find: bool = True,
unicode_replace: bool = True) -> None:
self.win_prefix_lit = '\\\\?\\' * bool(on_windows_os)
self.win_prefix_lit = '\\\\?\\' * on_windows_os
self.default_file_encoding: str = default_file_encoding
self.unicode_echo: bool = unicode_echo
self.unicode_find = unicode_find
Expand Down
32 changes: 14 additions & 18 deletions cat_win/src/cat.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from itertools import groupby
from time import monotonic
import os
import platform
import shlex
import sys

Expand All @@ -24,15 +23,16 @@
from cat_win.src.domain.files import Files
from cat_win.src.persistence.cconfig import CConfig
from cat_win.src.persistence.config import Config
from cat_win.src.service.helper.archiveviewer import display_archive
from cat_win.src.service.helper.environment import on_windows_os
from cat_win.src.service.helper.iohelper import IoHelper, err_print
from cat_win.src.service.helper.progressbar import PBar
from cat_win.src.service.helper.levenshtein import calculate_suggestions
from cat_win.src.service.helper.progressbar import PBar
from cat_win.src.service.helper.tmpfilehelper import TmpFileHelper
try:
from cat_win.src.service.helper.utility import comp_eval, comp_conv
except SyntaxError: # in case of Python 3.7
from cat_win.src.service.helper.utilityold import comp_eval, comp_conv
from cat_win.src.service.helper.archiveviewer import display_archive
from cat_win.src.service.cbase64 import encode_base64, decode_base64
from cat_win.src.service.checksum import print_checksum
from cat_win.src.service.clipboard import Clipboard
Expand All @@ -56,7 +56,6 @@
coloramaInit(strip=False)
working_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir, os.pardir))

on_windows_os = platform.system() == 'Windows'
file_uri_prefix = 'file://' + '/' * on_windows_os

cconfig = CConfig(working_dir)
Expand All @@ -78,8 +77,7 @@ def setup():
color_dic = default_color_dic.copy()
const_dic = config.load_config()

arg_parser = ArgParser(on_windows_os,
const_dic[DKW.DEFAULT_FILE_ENCODING],
arg_parser = ArgParser(const_dic[DKW.DEFAULT_FILE_ENCODING],
const_dic[DKW.UNICODE_ESCAPED_ECHO],
const_dic[DKW.UNICODE_ESCAPED_FIND],
const_dic[DKW.UNICODE_ESCAPED_REPLACE])
Expand Down Expand Up @@ -177,7 +175,7 @@ def _show_help(repl: bool = False) -> None:
try:
(More(help_message.splitlines())).step_through()
finally:
print_update_information(__project__, __version__, color_dic, on_windows_os)
print_update_information(__project__, __version__, color_dic)


def _show_version(repl: bool = False) -> None:
Expand All @@ -201,7 +199,7 @@ def _show_version(repl: bool = False) -> None:
version_message += 'Install time: \t-\n'
version_message += f"Author: \t{__author__}\n"
print(version_message)
print_update_information(__project__, __version__, color_dic, on_windows_os)
print_update_information(__project__, __version__, color_dic)


def _show_debug(args: list, unknown_args: list, known_files: list, unknown_files: list,
Expand Down Expand Up @@ -258,7 +256,6 @@ def _print_meta_and_checksum(show_meta: bool, show_checksum: bool) -> None:
for file in u_files:
if show_meta:
print_meta(file.path, os.path.join(working_dir, 'res', 'signatures.json'),
on_windows_os,
[color_dic[CKW.RESET_ALL],
color_dic[CKW.ATTRIB],
color_dic[CKW.ATTRIB_POSITIVE],
Expand Down Expand Up @@ -1037,14 +1034,14 @@ def init(repl: bool = False) -> tuple:
sys.exit(0)

Editor.set_indentation(const_dic[DKW.EDITOR_INDENTATION], const_dic[DKW.EDITOR_AUTO_INDENT])
Editor.set_flags(u_args[ARGS_STDIN] and on_windows_os, on_windows_os,
u_args[ARGS_DEBUG], const_dic[DKW.UNICODE_ESCAPED_EDITOR_SEARCH],
Editor.set_flags(u_args[ARGS_STDIN] and on_windows_os, u_args[ARGS_DEBUG],
const_dic[DKW.UNICODE_ESCAPED_EDITOR_SEARCH],
const_dic[DKW.UNICODE_ESCAPED_EDITOR_REPLACE],
arg_parser.file_encoding)
HexEditor.set_flags(u_args[ARGS_STDIN] and on_windows_os, on_windows_os,
u_args[ARGS_DEBUG], const_dic[DKW.UNICODE_ESCAPED_EDITOR_SEARCH],
HexEditor.set_flags(u_args[ARGS_STDIN] and on_windows_os, u_args[ARGS_DEBUG],
const_dic[DKW.UNICODE_ESCAPED_EDITOR_SEARCH],
const_dic[DKW.HEX_EDITOR_COLUMNS])
More.set_flags(on_windows_os, const_dic[DKW.MORE_STEP_LENGTH])
More.set_flags(const_dic[DKW.MORE_STEP_LENGTH])
Visualizer.set_flags(u_args[ARGS_DEBUG])
Summary.set_flags(const_dic[DKW.SUMMARY_UNIQUE_ELEMENTS])
Summary.set_colors(color_dic[CKW.SUMMARY], color_dic[CKW.RESET_ALL])
Expand Down Expand Up @@ -1104,16 +1101,15 @@ def handle_args(tmp_file_helper: TmpFileHelper) -> None:
)]
else:
unknown_files = IoHelper.read_write_files_from_stdin(
unknown_files, arg_parser.file_encoding, on_windows_os,
u_args[ARGS_ONELINE]
unknown_files, arg_parser.file_encoding, u_args[ARGS_ONELINE]
)

if u_args[ARGS_EDITOR]:
with IoHelper.dup_stdin(on_windows_os, u_args[ARGS_STDIN]):
with IoHelper.dup_stdin(u_args[ARGS_STDIN]):
for file in known_files:
Editor.open(file, u_files.get_file_display_name(file), u_args[ARGS_PLAIN_ONLY])
elif u_args[ARGS_HEX_EDITOR]:
with IoHelper.dup_stdin(on_windows_os, u_args[ARGS_STDIN]):
with IoHelper.dup_stdin(u_args[ARGS_STDIN]):
for file in known_files:
HexEditor.open(file, u_files.get_file_display_name(file))

Expand Down
8 changes: 3 additions & 5 deletions cat_win/src/service/clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
clipboard
"""

import os
import sys

from cat_win.src.service.helper.environment import get_py_executable
from cat_win.src.service.helper.iohelper import err_print


Expand Down Expand Up @@ -52,7 +50,7 @@ def _copy(content: str, __dependency: int = 3, __clip_board_error: bool = False)
error_msg += "in order to use the '--clip' parameter.\n"
error_msg += 'Should you have any problem with either module, '
error_msg += 'try to install a different one using '
error_msg += f"'{os.path.basename(sys.executable)} -m pip install ...'"
error_msg += f"'{get_py_executable()} -m pip install ...'"
err_print('\n', error_msg, sep='')
return False
try:
Expand Down Expand Up @@ -115,7 +113,7 @@ def _paste(__dependency: int = 3, __clip_board_error: bool = False):
error_msg += "in order to use the '--clip' parameter.\n"
error_msg += 'Should you have any problem with either module, '
error_msg += 'try to install a different one using '
error_msg += f"'{os.path.basename(sys.executable)} -m pip install ...'"
error_msg += f"'{get_py_executable()} -m pip install ...'"
err_print('\n', error_msg, sep='')
return
try:
Expand Down
11 changes: 4 additions & 7 deletions cat_win/src/service/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from cat_win.src.service.helper.editorhelper import History, Position, _SearchIter, \
UNIFY_HOTKEYS, KEY_HOTKEYS, ACTION_HOTKEYS, SCROLL_HOTKEYS, MOVE_HOTKEYS, \
SELECT_HOTKEYS, HISTORY_HOTKEYS, INDENT_HOTKEYS, HEX_BYTE_KEYS
from cat_win.src.service.helper.environment import on_windows_os
from cat_win.src.service.helper.iohelper import IoHelper, err_print
from cat_win.src.service.clipboard import Clipboard
from cat_win.src.service.rawviewer import SPECIAL_CHARS
Expand All @@ -33,7 +34,6 @@ class Editor:
auto_indent = False

save_with_alt = False
on_windows_os = False
debug_mode = False

unicode_escaped_search = True
Expand Down Expand Up @@ -1527,7 +1527,7 @@ def open(cls, file: Path, display_name: str, skip_binary: bool = False) -> bool:

if CURSES_MODULE_ERROR:
err_print("The Editor could not be loaded. No Module 'curses' was found.")
if Editor.on_windows_os:
if on_windows_os:
err_print('If you are on Windows OS, try pip-installing ', end='')
err_print("'windows-curses'.")
err_print()
Expand All @@ -1540,7 +1540,7 @@ def open(cls, file: Path, display_name: str, skip_binary: bool = False) -> bool:
special_chars = dict(map(lambda x: (chr(x[0]), x[2]), SPECIAL_CHARS))
editor._set_special_chars(special_chars)

if Editor.on_windows_os:
if on_windows_os:
# disable background feature on windows
editor._action_background = lambda *_: True
else:
Expand All @@ -1567,7 +1567,7 @@ def set_indentation(indentation: str = '\t', auto_indent: bool = True) -> None:
Editor.auto_indent = auto_indent

@staticmethod
def set_flags(save_with_alt: bool, on_windows_os: bool, debug_mode: bool,
def set_flags(save_with_alt: bool, debug_mode: bool,
unicode_escaped_search: bool, unicode_escaped_replace: bool,
file_encoding: str) -> None:
"""
Expand All @@ -1576,8 +1576,6 @@ def set_flags(save_with_alt: bool, on_windows_os: bool, debug_mode: bool,
Parameters:
save_with_alt (bool):
indicates whetcher the stdin pipe has been used (and therefor tampered)
on_windows_os (bool):
indicates if the user is on windows OS using platform.system() == 'Windows'
debug_mode (bool)
indicates if debug info should be displayed
unicode_escaped_search (bool):
Expand All @@ -1586,7 +1584,6 @@ def set_flags(save_with_alt: bool, on_windows_os: bool, debug_mode: bool,
the file encoding to use when opening a file
"""
Editor.save_with_alt = save_with_alt
Editor.on_windows_os = on_windows_os
Editor.debug_mode = debug_mode
Editor.unicode_escaped_search = unicode_escaped_search
Editor.unicode_escaped_replace = unicode_escaped_replace
Expand Down
12 changes: 4 additions & 8 deletions cat_win/src/service/fileattributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
except ImportError:
pass

from cat_win.src.service.helper.environment import on_windows_os
from cat_win.src.service.helper.winstreams import WinStreams


Expand Down Expand Up @@ -233,7 +234,7 @@ def get_file_mtime(file: Path) -> float:
except OSError:
return 0.0

def get_file_meta_data(file: Path, res_path: str, on_windows_os: bool, colors = None) -> str:
def get_file_meta_data(file: Path, res_path: str, colors = None) -> str:
"""
calculate file metadata information.
Expand All @@ -242,9 +243,6 @@ def get_file_meta_data(file: Path, res_path: str, on_windows_os: bool, colors =
a string representation of a file (-path)
res_path (str);
the path to the signatures database
on_windows_os (bool):
indicates if the user is on windows OS using
platform.system() == 'Windows'
colors (list):
a list containing the ANSI-Colorcodes to display
the attributes like [RESET_ALL, ATTRIB, +ATTRIB, -ATTRIB]
Expand Down Expand Up @@ -299,17 +297,15 @@ def get_file_meta_data(file: Path, res_path: str, on_windows_os: bool, colors =
except OSError:
return ''

def print_meta(file: Path, res_path: str, on_windows_os: bool, colors: list) -> None:
def print_meta(file: Path, res_path: str, colors: list) -> None:
"""
print the information retrieved by get_file_meta_data()
Parameters:
file (Path):
a string representation of a file (-path)
on_windows_os (bool):
indicates if the current system is Windows
colors (list):
[reset, attributes, positive_attr, negative_attr] color codes
"""
meta_data = get_file_meta_data(file, res_path, on_windows_os, colors)
meta_data = get_file_meta_data(file, res_path, colors)
print(meta_data)
25 changes: 25 additions & 0 deletions cat_win/src/service/helper/environment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
environment
"""

import os
import platform
import sys


on_windows_os = platform.system() == 'Windows'

def get_py_executable() -> str:
"""
get the most likely python executable
Returns:
py_executable (str):
the python executable used to start the current process
"""
py_executable = sys.executable
if os.path.dirname(py_executable) in os.environ['PATH'].split(os.pathsep):
py_executable = os.path.basename(py_executable)
elif ' ' in py_executable:
py_executable = f'"{py_executable}"' if on_windows_os else py_executable.replace(' ', '\\ ')
return py_executable
10 changes: 3 additions & 7 deletions cat_win/src/service/helper/iohelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import os
import sys

from cat_win.src.service.helper.environment import on_windows_os
from cat_win.src.service.helper.progressbar import PBar


Expand Down Expand Up @@ -334,7 +335,7 @@ def write_files(file_list: list, content: str, file_encoding: str) -> list:


@staticmethod
def read_write_files_from_stdin(file_list: list, file_encoding: str, on_windows_os: bool,
def read_write_files_from_stdin(file_list: list, file_encoding: str,
one_line: bool = False) -> list:
"""
Write stdin input to multiple files.
Expand All @@ -344,9 +345,6 @@ def read_write_files_from_stdin(file_list: list, file_encoding: str, on_windows_
all files that should be written
file_encoding (str):
the encoding to use for writing the files
on_windows_os (bool):
indicates if the user is on windows OS using
platform.system() == 'Windows'
one_line (bool):
determines if only the first stdin line should be read
Expand All @@ -370,13 +368,11 @@ def read_write_files_from_stdin(file_list: list, file_encoding: str, on_windows_

@staticmethod
@contextlib.contextmanager
def dup_stdin(on_windows_os: bool, dup: bool = True):
def dup_stdin(dup: bool = True):
"""
dup the stdin so the user can interact while also piping into cat.
Parameters:
on_windows_os (bool):
indicates if the current system is Windows
dup (bool):
is this is false the function will not do anything.
only implemented to eliminate repeated code somewhere else
Expand Down
11 changes: 4 additions & 7 deletions cat_win/src/service/hexeditor.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from cat_win.src.const.escapecodes import ESC_CODE
from cat_win.src.service.helper.editorhelper import Position, UNIFY_HOTKEYS, \
KEY_HOTKEYS, ACTION_HOTKEYS, MOVE_HOTKEYS, SELECT_HOTKEYS, HEX_BYTE_KEYS
from cat_win.src.service.helper.environment import on_windows_os
from cat_win.src.service.helper.iohelper import IoHelper, err_print
from cat_win.src.service.clipboard import Clipboard
from cat_win.src.service.rawviewer import get_display_char_gen
Expand All @@ -27,7 +28,6 @@ class HexEditor:
loading_failed = False

save_with_alt = False
on_windows_os = False
debug_mode = False

unicode_escaped_search = True
Expand Down Expand Up @@ -1065,7 +1065,7 @@ def open(cls, file: Path, display_name: str) -> bool:

if CURSES_MODULE_ERROR:
err_print("The Editor could not be loaded. No Module 'curses' was found.")
if HexEditor.on_windows_os:
if on_windows_os:
err_print('If you are on Windows OS, try pip-installing ', end='')
err_print("'windows-curses'.")
err_print()
Expand All @@ -1074,7 +1074,7 @@ def open(cls, file: Path, display_name: str) -> bool:

editor = cls(file, display_name)

if HexEditor.on_windows_os:
if on_windows_os:
# disable background feature on windows
editor._action_background = lambda *_: True
else:
Expand All @@ -1086,16 +1086,14 @@ def open(cls, file: Path, display_name: str) -> bool:
return editor.changes_made

@staticmethod
def set_flags(save_with_alt: bool, on_windows_os: bool, debug_mode: bool,
def set_flags(save_with_alt: bool, debug_mode: bool,
unicode_escaped_search: bool, columns: int) -> None:
"""
set the config flags for the Editor
Parameters:
save_with_alt (bool):
indicates whetcher the stdin pipe has been used (and therefor tampered)
on_windows_os (bool):
indicates if the user is on windows OS using platform.system() == 'Windows'
debug_mode (bool)
indicates if debug info should be displayed
unicode_escaped_search (bool):
Expand All @@ -1104,7 +1102,6 @@ def set_flags(save_with_alt: bool, on_windows_os: bool, debug_mode: bool,
defines how many columns the editor should have
"""
HexEditor.save_with_alt = save_with_alt
HexEditor.on_windows_os = on_windows_os
HexEditor.debug_mode = debug_mode
HexEditor.unicode_escaped_search = unicode_escaped_search
HexEditor.columns = columns
Loading

0 comments on commit 5f54ffa

Please sign in to comment.