Skip to content

Commit

Permalink
Add: Add a base class for Enums in python-gvm
Browse files Browse the repository at this point in the history
This will simplify all our enums and reduce duplicate code.
  • Loading branch information
bjoernricks committed Feb 27, 2024
1 parent 6db4b1e commit 5e74178
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
38 changes: 38 additions & 0 deletions gvm/_enum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# SPDX-FileCopyrightText: 2024 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later
#

from enum import Enum as PythonEnum
from typing import Optional

from typing_extensions import Self

from gvm.errors import InvalidArgument


class Enum(PythonEnum):
"""
Base class for Enums in python-gvm
"""

@classmethod
def from_string(
cls,
value: Optional[str],
) -> Optional[Self]:
"""
Convert a string value into an Enum instance
If value is None or empty None is returned
"""
if not value:
return None

try:
return cls[value.replace(" ", "_").upper()]
except KeyError:
raise InvalidArgument(
f"Invalid argument {value} for {cls.__name__}.from_string. "
f"Allowed values are {','.join(e.name for e in cls)}."
) from None
4 changes: 2 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ python = "^3.9"
paramiko = ">=2.7.1"
lxml = ">=4.5.0"
defusedxml = ">=0.6"

typing-extensions = ">=4.9.0"

[tool.poetry.group.dev.dependencies]
coverage = ">=7.2"
Expand Down

0 comments on commit 5e74178

Please sign in to comment.