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.
@ -89,7 +88,6 @@ class Logger: # class redeclaration & initialisation
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,
@ -107,15 +105,13 @@ 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,
@ -130,17 +126,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.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,
@ -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
@ -247,10 +240,10 @@ class Logger: # class redeclaration & initialisation
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,8 +253,7 @@ 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:
@ -271,9 +263,9 @@ 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,
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: Union[TextIOWrapper, None] = None,
flush: bool = True) -> None: flush: bool = True) -> None:
@ -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,24 +323,22 @@ 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
@ -356,13 +346,13 @@ class Logger: # class redeclaration & initialisation
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

@ -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

@ -29,7 +29,7 @@ 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.