Updated files to flake8 standard

Files have been changed to ensure they abid flake8 defined rules that
have not been identified as ignored. Files mostly pass flake8 rules.
This commit is contained in:
Ethan Smith-Coss 2022-05-04 01:13:13 +01:00
parent c0eff133a9
commit 3fe521bcf5
Signed by: TheOnePath
GPG Key ID: 4E7D436CE1A0BAF1
3 changed files with 56 additions and 64 deletions

View File

@ -5,7 +5,7 @@ from typing import TextIO, Union
from collections import namedtuple from collections import namedtuple
from .utils import common from .utils import common
from .utils.printfmt import * from .utils import printfmt
class Logger: ... # class delcaration class Logger: ... # class delcaration
@ -61,7 +61,6 @@ class Logger: # class redeclaration & initialisation
## 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: str = ...) -> Logger:
"""Construct a new instance of the class and initialise it. """Construct a new instance of the class and initialise it.
@ -81,19 +80,18 @@ class Logger: # class redeclaration & initialisation
## public attribute for the currect log location ## public attribute for the currect log location
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 = None # 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')
return cls.__instance__
return cls.__instance__
@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) -> 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
@ -107,19 +105,17 @@ class Logger: # class redeclaration & initialisation
Logger.printLog2File(*value, sep=sep, end=end, Logger.printLog2File(*value, sep=sep, end=end,
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: namedtuple = Logger.__LOG_INFO_TUPLE(
Logger.__IS_STDERR_REDIR, LogLevel.DEBUG, value, sep, end Logger.__IS_STDERR_REDIR, common.LogLevel.DEBUG, value, sep, end
) )
return cls
return cls
@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) -> 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,21 +126,20 @@ class Logger: # class redeclaration & initialisation
method can be invoked directly afterwards (or later) to write method can be invoked directly afterwards (or later) to write
the same message to the console. the same message to the console.
""" """
Logger.printLog2File(*value, level=LogLevel.WARN, sep=sep, Logger.printLog2File(*value, level=common.LogLevel.WARN, sep=sep,
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: namedtuple = Logger.__LOG_INFO_TUPLE(
Logger.__IS_STDERR_REDIR, LogLevel.WARN, value, sep, end Logger.__IS_STDERR_REDIR, common.LogLevel.WARN, value, sep, end
) )
return cls
return cls
@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) -> 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
@ -155,17 +150,16 @@ class Logger: # class redeclaration & initialisation
method can be invoked directly afterwards (or later) to write method can be invoked directly afterwards (or later) to write
the same message to the console. the same message to the console.
""" """
Logger.printLog2File(*value, level=LogLevel.ERROR, sep=sep, Logger.printLog2File(*value, level=common.LogLevel.ERROR, sep=sep,
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: namedtuple = Logger.__LOG_INFO_TUPLE(
Logger.__IS_STDERR_REDIR, LogLevel.ERROR, value, sep, end Logger.__IS_STDERR_REDIR, common.LogLevel.ERROR, value, sep, end
) )
return cls return cls
@staticmethod @staticmethod
def withConsole() -> None: def withConsole() -> None:
"""Write the last message logged to a file to the console as """Write the last message logged to a file to the console as
@ -181,18 +175,17 @@ class Logger: # class redeclaration & initialisation
information regarding the formatting of the message is directly information regarding the formatting of the message is directly
associated to the formatting used when writing to a log file. associated to the formatting used when writing to a log file.
""" """
if not Logger.__loginfo is None: if Logger.__loginfo is not None:
Logger.__printLog__(Logger.__loginfo.isatty, Logger.__printLog__(Logger.__loginfo.isatty,
Logger.__loginfo.lv, Logger.__loginfo.msg, Logger.__loginfo.lv, Logger.__loginfo.msg,
Logger.__loginfo.sep, Logger.__loginfo.end) Logger.__loginfo.sep, Logger.__loginfo.end)
@staticmethod @staticmethod
def printLog2File(*value: object, def printLog2File(*value: object,
level: Union[LogLevel, int] = LogLevel.DEBUG, mode: str = 'a', level: Union[common.LogLevel, int] = common.LogLevel.DEBUG,
file: Union[TextIOWrapper, str] = ..., sep: Union[str, None] = None, mode: str = 'a', file: Union[TextIOWrapper, str] = ...,
end: Union[str, None] = None, wrapping: bool = True, sep: Union[str, None] = None, end: Union[str, None] = None,
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
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
@ -241,16 +234,16 @@ class Logger: # class redeclaration & initialisation
""" """
## 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 Ellipsis or 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 \
dir(Logger) else sys._getframe(1) dir(Logger) else sys._getframe(1)
## get the executing filename of where log was called ## get the executing filename of where log was called
_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
if header: if header:
msg = gen_log_header(level).format( msg = printfmt.gen_log_header(level).format(
" ".join(value), CALLER="{0}:{1}[{2}]".format( " ".join(value), 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"
@ -260,9 +253,8 @@ class Logger: # class redeclaration & initialisation
# perform wrapping of message and indent wrapped lines # perform wrapping of message and indent wrapped lines
if wrapping: if wrapping:
msg = wrap(msg).replace('\n', '\n\t') msg = printfmt.wrap(msg).replace('\n', '\n\t')
if isinstance(file, str): 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
@ -271,12 +263,12 @@ class Logger: # class redeclaration & initialisation
Logger.__stdpipe = log 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, level: Union[int, LogLevel] = LogLevel.NORMAL, def printLog(*value: object,
sep: Union[str, None] = None, end: Union[str, None] = None, level: Union[int, common.LogLevel] = common.LogLevel.NORMAL,
file: Union[TextIOWrapper, None] = None, sep: Union[str, None] = None, end: Union[str, None] = None,
flush: bool = True) -> None: file: Union[TextIOWrapper, None] = 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
@ -320,7 +312,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 >= LogLevel.DEBUG: if level >= common.LogLevel.DEBUG:
Logger.__stdpipe = sys.stderr Logger.__stdpipe = sys.stderr
else: else:
Logger.__stdpipe = sys.stdout Logger.__stdpipe = sys.stdout
@ -331,38 +323,36 @@ class Logger: # class redeclaration & initialisation
else: else:
Logger.printLog("Warning: logging function was called with a", Logger.printLog("Warning: logging function was called with a",
"file specifier parameter which is not a valid option.", "file specifier parameter which is not a valid option.",
level=LogLevel.WARN) level=common.LogLevel.WARN)
return return
## display message to console with appropriate colouring ## display message to console with appropriate colouring
### :@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 < LogLevel.WARN: ## handle output for STDOUT if level < common.LogLevel.WARN: # 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
Logger.__printLog__(Logger.__IS_STDERR_REDIR, level, value, Logger.__printLog__(Logger.__IS_STDERR_REDIR, level, value,
sep, end, flush) sep, end, flush)
@staticmethod @staticmethod
def __printLog__(isatty: bool, lv: LogLevel, msg: object, def __printLog__(isatty: bool, lv: common.LogLevel, msg: object,
s: Union[str, None] = None, e: Union[str, None] = None, s: Union[str, None] = None, e: Union[str, None] = None,
flsh: bool = True) -> 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 or \ if isatty and (Logger.__stdpipe is sys.stdout
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(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)
## reset the colour sequence back to normal ## reset the colour sequence back to normal
print(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)

View File

@ -11,7 +11,7 @@ __REGEX_PAT = re.compile(r'^(.+)[\\]([^\\]+)\\*$') \
class LogLevel: class LogLevel:
"""Enumerator structure to map an integer against a log level. """Enumerator structure to map an integer against a log level.
Higher `int` value means higher severity of level for logging. Higher `int` value means higher severity of level for logging.
""" """
NORMAL = 0 NORMAL = 0
@ -20,17 +20,18 @@ class LogLevel:
WARN = 3 WARN = 3
ERROR = 4 ERROR = 4
def is_path_spec(path_spec: str) -> bool: def is_path_spec(path_spec: str) -> bool:
"""Evaluate if a given string is a valid pathspec identifier. """Evaluate if a given string is a valid pathspec identifier.
Pathspec evaluation is matched against the following regular Pathspec evaluation is matched against the following regular
expression patterns: expression patterns:
```plaintext ```plaintext
OS Pathspec OS Pathspec
NT: ^(.+)[\\]([^\\]+)\\*$ NT: ^(.+)[\\\\]([^\\\\]+)\\*$
Other: ^(.+)[\/]([^\/]+)$ Other: ^(.+)[\\/]([^\\/]+)$
OR OR
Valid names of CWD subdirectories Valid names of CWD subdirectories
^[\w\d\-_]+$ ^[\\w\\d\\-_]+$
``` ```
The following pathspecs are evaluated as valid pathspec identifiers The following pathspecs are evaluated as valid pathspec identifiers
(OS implicitly implied): (OS implicitly implied):
@ -48,6 +49,6 @@ 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"\"'")) or \ __REGEX_PAT, path_spec.strip(r"\"'"))
re.match(r'^[\w\d\-_]+$', path_spec.strip(r"\"'")) or re.match(r'^[\w\d\-_]+$', path_spec.strip(r"\"'"))
) )

View File

@ -28,8 +28,8 @@ def loglevel_as_str(level: Union[LogLevel, int]) -> str:
""" """
## perform a lookup of each attribute of LogLevel and its associate ## perform a lookup of each attribute of LogLevel and its associate
## value, and search for the attribute that has the matching level ## value, and search for the attribute that has the matching level
## value passed to the function. ## value passed to the function.
_attrs = [_dir for _dir in dir(LogLevel) \ _attrs = [_dir for _dir in dir(LogLevel)
if not _dir.startswith('__')] # list of all attributes of LogLevel if not _dir.startswith('__')] # list of all attributes of LogLevel
for _ in _attrs: # iterate over all attributes defined for _ in _attrs: # iterate over all attributes defined
if getattr(LogLevel, _) == level: # if the level matches if getattr(LogLevel, _) == level: # if the level matches
@ -59,6 +59,7 @@ def log_as_col(level: Union[int, LogLevel]) -> Colours:
else: else:
return Colours.NORMAL return Colours.NORMAL
def gen_log_header(_type: Union[LogLevel, int, str]) -> str: def gen_log_header(_type: Union[LogLevel, int, str]) -> str:
"""Generate a header string for use of standardising log outputs. """Generate a header string for use of standardising log outputs.
@ -66,7 +67,7 @@ def gen_log_header(_type: Union[LogLevel, int, str]) -> str:
```plaintext ```plaintext
"[YYYY-MM-DDTHH:MM:SS+OFFSET] [{CALLER}] <LogLevel> {0}" "[YYYY-MM-DDTHH:MM:SS+OFFSET] [{CALLER}] <LogLevel> {0}"
``` ```
The first column defines the Date-Time following the ISO 8601 (long) The first column defines the Date-Time following the ISO 8601 (long)
standard timestamp format, whereby `T` is the separator between Date standard timestamp format, whereby `T` is the separator between Date
and Time. The `+OFFSET` is the number of hours ahead/behind UTC, the and Time. The `+OFFSET` is the number of hours ahead/behind UTC, the
@ -93,7 +94,7 @@ def gen_log_header(_type: Union[LogLevel, int, str]) -> str:
if not isinstance(_type, str): if not isinstance(_type, 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}', DATE=\
time.strftime(__TIMESTAMP_FMT, time.localtime()), time.strftime(__TIMESTAMP_FMT, time.localtime()),
TYPE=_type) + "{0}" TYPE=_type) + "{0}"
@ -109,4 +110,4 @@ def wrap(value: str, *, width: int = 120, tb_size: int = 4) -> str:
`@Params`: value - `str`, width = 120 - `int`, tb_size = 4 - `int` `@Params`: value - `str`, width = 120 - `int`, tb_size = 4 - `int`
`@Return`: `str` `@Return`: `str`
""" """
return "\n".join(textwrap.wrap(value, width=width, tabsize=tb_size)) return "\n".join(textwrap.wrap(value, width=width, tabsize=tb_size))