feat(api): add list_inventory_tags

This commit is contained in:
Brian McGee
2025-08-11 14:44:16 +01:00
parent 1abdd45821
commit 2608bee30a
2 changed files with 101 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
from typing import TypedDict
from clan_lib.api import API
from clan_lib.flake import Flake
from clan_lib.persist.inventory_store import InventoryStore
readonly_tags = {"all", "nixos", "darwin"}
class MachineTag(TypedDict):
name: str
readonly: bool
@API.register
def list_inventory_tags(flake: Flake) -> list[MachineTag]:
inventory_store = InventoryStore(flake=flake)
inventory = inventory_store.read()
machines = inventory.get("machines", {})
tags: dict[str, MachineTag] = {}
for _, machine in machines.items():
machine_tags = machine.get("tags", [])
for tag in machine_tags:
tags[tag] = MachineTag(name=tag, readonly=tag in readonly_tags)
return sorted(tags.values(), key=lambda x: x["name"])

View File

@@ -0,0 +1,72 @@
from collections.abc import Callable
import pytest
from clan_lib.flake import Flake
from .actions import MachineTag, list_inventory_tags
@pytest.mark.with_core
def test_list_inventory_tags(clan_flake: Callable[..., Flake]) -> None:
flake = clan_flake(
{
"inventory": {
"machines": {
"jon": {
# machineClass defaults to nixos
"tags": ["foo", "bar"],
},
"sara": {
"machineClass": "darwin",
"tags": ["foo", "baz", "fizz"],
},
"bob": {
"machineClass": "nixos",
"tags": ["foo", "bar"],
},
},
}
},
)
tags = list_inventory_tags(flake)
assert tags == [
MachineTag(name="all", readonly=True),
MachineTag(name="bar", readonly=False),
MachineTag(name="baz", readonly=False),
MachineTag(name="darwin", readonly=True),
MachineTag(name="fizz", readonly=False),
MachineTag(name="foo", readonly=False),
MachineTag(name="nixos", readonly=True),
]
@pytest.mark.with_core
def test_list_inventory_tags_defaults(clan_flake: Callable[..., Flake]) -> None:
flake = clan_flake(
{
"inventory": {
"machines": {
"jon": {
# machineClass defaults to nixos
},
"sara": {
"machineClass": "darwin",
},
"bob": {
"machineClass": "nixos",
},
},
}
},
)
tags = list_inventory_tags(flake)
assert tags == [
MachineTag(name="all", readonly=True),
MachineTag(name="darwin", readonly=True),
MachineTag(name="nixos", readonly=True),
]