Amended files to adhere to flake8 and mypy

Files changed in accordance with flake8 and mypy reports and defined
sections which should be ignored by the systems.
This commit is contained in:
Ethan Smith-Coss 2022-05-04 21:26:51 +01:00
parent 38ce833bb1
commit 8ef1891ca6
Signed by: TheOnePath
GPG Key ID: 4E7D436CE1A0BAF1
3 changed files with 41 additions and 40 deletions

View File

@ -1,14 +1,14 @@
from __future__ import annotations
import os import os
import sys import sys
from io import TextIOWrapper from io import TextIOWrapper
from typing import TextIO, Union from typing import IO, Any, Type, Union
from collections import namedtuple from collections import namedtuple
from .utils import common from .utils import common
from .utils import printfmt from .utils import printfmt
class Logger: ... # class delcaration
class Logger: # class redeclaration & initialisation class Logger: # class redeclaration & initialisation
"""A simple logging class to write messages directly to the console """A simple logging class to write messages directly to the console
or to a log file. or to a log file.
@ -47,21 +47,21 @@ class Logger: # class redeclaration & initialisation
not writing to console on STDOUT or STDERR. not writing to console on STDOUT or STDERR.
""" """
## set the PIPE to STDOUT by default ## set the PIPE to STDOUT by default
__stdpipe: TextIO = sys.stdout __stdpipe: IO[Any] = sys.stdout
## detect if there's a redirect ## detect if there's a redirect
__IS_STDOUT_REDIR: bool = os.isatty(sys.stdout.fileno()) __IS_STDOUT_REDIR: bool = os.isatty(sys.stdout.fileno())
__IS_STDERR_REDIR: bool = os.isatty(sys.stderr.fileno()) __IS_STDERR_REDIR: bool = os.isatty(sys.stderr.fileno())
## the default log out file ## the default log out file
__DEFAULT_OUT_FILE: str = "dump.log" __DEFAULT_OUT_FILE: str = "dump.log"
## log info namedtuple for storing class states ## log info namedtuple for storing class states
__LOG_INFO_TUPLE = namedtuple('LogInfo', __LOG_INFO_TUPLE = namedtuple('__LOG_INFO_TUPLE',
['isatty', 'lv', 'msg', 'sep', 'end']) ['isatty', 'lv', 'msg', 'sep', 'end'])
## create instance attribute for class singleton ## create instance attribute for class singleton
__instance__ = None __instance__ = None
## create instance attribute as read-only for log location ## create instance attribute as read-only for log location
log = None log = None
def __new__(cls, *, out_f: str = ...) -> Logger: def __new__(cls, *, out_f: Union[str, None] = None) -> Logger:
"""Construct a new instance of the class and initialise it. """Construct a new instance of the class and initialise it.
Constructor method is used to establish the class as a Constructor method is used to establish the class as a
@ -73,7 +73,7 @@ class Logger: # class redeclaration & initialisation
cls.__instance__ = super(Logger, cls).__new__(cls) # establish singleton instance cls.__instance__ = super(Logger, cls).__new__(cls) # establish singleton instance
cls.log = cls.__DEFAULT_OUT_FILE # initialise attribute to default cls.log = cls.__DEFAULT_OUT_FILE # initialise attribute to default
## handle if a custom file pathspec was given ## handle if a custom file pathspec was given
if out_f is not Ellipsis and isinstance(out_f, str): if out_f is not None and isinstance(out_f, str):
## verify path and convert to real pathspec. ## verify path and convert to real pathspec.
if common.is_path_spec(out_f): if common.is_path_spec(out_f):
## redefine the default log out attribute and create ## redefine the default log out attribute and create
@ -81,7 +81,9 @@ class Logger: # class redeclaration & initialisation
cls.log = cls.__DEFAULT_OUT_FILE = \ cls.log = cls.__DEFAULT_OUT_FILE = \
os.path.realpath(out_f).strip('"') os.path.realpath(out_f).strip('"')
cls.__loginfo = None # default the namedtuple to None on first instance cls.__loginfo: Logger.__LOG_INFO_TUPLE = Logger.__LOG_INFO_TUPLE(
*([None] * 5)
) # default the namedtuple to None on first instance
cls.printLog2File("----[New instance of script has been started]----", cls.printLog2File("----[New instance of script has been started]----",
file=cls.__DEFAULT_OUT_FILE, mode='w') file=cls.__DEFAULT_OUT_FILE, mode='w')
@ -91,7 +93,7 @@ class Logger: # class redeclaration & initialisation
@classmethod @classmethod
def debug(cls, *value: object, sep: Union[str, None] = None, def debug(cls, *value: object, sep: Union[str, None] = None,
end: Union[str, None] = None, wrapping: bool = True, end: Union[str, None] = None, wrapping: bool = True,
strace: bool = True) -> Logger: strace: bool = True) -> Type[Logger]:
"""Pseudolog for writing to log file with level `LogLevel.DEBUG`. """Pseudolog for writing to log file with level `LogLevel.DEBUG`.
Method is invoked on a `Logger` instance and will directly write Method is invoked on a `Logger` instance and will directly write
@ -106,7 +108,7 @@ class Logger: # class redeclaration & initialisation
wrapping=wrapping, strace=strace) wrapping=wrapping, strace=strace)
Logger.__stdpipe = sys.stderr Logger.__stdpipe = sys.stderr
cls.__loginfo: namedtuple = Logger.__LOG_INFO_TUPLE( cls.__loginfo = Logger.__LOG_INFO_TUPLE(
Logger.__IS_STDERR_REDIR, common.LogLevel.DEBUG, value, sep, end Logger.__IS_STDERR_REDIR, common.LogLevel.DEBUG, value, sep, end
) )
@ -115,7 +117,7 @@ class Logger: # class redeclaration & initialisation
@classmethod @classmethod
def warn(cls, *value: object, sep: Union[str, None] = None, def warn(cls, *value: object, sep: Union[str, None] = None,
end: Union[str, None] = None, wrapping: bool = True, end: Union[str, None] = None, wrapping: bool = True,
strace: bool = True) -> Logger: strace: bool = True) -> Type[Logger]:
"""Pseudolog for writing to log file with level `LogLevel.WARN`. """Pseudolog for writing to log file with level `LogLevel.WARN`.
Method is invoked on a `Logger` instance and will directly write Method is invoked on a `Logger` instance and will directly write
@ -130,7 +132,7 @@ class Logger: # class redeclaration & initialisation
end=end, wrapping=wrapping, strace=strace) end=end, wrapping=wrapping, strace=strace)
Logger.__stdpipe = sys.stderr Logger.__stdpipe = sys.stderr
cls.__loginfo: namedtuple = Logger.__LOG_INFO_TUPLE( cls.__loginfo = Logger.__LOG_INFO_TUPLE(
Logger.__IS_STDERR_REDIR, common.LogLevel.WARN, value, sep, end Logger.__IS_STDERR_REDIR, common.LogLevel.WARN, value, sep, end
) )
@ -139,7 +141,7 @@ class Logger: # class redeclaration & initialisation
@classmethod @classmethod
def error(cls, *value: object, sep: Union[str, None] = None, def error(cls, *value: object, sep: Union[str, None] = None,
end: Union[str, None] = None, wrapping: bool = True, end: Union[str, None] = None, wrapping: bool = True,
strace: bool = True) -> Logger: strace: bool = True) -> Type[Logger]:
"""Pseudolog for writing to log file with level `LogLevel.ERROR`. """Pseudolog for writing to log file with level `LogLevel.ERROR`.
Method is invoked on a `Logger` instance and will directly write Method is invoked on a `Logger` instance and will directly write
@ -154,7 +156,7 @@ class Logger: # class redeclaration & initialisation
end=end, wrapping=wrapping, strace=strace) end=end, wrapping=wrapping, strace=strace)
Logger.__stdpipe = sys.stderr Logger.__stdpipe = sys.stderr
cls.__loginfo: namedtuple = Logger.__LOG_INFO_TUPLE( cls.__loginfo = Logger.__LOG_INFO_TUPLE(
Logger.__IS_STDERR_REDIR, common.LogLevel.ERROR, value, sep, end Logger.__IS_STDERR_REDIR, common.LogLevel.ERROR, value, sep, end
) )
@ -183,7 +185,7 @@ class Logger: # class redeclaration & initialisation
@staticmethod @staticmethod
def printLog2File(*value: object, def printLog2File(*value: object,
level: Union[common.LogLevel, int] = common.LogLevel.DEBUG, level: Union[common.LogLevel, int] = common.LogLevel.DEBUG,
mode: str = 'a', file: Union[TextIOWrapper, str] = ..., mode: str = 'a', file: Union[TextIOWrapper, str, None] = None,
sep: Union[str, None] = None, end: Union[str, None] = None, sep: Union[str, None] = None, end: Union[str, None] = None,
wrapping: bool = True, strace: bool = True, header: bool = True) -> None: wrapping: bool = True, strace: bool = True, header: bool = True) -> None:
"""Wrapper method over the built-in `print()` function defined """Wrapper method over the built-in `print()` function defined
@ -233,7 +235,13 @@ class Logger: # class redeclaration & initialisation
the default pathspec used is defined by the `Logger` instance. the default pathspec used is defined by the `Logger` instance.
""" """
## handle if no file parameter was given ## handle if no file parameter was given
if file is Ellipsis or not os.path.exists(file): if file is None or not isinstance(file, (TextIOWrapper, str)):
file = Logger.__DEFAULT_OUT_FILE
if not isinstance(file, str):
file = file.name
if not os.path.exists(file):
file = Logger.__DEFAULT_OUT_FILE file = Logger.__DEFAULT_OUT_FILE
_frame = sys._getframe(2) if sys._getframe(1).f_code.co_name in \ _frame = sys._getframe(2) if sys._getframe(1).f_code.co_name in \
@ -242,33 +250,29 @@ class Logger: # class redeclaration & initialisation
_fname = _frame.f_code.co_filename.removeprefix( _fname = _frame.f_code.co_filename.removeprefix(
os.getcwd()).strip('\\/') os.getcwd()).strip('\\/')
## generate new header for log file and construct new message ## generate new header for log file and construct new message
_val = [*map(str, value)] # convert all objects to string
if header: if header:
msg = printfmt.gen_log_header(level).format( msg = printfmt.gen_log_header(level).format(
" ".join(value), CALLER="{0}:{1}[{2}]".format( " ".join(_val), CALLER="{0}:{1}[{2}]".format(
_fname, _frame.f_code.co_name, _frame.f_lineno _fname, _frame.f_code.co_name, _frame.f_lineno
).replace("module", "global") if strace else "LOGGER" ).replace("module", "global") if strace else "LOGGER"
) )
else: else:
msg = " ".join(value) msg = " ".join(_val)
# perform wrapping of message and indent wrapped lines # perform wrapping of message and indent wrapped lines
if wrapping: if wrapping:
msg = printfmt.wrap(msg).replace('\n', '\n\t') msg = printfmt.wrap(msg).replace('\n', '\n\t')
if isinstance(file, str): with open(file, mode, encoding="utf-8") as log:
with open(file, mode, encoding="utf-8") as log: Logger.__stdpipe = log # pre-requisite to write PIPE to file
Logger.__stdpipe = log # pre-requisite to write PIPE to file
Logger.__printLog__(False, level, (msg,), sep, end, False)
elif isinstance(file, TextIOWrapper):
Logger.__stdpipe = log
Logger.__printLog__(False, level, (msg,), sep, end, False) Logger.__printLog__(False, level, (msg,), sep, end, False)
@staticmethod @staticmethod
def printLog(*value: object, def printLog(*value: object,
level: Union[int, common.LogLevel] = common.LogLevel.NORMAL, level: Union[int, common.LogLevel] = common.LogLevel.NORMAL,
sep: Union[str, None] = None, end: Union[str, None] = None, sep: Union[str, None] = None, end: Union[str, None] = None,
file: Union[TextIOWrapper, None] = None, file=None, flush: bool = True) -> None:
flush: bool = True) -> None:
"""Wrapper method over the built-in `print()` function defined """Wrapper method over the built-in `print()` function defined
using 3.x syntax. All Familiar functionality can be passed to using 3.x syntax. All Familiar functionality can be passed to
the method as found when calling `print()`, but comes with added the method as found when calling `print()`, but comes with added
@ -312,7 +316,7 @@ class Logger: # class redeclaration & initialisation
## configure PIPE to STDERR if logging is high enough ## configure PIPE to STDERR if logging is high enough
if file is None: if file is None:
if level >= common.LogLevel.DEBUG: if level >= common.LogLevel.DEBUG: # type: ignore
Logger.__stdpipe = sys.stderr Logger.__stdpipe = sys.stderr
else: else:
Logger.__stdpipe = sys.stdout Logger.__stdpipe = sys.stdout
@ -330,7 +334,7 @@ class Logger: # class redeclaration & initialisation
### :@NOTE: if there's a PIPE redirect, don't use colour ### :@NOTE: if there's a PIPE redirect, don't use colour
### for that redirect PIPE ### for that redirect PIPE
if level < common.LogLevel.WARN: # handle output for STDOUT if level < common.LogLevel.WARN: # type: ignore # handle output for STDOUT
Logger.__printLog__(Logger.__IS_STDOUT_REDIR, level, value, Logger.__printLog__(Logger.__IS_STDOUT_REDIR, level, value,
sep, end, flush) sep, end, flush)
else: # handle output for STDERR else: # handle output for STDERR
@ -338,21 +342,20 @@ class Logger: # class redeclaration & initialisation
sep, end, flush) sep, end, flush)
@staticmethod @staticmethod
def __printLog__(isatty: bool, lv: common.LogLevel, msg: object, def __printLog__(isatty: bool, lv: Union[common.LogLevel, int],
s: Union[str, None] = None, e: Union[str, None] = None, msg: object, s: Union[str, None] = None,
flsh: bool = True) -> None: e: Union[str, None] = None, flsh: bool = True) -> None:
"""Private helper method responsible for invoking the built-in """Private helper method responsible for invoking the built-in
`print` function with appropriate keyword arugments. Method `print` function with appropriate keyword arugments. Method
identifies the PIPE used and provide text highlighting accordingly. identifies the PIPE used and provide text highlighting accordingly.
""" """
## handle if we have a redirect ## handle if we have a redirect
if isatty and (Logger.__stdpipe is sys.stdout if isatty and (Logger.__stdpipe is sys.stdout or Logger.__stdpipe is sys.stderr):
or Logger.__stdpipe is sys.stderr):
## write ANSI code to start coloured text ## write ANSI code to start coloured text
print(printfmt.log_as_col(lv), end="", file=Logger.__stdpipe, flush=flsh) print(printfmt.log_as_col(lv), end="", file=Logger.__stdpipe, flush=flsh)
## unpack the object and pass to print ## unpack the object and pass to print
print(*msg, sep=s, end="", file=Logger.__stdpipe, flush=flsh) print(*msg, sep=s, end="", file=Logger.__stdpipe, flush=flsh) # type: ignore
## reset the colour sequence back to normal ## reset the colour sequence back to normal
print(printfmt.Colours.NORMAL, end=e, file=Logger.__stdpipe, flush=flsh) print(printfmt.Colours.NORMAL, end=e, file=Logger.__stdpipe, flush=flsh)
else: else:
print(*msg, sep=s, end=e, file=Logger.__stdpipe, flush=flsh) print(*msg, sep=s, end=e, file=Logger.__stdpipe, flush=flsh) # type: ignore

View File

@ -49,6 +49,5 @@ def is_path_spec(path_spec: str) -> bool:
## perform a regex match to ensure that the given path is a ## perform a regex match to ensure that the given path is a
## valid pathspec for the system. ## valid pathspec for the system.
return bool(re.match( return bool(re.match(
__REGEX_PAT, path_spec.strip(r"\"'")) __REGEX_PAT, path_spec.strip(r"\"'")) or re.match(r'^[\w\d\-_]+$', path_spec.strip(r"\"'"))
or re.match(r'^[\w\d\-_]+$', path_spec.strip(r"\"'"))
) )

View File

@ -38,7 +38,7 @@ def loglevel_as_str(level: Union[LogLevel, int]) -> str:
return " " * 5 return " " * 5
def log_as_col(level: Union[int, LogLevel]) -> Colours: def log_as_col(level: Union[int, LogLevel]) -> str:
"""Convert an integer or enum value into an associated ANSI escape """Convert an integer or enum value into an associated ANSI escape
code terminal colour sequence. Depending on log level severity, an code terminal colour sequence. Depending on log level severity, an
associated colour is returned to give STDOUT text a distinct associated colour is returned to give STDOUT text a distinct
@ -95,9 +95,8 @@ def gen_log_header(_type: Union[LogLevel, int, str]) -> str:
_type = loglevel_as_str(_type) _type = loglevel_as_str(_type)
## return newly formatted log message header ## return newly formatted log message header
return __LOG_TMPL.format('{CALLER}', DATE=\ return __LOG_TMPL.format('{CALLER}', TYPE=_type,
time.strftime(__TIMESTAMP_FMT, time.localtime()), DATE=time.strftime(__TIMESTAMP_FMT, time.localtime())) + "{0}"
TYPE=_type) + "{0}"
def wrap(value: str, *, width: int = 120, tb_size: int = 4) -> str: def wrap(value: str, *, width: int = 120, tb_size: int = 4) -> str: