Skip to content

Commit

Permalink
Apply the code formatter to the entire code base.
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicoretti committed Oct 23, 2024
1 parent 14a9de4 commit 63910ee
Show file tree
Hide file tree
Showing 19 changed files with 371 additions and 251 deletions.
1 change: 0 additions & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,3 @@
"github_url": "https://github.com/exasol/error-reporting-python",
"accent_color": "grass",
}

5 changes: 4 additions & 1 deletion exasol/error/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from exasol.error._error import ExaError, Parameter
from exasol.error._error import (
ExaError,
Parameter,
)

__all__ = ["ExaError", "Parameter"]
66 changes: 39 additions & 27 deletions exasol/error/_error.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import warnings
from dataclasses import dataclass
from inspect import cleandoc
from typing import Dict, Iterable, List, Mapping, Union
from pathlib import Path
from typing import (
Dict,
Iterable,
List,
Mapping,
Union,
)

with warnings.catch_warnings():
warnings.simplefilter("ignore")
Expand All @@ -18,11 +24,11 @@ class Parameter:

class Error:
def __init__(
self,
code: str,
message: str,
mitigations: Union[str, Iterable[str]],
parameters: Dict[str, Union[str, Parameter]],
self,
code: str,
message: str,
mitigations: Union[str, Iterable[str]],
parameters: Dict[str, Union[str, Parameter]],
):
# This function maybe flattened into or moved out of the constructor in the future.
def build_error(code, msg, mitigations, params):
Expand Down Expand Up @@ -62,38 +68,42 @@ def __str__(self) -> str:
"messagePlaceholders": [
{
"placeholder": "code",
"description": "Error code which was causing the error."
"description": "Error code which was causing the error.",
}
],
"mitigations": ["Ensure you follow the standard error code format."],
"sourceFile": Path(__file__).name
"sourceFile": Path(__file__).name,
},
"E-ERP-2": {
"identifier": "E-ERP-2",
"message": "Unknown error/exception occurred.",
"messagePlaceholders": [
{
"placeholder": "traceback",
"description": "Exception traceback which lead to the generation of this error."
"description": "Exception traceback which lead to the generation of this error.",
}
],
"description": "An unexpected error occurred during the creation of the error",
"mitigations": [cleandoc("""
"mitigations": [
cleandoc(
"""
A good starting point would be to investigate the cause of the attached exception.
Trackback:
{{traceback}}
""")],
"sourceFile": Path(__file__).name
"""
)
],
"sourceFile": Path(__file__).name,
},
}


def ExaError(
code: str,
message: str,
mitigations: Union[str, List[str]],
parameters: Mapping[str, Union[str, Parameter]],
code: str,
message: str,
mitigations: Union[str, List[str]],
parameters: Mapping[str, Union[str, Parameter]],
) -> Error:
"""Create a new ExaError.
Expand All @@ -112,36 +122,38 @@ def ExaError(
try:
return Error(code, message, mitigations, parameters)
except InvalidErrorCode:
error_code = 'E-ERP-1'
error_code = "E-ERP-1"
error_details = LIBRARY_ERRORS[error_code]
return Error(
code=error_details['identifier'],
message=error_details['message'],
mitigations=error_details['mitigations'],
parameters={"code": code}
code=error_details["identifier"],
message=error_details["message"],
mitigations=error_details["mitigations"],
parameters={"code": code},
)
except Exception as ex:
import traceback

tb = traceback.format_exc()
parameters = {"traceback": tb}
error_code = 'E-ERP-2'
error_code = "E-ERP-2"
error_details = LIBRARY_ERRORS[error_code]
return Error(
code=error_details['identifier'],
message=error_details['message'],
mitigations=error_details['mitigations'],
parameters=parameters
code=error_details["identifier"],
message=error_details["message"],
mitigations=error_details["mitigations"],
parameters=parameters,
)


def _create_error_code_definitions(version=None):
from exasol.error.version import VERSION

version = version or VERSION
return {
"$schema": "https://schemas.exasol.com/error_code_report-1.0.0.json",
"projectName": "exasol-error-reporting",
"projectVersion": version,
"errorCodes": [code for code in LIBRARY_ERRORS.values()]
"errorCodes": [code for code in LIBRARY_ERRORS.values()],
}


Expand Down
55 changes: 32 additions & 23 deletions exasol/error/_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,19 @@
from contextlib import ExitStack
from dataclasses import dataclass
from pathlib import Path
from typing import Generator, Iterable, List, Optional, Tuple, Union
from typing import (
Generator,
Iterable,
List,
Optional,
Tuple,
Union,
)

from exasol.error._report import ErrorCodeDetails, Placeholder
from exasol.error._report import (
ErrorCodeDetails,
Placeholder,
)


class _ExaErrorNodeWalker:
Expand Down Expand Up @@ -39,7 +49,12 @@ def _extract_parameters(node: ast.Call):
for keyword_argument in node.keywords:
kwargs[keyword_argument.arg] = keyword_argument.value

return kwargs["code"], kwargs["message"], kwargs["mitigations"], kwargs["parameters"]
return (
kwargs["code"],
kwargs["message"],
kwargs["mitigations"],
kwargs["parameters"],
)


class Validator:
Expand Down Expand Up @@ -69,7 +84,7 @@ def warnings(self) -> Iterable["Validator.Warning"]:
return self._warnings

def validate(
self, node: ast.Call, file: str
self, node: ast.Call, file: str
) -> Tuple[List["Validator.Error"], List["Validator.Warning"]]:
code: ast.Constant
message: ast.Constant
Expand Down Expand Up @@ -110,8 +125,7 @@ def _validate_message(self, node: ast.Constant, file: str):
if not isinstance(node, ast.Constant):
self._errors.append(
self.Error(
message=self._error_msg.format(
type="message", value=type(node)),
message=self._error_msg.format(type="message", value=type(node)),
file=file,
line_number=node.lineno,
)
Expand Down Expand Up @@ -150,8 +164,7 @@ def _validate_parameters(self, node: ast.Dict, file: str):
if not isinstance(key, ast.Constant):
self._errors.append(
self.Error(
message=self._error_msg.format(
type="key", value=type(key)),
message=self._error_msg.format(type="key", value=type(key)),
file=file,
line_number=key.lineno,
)
Expand Down Expand Up @@ -215,12 +228,14 @@ def normalize(params):
internalDescription=None,
potentialCauses=None,
mitigations=(
[m.value for m in mitigations.elts]
if isinstance(mitigations, ast.List)
else [mitigations.value]
)
if not isinstance(mitigations, str)
else [mitigations],
(
[m.value for m in mitigations.elts]
if isinstance(mitigations, ast.List)
else [mitigations.value]
)
if not isinstance(mitigations, str)
else [mitigations]
),
sourceFile=self._filename,
sourceLine=node.lineno,
contextHash=None,
Expand All @@ -236,21 +251,15 @@ def collect(self) -> None:
self._error_definitions.append(error_definition)


def parse_file(
file: Union[str, Path, io.FileIO]
) -> Tuple[
def parse_file(file: Union[str, Path, io.FileIO]) -> Tuple[
Iterable[ErrorCodeDetails],
Iterable["Validator.Warning"],
Iterable["Validator.Error"],
]:
with ExitStack() as stack:
f = (
file
if isinstance(file, io.TextIOBase)
else stack.enter_context(open(file, "r"))
)
f = file if isinstance(file, io.TextIOBase) else stack.enter_context(open(file))
root_node = ast.parse(f.read())
name = f.name if hasattr(f, 'name') else f'<{f.__class__.__name__}>'
name = f.name if hasattr(f, "name") else f"<{f.__class__.__name__}>"
collector = ErrorCollector(root_node, name)
collector.collect()

Expand Down
11 changes: 9 additions & 2 deletions exasol/error/_report.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import json
from dataclasses import asdict, dataclass, is_dataclass
from typing import List, Optional
from dataclasses import (
asdict,
dataclass,
is_dataclass,
)
from typing import (
List,
Optional,
)


class JsonEncoder(json.JSONEncoder):
Expand Down
7 changes: 6 additions & 1 deletion exasol/error/version.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# ATTENTION:
# This file is generated by exasol/toolbox/pre_commit_hooks/package_version.py when using:
# * either "poetry run nox -s fix"
# * or "poetry run version-check <path/version.py> --fix"
# Do not edit this file manually!
# If you need to change the version, do so in the project.toml, e.g. by using `poetry version X.Y.Z`.
MAJOR = 0
MINOR = 4
PATCH = 0

VERSION = f"{MAJOR}.{MINOR}.{PATCH}"
1 change: 1 addition & 0 deletions exasol_error_reporting_python/error_message_builder.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
from typing import Any

from exasol_error_reporting_python.parameters_mapper import ParametersMapper
from exasol_error_reporting_python.placeholder_handler import PlaceholderHandler

Expand Down
3 changes: 1 addition & 2 deletions exasol_error_reporting_python/exa_error.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from exasol_error_reporting_python.error_message_builder import \
ErrorMessageBuilder
from exasol_error_reporting_python.error_message_builder import ErrorMessageBuilder


class ExaError:
Expand Down
20 changes: 10 additions & 10 deletions exasol_error_reporting_python/parameters_mapper.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from typing import Any
from exasol_error_reporting_python.placeholder_handler\
import PlaceholderHandler

from exasol_error_reporting_python.placeholder_handler import PlaceholderHandler


class ParametersMapper:
"""
This class is responsible for mapping positional arguments to corresponding
placeholders in messages.
"""

def __init__(self, text: str, arguments: str):
self._text = text
self._parameters = arguments
Expand Down Expand Up @@ -38,8 +39,7 @@ def _map_parameters(self):

for placeholder in PlaceholderHandler.get_placeholders(self._text):
if self._is_parameter_present():
self._parameter_dict[placeholder.name] = \
self._get_current_parameter()
self._parameter_dict[placeholder.name] = self._get_current_parameter()
self._next_parameters()

def _get_current_parameter(self) -> Any:
Expand All @@ -48,23 +48,23 @@ def _get_current_parameter(self) -> Any:
:return: a parameter in the parameters list or None
"""
return self._parameters[self._parameter_idx] \
if self._is_parameter_present() else None
return (
self._parameters[self._parameter_idx]
if self._is_parameter_present()
else None
)

def _is_parameter_present(self) -> bool:
"""
Check whether the current parameter present.
:return: True if present, False otherwise
"""
return self._parameters and \
self._parameter_idx < len(self._parameters)
return self._parameters and self._parameter_idx < len(self._parameters)

def _next_parameters(self):
"""
Increase index for parameter list.
"""

self._parameter_idx += 1


5 changes: 1 addition & 4 deletions exasol_error_reporting_python/placeholder.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

class Placeholder:
"""
A data class holds information about Placeholder.
Expand Down Expand Up @@ -35,6 +34,4 @@ def _parse_unquoted_placeholder_name(self) -> str:
:return: the text in which the unquotation suffix is removed
"""
return self.text[:-len(self._unquoted_suffix)]


return self.text[: -len(self._unquoted_suffix)]
Loading

0 comments on commit 63910ee

Please sign in to comment.