Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resource history #232

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 3 additions & 26 deletions mreg_cli/api/abstracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from pydantic.fields import FieldInfo

from mreg_cli.api.endpoints import Endpoint
from mreg_cli.api.history import HistoryItem, HistoryResource
from mreg_cli.exceptions import (
CreateError,
EntityAlreadyExists,
Expand Down Expand Up @@ -432,7 +431,7 @@ def refetch(self) -> Self:

return obj

def patch(self, fields: dict[str, Any], use_json: bool = False, validate: bool = True) -> Self:
def patch(self, fields: dict[str, Any], validate: bool = True) -> Self:
"""Patch the object with the given values.

Notes
Expand All @@ -445,11 +444,7 @@ def patch(self, fields: dict[str, Any], use_json: bool = False, validate: bool =
:param validate: Whether to validate the patched object.
:returns: The object refetched from the server.
"""
if use_json:
patch(self.endpoint().with_id(self.id_for_endpoint()), fields, use_json=True)
else:
patch(self.endpoint().with_id(self.id_for_endpoint()), use_json=False, **fields)

patch(self.endpoint().with_id(self.id_for_endpoint()), **fields)
new_object = self.refetch()

if validate:
Expand All @@ -473,7 +468,7 @@ def delete(self) -> bool:

@classmethod
def create(
cls, params: Mapping[str, str | None], fetch_after_create: bool = True
cls, params: Mapping[str, str | list[str] | None], fetch_after_create: bool = True
) -> Self | None:
"""Create the object.

Expand Down Expand Up @@ -512,21 +507,3 @@ def create(
raise CreateError(f"Failed to create {cls} with {params} @ {cls.endpoint()}.")

return None

def history(self, resource: HistoryResource) -> list[HistoryItem]:
"""Get the history of the object.

:param resource: The resource type to get the history for.

:returns: The history of the object.
"""
name = self.id_for_endpoint()
return HistoryItem.get(str(name), resource)

def output_history(self, resource: HistoryResource) -> None:
"""Output the history of the object.

:param resource: The resource type to get the history for.
"""
items = self.history(resource)
HistoryItem.output_multiple(str(self.id_for_endpoint()), items)
21 changes: 17 additions & 4 deletions mreg_cli/api/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from enum import Enum
from typing import Any, Callable
from urllib.parse import quote
from urllib.parse import quote, urljoin


class hybridmethod:
Expand Down Expand Up @@ -78,6 +78,18 @@ class Endpoint(str, Enum):

ForwardZones = f"{Zones}forward/"
ReverseZones = f"{Zones}reverse/"

# NOTE: Delegations endpoints MUST have a trailing slash
ForwardZonesDelegations = f"{ForwardZones}{{}}/delegations/"
ReverseZonesDelegations = f"{ReverseZones}{{}}/delegations/"

ForwardZonesDelegationsZone = f"{ForwardZones}{{}}/delegations/{{}}"
ReverseZonesDelegationsZone = f"{ReverseZones}{{}}/delegations/{{}}"

# NOTE: Nameservers endpoints must NOT have a trailing slash
ForwardZonesNameservers = f"{ForwardZones}{{}}/nameservers"
ReverseZonesNameservers = f"{ReverseZones}{{}}/nameservers"

ForwardZoneForHost = f"{ForwardZones}hostname/"

def __str__(self):
Expand All @@ -99,6 +111,8 @@ def external_id_field(self) -> str:
Endpoint.Cnames,
Endpoint.ForwardZones,
Endpoint.ReverseZones,
Endpoint.ForwardZonesDelegations,
Endpoint.ReverseZonesDelegations,
Endpoint.HostPolicyRoles,
Endpoint.HostPolicyAtoms,
):
Expand All @@ -109,11 +123,11 @@ def external_id_field(self) -> str:
return "host"
return "id"

# Add methods via composition
def with_id(self, identity: str | int) -> str:
"""Return the endpoint with an ID."""
id_field = quote(str(identity))

return f"{self.value}{id_field}"
return urljoin(self.value, id_field)

def with_params(self, *params: str | int) -> str:
"""Construct and return an endpoint URL by inserting parameters.
Expand All @@ -128,7 +142,6 @@ def with_params(self, *params: str | int) -> str:
raise ValueError(
f"{self.name} endpoint expects {placeholders_count} parameters, got {len(params)}."
)

encoded_params = (quote(str(param)) for param in params)
return self.value.format(*encoded_params)

Expand Down
36 changes: 20 additions & 16 deletions mreg_cli/api/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,28 @@
class HistoryResource(str, Enum):
"""History resources."""

Host = "host"
Group = "group"
HostPolicy_Role = "hostpolicy_role"
HostPolicy_Atom = "hostpolicy_atom"
Host = "hosts"
Group = "groups"
HostPolicy_Role = "roles"
HostPolicy_Atom = "atoms"

@classmethod
def _missing_(cls, value: Any) -> HistoryResource:
v = str(value).lower()
for resource in cls:
if resource.value == v:
return resource
elif resource.name.lower() == v:
return resource
raise ValueError(f"Unknown resource {value}")

def relation(self) -> str:
"""Provide the relation of the resource."""
if self == HistoryResource.Host:
return "hosts"
if self == HistoryResource.Group:
return "groups"
if self == HistoryResource.HostPolicy_Role:
return "roles"
if self == HistoryResource.HostPolicy_Atom:
return "atoms"
"""Get the resource relation."""
return self.value

raise ValueError(f"Unknown resource {self}")
def resource(self) -> str:
"""Get the resource name."""
return self.name.lower()


class HistoryItem(BaseModel):
Expand Down Expand Up @@ -112,7 +117,7 @@ def output_multiple(cls, basename: str, items: list[HistoryItem]) -> None:
@classmethod
def get(cls, name: str, resource: HistoryResource) -> list[HistoryItem]:
"""Get history items for a resource."""
resource_value = resource.value
resource_value = resource.resource()

params: dict[str, str | int] = {"resource": resource_value, "name": name}

Expand All @@ -131,7 +136,6 @@ def get(cls, name: str, resource: HistoryResource) -> list[HistoryItem]:
ret = get_list(Endpoint.History, params=params)

data_relation = resource.relation()

params = {
"data__relation": data_relation,
"data__id__in": model_ids,
Expand Down
Loading
Loading