Skip to content

Commit

Permalink
Add function match_multiple to the clas NameFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
Josef-Friedrich committed Mar 2, 2024
1 parent b11444c commit 95e33a6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
34 changes: 29 additions & 5 deletions check_systemd.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ class Timer:
next: Optional[float]
passed: Optional[float]

class UnitNameFilter:
class NameFilter:
"""This class stores all system unit names (e. g. ``nginx.service`` or
``fstrim.timer``) and provides a interface to filter the names by regular
expressions."""
Expand All @@ -357,6 +357,29 @@ class UnitNameFilter:
def __init__(self, unit_names: Sequence[str] = ()) -> None:
self.__unit_names = set(unit_names)

@staticmethod
def __match(unit_name: str, regexes: str | Sequence[str]) -> bool:
"""
Match multiple regular expressions against a unit name.
:param unit_name: The unit name to be matched.
:param regexes: A single regular expression (``include='.*service'``) or a
list of regular expressions (``include=('.*service', '.*mount')``).
:return: True if one regular expression matches"""
if isinstance(regexes, str):
regexes = [regexes]
for regex in regexes:
try:
if re.match(regex, unit_name):
return True
except Exception:
raise CheckSystemdRegexpError(
"Invalid regular expression: '{}'".format(regex)
)
return False

def add(self, unit_name: str) -> None:
"""Add one unit name.
Expand Down Expand Up @@ -387,12 +410,13 @@ def filter(
regular expression (``exclude='.*service'``) or a list of regular
expressions (``exclude=('.*service', '.*mount')``).
"""
match = Source.NameFilter.__match
for name in self.__unit_names:
output: Optional[str] = name
if include and not match_multiple(name, include):
if include and not match(name, include):
output = None

if output and exclude and match_multiple(name, exclude):
if output and exclude and match(name, exclude):
output = None

if output:
Expand All @@ -403,11 +427,11 @@ class UnitCache:

__units: dict[str, Source.Unit]

__name_filter: Source.UnitNameFilter
__name_filter: Source.NameFilter

def __init__(self) -> None:
self.__units = {}
self.__name_filter = Source.UnitNameFilter()
self.__name_filter = Source.NameFilter()

def add(self, unit: Source.Unit) -> None:
self.__units[unit.name] = unit
Expand Down
2 changes: 1 addition & 1 deletion tests/test_data_acquisition_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

Unit = Source.Unit
UnitCache = Source.UnitCache
UnitNameFilter = Source.UnitNameFilter
UnitNameFilter = Source.NameFilter

unit_modem_manager = Unit(
name="ModemManager.service",
Expand Down

0 comments on commit 95e33a6

Please sign in to comment.