Skip to content

Commit

Permalink
Define HBA as a dataclass
Browse files Browse the repository at this point in the history
  • Loading branch information
pgiraud committed Nov 29, 2024
1 parent 5c45afe commit ad5df3b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
28 changes: 13 additions & 15 deletions pgtoolkit/hba.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
import sys
import warnings
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import IO, Any

Expand Down Expand Up @@ -209,20 +210,20 @@ def __str__(self) -> str:
widths = [8, 16, 16, 16, 8]

fmt = ""
for i, field in enumerate(self.COMMON_FIELDS):
for i, field_ in enumerate(self.COMMON_FIELDS):
try:
width = widths[i]
except IndexError:
width = 0

if field not in self.fields:
if field_ not in self.fields:
fmt += " " * width
continue

if width:
fmt += "%%(%s)-%ds " % (field, width - 1)
fmt += "%%(%s)-%ds " % (field_, width - 1)
else:
fmt += f"%({field})s "
fmt += f"%({field_})s "
# Serialize database and user list using property.
values = dict(self.__dict__, databases=self.database, users=self.user)
line = fmt.rstrip() % values
Expand Down Expand Up @@ -298,6 +299,7 @@ def matches(self, **attrs: str) -> bool:
return True


@dataclass
class HBA:
"""Represents pg_hba.conf records
Expand All @@ -317,18 +319,14 @@ class HBA:
.. automethod:: merge
"""

lines: list[HBAComment | HBARecord]
path: str | Path | None
entries: Iterable[HBAComment | HBARecord] | None = None
lines: list[HBAComment | HBARecord] = field(default_factory=list, init=False)
path: str | Path | None = field(init=False)

def __init__(self, entries: Iterable[HBAComment | HBARecord] | None = None) -> None:
"""HBA constructor
:param entries: A list of HBAComment or HBARecord. Optional.
"""
if entries and not isinstance(entries, list):
raise ValueError("%s should be a list" % entries)
self.lines = list(entries) if entries is not None else []
self.path = None
def __post_init__(self) -> None:
if self.entries and not isinstance(self.entries, list):
raise ValueError(f"{self.entries} should be a list")
self.lines = list(self.entries) if self.entries is not None else []

def __iter__(self) -> Iterator[HBARecord]:
"""Iterate on records, ignoring comments and blank lines."""
Expand Down
2 changes: 1 addition & 1 deletion tests/test_hba.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def test_hba_create():
assert ["all"] == r.databases

# Should be a list
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="should be a list"):
HBA("blah")


Expand Down

0 comments on commit ad5df3b

Please sign in to comment.