Added a couple of hints

This commit is contained in:
Maximilien Rigaut 2022-02-09 20:57:22 +01:00
parent 335c596e61
commit 6ee449b6ae
5 changed files with 65 additions and 7 deletions

View File

@ -5,26 +5,43 @@ import yaml
class ConfigLoader: class ConfigLoader:
""" """
Reads config files. Reads config files
:param configfile: The file to read
""" """
def __init__(self, configfile): def __init__(self, configfile):
"""
Loads config file
:param configfile: path to config file
:return: None
"""
with open(configfile, "r") as f: with open(configfile, "r") as f:
self.loaded_conf = yaml.safe_load(f) self.loaded_conf = yaml.safe_load(f)
def __getitem__(self, item): def __getitem__(self, item):
"""
Returns config value
:param item: config key
:return: config value
"""
try: try:
return self.loaded_conf[item] return self.loaded_conf[item]
except KeyError: except KeyError:
print("Argument", item, "not found.") print("Argument", item, "not found.")
def __repr__(self): def __repr__(self):
"""
Returns config as string
:return: config as string
"""
return self.loaded_conf.__repr__() return self.loaded_conf.__repr__()
class UserConfig(ConfigLoader): class UserConfig(ConfigLoader):
""" """
Reads user config file. Reads user config file.
:param configfile: path to config file
:return: None
""" """
def __init__(self, configfile): def __init__(self, configfile):
super().__init__(configfile) super().__init__(configfile)
@ -33,6 +50,8 @@ class UserConfig(ConfigLoader):
class GlobalConfig(ConfigLoader): class GlobalConfig(ConfigLoader):
""" """
Reads global config file. Reads global config file.
:param configfile: path to config file
:return: None
""" """
def __init__(self, configfile): def __init__(self, configfile):
super().__init__(configfile) super().__init__(configfile)

View File

@ -32,6 +32,7 @@ class Environment:
def integrity_check(self): def integrity_check(self):
""" """
Checks if all mandatory parameters are set. Checks if all mandatory parameters are set.
:return: True if all mandatory parameters are set, False otherwise.
""" """
for value in self._wasInitialised.values(): for value in self._wasInitialised.values():
if value is False: if value is False:
@ -41,6 +42,8 @@ class Environment:
def __getattr__(self, attribute): def __getattr__(self, attribute):
""" """
Getter for all parameters. Getter for all parameters.
:param attribute: The name of the parameter to get.
:return: The value of the parameter.
""" """
if attribute[0] == "_": if attribute[0] == "_":
super().__getattribute__(attribute) super().__getattribute__(attribute)
@ -54,6 +57,7 @@ class Environment:
def __setattr__(self, attribute, value): def __setattr__(self, attribute, value):
""" """
Setter for all parameters. Setter for all parameters.
:param attribute: The name of the parameter to set.
""" """
if attribute[0] == "_": if attribute[0] == "_":
super().__setattr__(attribute, value) super().__setattr__(attribute, value)

View File

@ -13,6 +13,12 @@ __all__ = _ERRORS+[]
def initlogging(filename=None, loglevel="ERROR", filemode='w', handler=None): def initlogging(filename=None, loglevel="ERROR", filemode='w', handler=None):
""" """
Initializes logging Initializes logging
:param filename: The name of the log file
:param loglevel: The level of logging
:type loglevel: str
:param filemode: The mode of the log file
:param handler: The handler to use
:return: None
""" """
loglevel = loglevel.upper() loglevel = loglevel.upper()
if loglevel not in ["ERROR", "INFO", "WARNING", "DEBUG", "CRITICAL"]: if loglevel not in ["ERROR", "INFO", "WARNING", "DEBUG", "CRITICAL"]:
@ -33,6 +39,10 @@ def initlogging(filename=None, loglevel="ERROR", filemode='w', handler=None):
def log_exception(exception, level="ERROR"): def log_exception(exception, level="ERROR"):
""" """
Logs an exception Logs an exception
:param exception: The exception to log
:param level: The level of the exception
:type level: str
:return: None
""" """
level = level.lower() level = level.lower()
logging.__getattribute__(level)(traceback.format_exc()) logging.__getattribute__(level)(traceback.format_exc())
@ -50,6 +60,12 @@ def log_exception(exception, level="ERROR"):
class ParsingError(Exception): class ParsingError(Exception):
""" """
Exception class for parsing errors Exception class for parsing errors
:param message: The message to display
:type message: str
:param line: The line number of the error
:param column: The column number of the error
:param file: The name of the file
:return: None
""" """
def __init__(self, message=None, line=None, column=None, file=None): def __init__(self, message=None, line=None, column=None, file=None):
@ -68,6 +84,7 @@ class ParsingError(Exception):
def __str__(self): def __str__(self):
""" """
Returns a string representation of the ParsingError Returns a string representation of the ParsingError
:return: The string representation of the ParsingError
""" """
if self.line is not None and self.column is not None and self.file is not None: if self.line is not None and self.column is not None and self.file is not None:
return "[{}] Line {}:{} {}".format(self.file, self.line, self.column, self.args[0]) return "[{}] Line {}:{} {}".format(self.file, self.line, self.column, self.args[0])

View File

@ -6,15 +6,26 @@ import os
class PathResolver: class PathResolver:
""" """
Initialised with a relative path and returns the translated absolute path Initialised with a relative path and returns the translated absolute path
:param base_path: Relative path to be resolved
""" """
def __init__(self, base_path): def __init__(self, base_path):
self.base_path = os.path.normpath(os.path.dirname(base_path)) self.base_path = os.path.normpath(os.path.dirname(base_path))
def __call__(self, relative_path='.'): def __call__(self, relative_path='.'):
"""
Returns the absolute path of the relative path
:param relative_path: Relative path to be resolved
:return: Absolute path
"""
return self.give_absolute(relative_path) return self.give_absolute(relative_path)
def give_absolute(self, relative_path='.'): def give_absolute(self, relative_path='.'):
"""
Returns the absolute path of the relative path
:param relative_path: Relative path to be resolved
:return: Absolute path
"""
return os.path.normpath(os.path.join(self.base_path, relative_path)) return os.path.normpath(os.path.join(self.base_path, relative_path))

View File

@ -21,11 +21,10 @@ class PreParser:
""" """
Initializes the PreParser object. Initializes the PreParser object.
Takes the following parameters: Takes the following parameters:
path: the path of the file to be parsed :param path: the path of the file to be parsed
__env: the environment object :param __env: the environment object
path_resolver: the path resolver object, if none is specified, a new one is created with the base path :param list_of_paths: the list of files that have been imported in this branch of the import tree
list_of_paths: the list of files that have been imported in this branch of the import tree :param dict_of_imports: Dictionary of all imports made to avoid duplicate file opening / pre-parsing
dict_of_imports: Dictionary of all imports made to avoid duplicate file opening / pre-parsing
""" """
if list_of_paths is None: if list_of_paths is None:
list_of_paths = [] list_of_paths = []
@ -46,6 +45,7 @@ class PreParser:
def open(self): def open(self):
""" """
Opens the file and returns a file object. Opens the file and returns a file object.
:return: the file object
""" """
self.file = open(self.relative_path_resolver(self.name), 'r') self.file = open(self.relative_path_resolver(self.name), 'r')
return self.file return self.file
@ -53,6 +53,7 @@ class PreParser:
def readlines(self): def readlines(self):
""" """
Reads the file and returns a list of lines. Reads the file and returns a list of lines.
:return: a list of lines
""" """
if self.file is None: if self.file is None:
self.open() self.open()
@ -63,6 +64,7 @@ class PreParser:
Creates a list of all files to be imported. Creates a list of all files to be imported.
Makes sure that the files are not already imported through a previous import statement. Makes sure that the files are not already imported through a previous import statement.
Recursively build a list of PreParser object for each file to be imported. Recursively build a list of PreParser object for each file to be imported.
:return: a list of PreParser objects
""" """
import_list = self.parse_import_list() import_list = self.parse_import_list()
for e, _ in import_list: for e, _ in import_list:
@ -80,6 +82,7 @@ class PreParser:
def parse_import_list(self): def parse_import_list(self):
""" """
Parses the import list of the file. Parses the import list of the file.
:return: a list of files to be imported
""" """
if self.saved_import_list: if self.saved_import_list:
return self.saved_import_list return self.saved_import_list
@ -99,6 +102,7 @@ class PreParser:
def export_with_imports(self): def export_with_imports(self):
""" """
Return the file object with all imports done Return the file object with all imports done
:return: a filelike object with all imports done
""" """
temp_file = StringIO() temp_file = StringIO()
source_line_count = 0 source_line_count = 0
@ -113,6 +117,7 @@ class PreParser:
def close(self): def close(self):
""" """
Closes the file. Closes the file.
:return: None
""" """
if self.file: if self.file:
self.file.close() self.file.close()
@ -127,6 +132,7 @@ class PreParser:
def __repr__(self): def __repr__(self):
""" """
Returns a string representation of the PreParser object. Returns a string representation of the PreParser object.
:return: a string representation of the PreParser object
""" """
return "PreParser(path={}, file={}, list_of_paths={}, dict_of_imports={})".format( return "PreParser(path={}, file={}, list_of_paths={}, dict_of_imports={})".format(
self.path, self.file, self.list_of_paths, self.global_dict_of_imports) self.path, self.file, self.list_of_paths, self.global_dict_of_imports)
@ -134,6 +140,7 @@ class PreParser:
def __str__(self): def __str__(self):
""" """
Returns a string representation of the PreParser object. Returns a string representation of the PreParser object.
:return: a string representation of the PreParser object
""" """
return self.__repr__() return self.__repr__()