Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 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
2 changes: 2 additions & 0 deletions infrahub_sdk/ctl/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ async def add(
password=password,
)
await credential.save(allow_upsert=True)
if not credential.id:
raise ValueError("credential.id must be set before building the request")
input_data["data"]["credential"] = {"id": credential.id}

query = Mutation(
Expand Down
16 changes: 8 additions & 8 deletions infrahub_sdk/node/attribute.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ def __init__(self, name: str, schema: AttributeSchemaAPI, data: Any | dict):

self._read_only = ["updated_at", "is_inherited"]

self.id: str | None = data.get("id", None)
self.id: str | None = data.get("id")

self._value: Any | None = data.get("value", None)
self._value: Any | None = data.get("value")
self.value_has_been_mutated = False
self.is_default: bool | None = data.get("is_default", None)
self.is_from_profile: bool | None = data.get("is_from_profile", None)
self.is_default: bool | None = data.get("is_default")
self.is_from_profile: bool | None = data.get("is_from_profile")

if self._value:
value_mapper: dict[str, Callable] = {
Expand All @@ -49,11 +49,11 @@ def __init__(self, name: str, schema: AttributeSchemaAPI, data: Any | dict):
mapper = value_mapper.get(schema.kind, lambda value: value)
self._value = mapper(data.get("value"))

self.is_inherited: bool | None = data.get("is_inherited", None)
self.updated_at: str | None = data.get("updated_at", None)
self.is_inherited: bool | None = data.get("is_inherited")
self.updated_at: str | None = data.get("updated_at")

self.is_visible: bool | None = data.get("is_visible", None)
self.is_protected: bool | None = data.get("is_protected", None)
self.is_visible: bool | None = data.get("is_visible")
self.is_protected: bool | None = data.get("is_protected")

self.source: NodeProperty | None = None
self.owner: NodeProperty | None = None
Expand Down
38 changes: 29 additions & 9 deletions infrahub_sdk/node/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
from typing import TYPE_CHECKING, Any

from ..constants import InfrahubClientMode
from ..exceptions import FeatureNotSupportedError, NodeNotFoundError, ResourceNotDefinedError, SchemaNotFoundError
from ..exceptions import (
FeatureNotSupportedError,
NodeNotFoundError,
ResourceNotDefinedError,
SchemaNotFoundError,
UninitializedError,
)
from ..graphql import Mutation, Query
from ..schema import GenericSchemaAPI, RelationshipCardinality, RelationshipKind
from ..utils import compare_lists, generate_short_id, get_flat_value
Expand Down Expand Up @@ -574,8 +580,9 @@ async def artifact_generate(self, name: str) -> None:
self._validate_artifact_support(ARTIFACT_GENERATE_FEATURE_NOT_SUPPORTED_MESSAGE)

artifact = await self._client.get(kind="CoreArtifact", name__value=name, object__ids=[self.id])
await artifact._get_relationship_one(name="definition").fetch()
await artifact._get_relationship_one(name="definition").peer.generate([artifact.id])
if artifact.id:
await artifact._get_relationship_one(name="definition").fetch()
await artifact._get_relationship_one(name="definition").peer.generate([artifact.id])

async def artifact_fetch(self, name: str) -> str | dict[str, Any]:
self._validate_artifact_support(ARTIFACT_GENERATE_FEATURE_NOT_SUPPORTED_MESSAGE)
Expand Down Expand Up @@ -619,16 +626,21 @@ async def save(

if not isinstance(self._schema, GenericSchemaAPI):
if "CoreGroup" in self._schema.inherit_from:
if self.id is None:
raise UninitializedError("Cannot add related groups before the node has an ID")
await self._client.group_context.add_related_groups(
ids=[self.id], update_group_context=update_group_context
)
else:
if self.id is None:
raise UninitializedError("Cannot add related nodes before the node has an ID")
await self._client.group_context.add_related_nodes(
ids=[self.id], update_group_context=update_group_context
)
else:
if self.id is None:
raise UninitializedError("Cannot add related nodes before the node has an ID")
await self._client.group_context.add_related_nodes(ids=[self.id], update_group_context=update_group_context)

self._client.store.set(node=self)

async def generate_query_data(
Expand Down Expand Up @@ -813,7 +825,7 @@ async def _process_mutation_result(
self, mutation_name: str, response: dict[str, Any], timeout: int | None = None
) -> None:
object_response: dict[str, Any] = response[mutation_name]["object"]
self.id = object_response["id"]
self.id = str(object_response["id"])
self._existing = True

for attr_name in self._attributes:
Expand Down Expand Up @@ -1161,8 +1173,9 @@ def generate(self, nodes: list[str] | None = None) -> None:
def artifact_generate(self, name: str) -> None:
self._validate_artifact_support(ARTIFACT_GENERATE_FEATURE_NOT_SUPPORTED_MESSAGE)
artifact = self._client.get(kind="CoreArtifact", name__value=name, object__ids=[self.id])
artifact._get_relationship_one(name="definition").fetch()
artifact._get_relationship_one(name="definition").peer.generate([artifact.id])
if artifact.id:
artifact._get_relationship_one(name="definition").fetch()
artifact._get_relationship_one(name="definition").peer.generate([artifact.id])

def artifact_fetch(self, name: str) -> str | dict[str, Any]:
self._validate_artifact_support(ARTIFACT_FETCH_FEATURE_NOT_SUPPORTED_MESSAGE)
Expand Down Expand Up @@ -1205,10 +1218,17 @@ def save(

if not isinstance(self._schema, GenericSchemaAPI):
if "CoreGroup" in self._schema.inherit_from:
self._client.group_context.add_related_groups(ids=[self.id], update_group_context=update_group_context)
if self.id is None:
raise UninitializedError("Cannot add related nodes before the node has an ID")
self._client.group_context.add_related_nodes(ids=[self.id], update_group_context=update_group_context)

else:
if self.id is None:
raise UninitializedError("Cannot add related nodes before the node has an ID")
self._client.group_context.add_related_nodes(ids=[self.id], update_group_context=update_group_context)
else:
if self.id is None:
raise UninitializedError("Cannot add related nodes before the node has an ID")
self._client.group_context.add_related_nodes(ids=[self.id], update_group_context=update_group_context)

self._client.store.set(node=self)
Expand Down Expand Up @@ -1394,7 +1414,7 @@ def _process_mutation_result(
self, mutation_name: str, response: dict[str, Any], timeout: int | None = None
) -> None:
object_response: dict[str, Any] = response[mutation_name]["object"]
self.id = object_response["id"]
self.id = str(object_response["id"])
self._existing = True

for attr_name in self._attributes:
Expand Down
4 changes: 2 additions & 2 deletions infrahub_sdk/node/related_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, branch: str, schema: RelationshipSchemaAPI, data: Any | dict,
self._properties_object = PROPERTIES_OBJECT
self._properties = self._properties_flag + self._properties_object

self._peer = None
self._peer: CoreNodeBase | InfrahubNode | InfrahubNodeSync | None = None
self._id: str | None = None
self._hfid: list[str] | None = None
self._display_label: str | None = None
Expand Down Expand Up @@ -64,7 +64,7 @@ def __init__(self, branch: str, schema: RelationshipSchemaAPI, data: Any | dict,
self._display_label = node_data.get("display_label", None)
self._typename = node_data.get("__typename", None)

self.updated_at: str | None = data.get("updated_at", data.get("_relation__updated_at", None))
self.updated_at: str | None = data.get("updated_at", data.get("_relation__updated_at"))

# FIXME, we won't need that once we are only supporting paginated results
if self._typename and self._typename.startswith("Related"):
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/pytest_plugin/items/jinja2_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def repr_failure(self, excinfo: ExceptionInfo, style: str | None = None) -> str:
class InfrahubJinja2TransformSmokeItem(InfrahubJinja2Item):
def runtest(self) -> None:
file_path: Path = self.session.infrahub_config_path.parent / self.resource_config.template_path # type: ignore[attr-defined]
self.get_jinja2_environment().parse(file_path.read_text(), filename=file_path.name)
self.get_jinja2_environment().parse(file_path.read_text(encoding="utf-8"), filename=file_path.name)


class InfrahubJinja2TransformUnitRenderItem(InfrahubJinja2Item):
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/pytest_plugin/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def load_repository_config(repo_config_file: Path) -> InfrahubRepositoryConfig:
raise FileNotFoundError(repo_config_file)

try:
yaml_data = repo_config_file.read_text()
yaml_data = repo_config_file.read_text(encoding="utf-8")
data = yaml.safe_load(yaml_data)
except yaml.YAMLError as exc:
raise FileNotValidError(name=str(repo_config_file)) from exc
Expand Down
9 changes: 5 additions & 4 deletions infrahub_sdk/transfer/importer/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ async def import_data(self, import_directory: Path, branch: str) -> None:
for graphql_data, kind in zip(table.column("graphql_json"), table.column("kind")):
node = await InfrahubNode.from_graphql(self.client, branch, ujson.loads(str(graphql_data)))
import_nodes_by_kind[str(kind)].append(node)
self.all_nodes[node.id] = node
if node.id:
self.all_nodes[node.id] = node

schema_batch = await self.client.create_batch()
for kind in import_nodes_by_kind:
Expand Down Expand Up @@ -112,11 +113,11 @@ async def remove_and_store_optional_relationships(self) -> None:
for relationship_name in self.optional_relationships_schemas_by_node_kind[node_kind].keys():
relationship_value = getattr(node, relationship_name)
if isinstance(relationship_value, RelationshipManager):
if relationship_value.peer_ids:
if relationship_value.peer_ids and node.id:
self.optional_relationships_by_node[node.id][relationship_name] = relationship_value
setattr(node, relationship_name, None)
elif isinstance(relationship_value, RelatedNode):
if relationship_value.id:
if relationship_value.id and node.id:
self.optional_relationships_by_node[node.id][relationship_name] = relationship_value
setattr(node, relationship_name, None)

Expand Down Expand Up @@ -144,7 +145,7 @@ async def update_optional_relationships(self) -> None:
await self.execute_batches([update_batch], "Adding optional relationships to nodes")

async def update_many_to_many_relationships(self, file: Path) -> None:
relationships = ujson.loads(file.read_text())
relationships = ujson.loads(file.read_text(encoding="utf-8"))
update_batch = await self.client.create_batch(return_exceptions=True)

for relationship in relationships:
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def write_to_file(path: Path, value: Any) -> bool:
raise FileExistsError(f"{path} is a directory")

to_write = str(value)
written = path.write_text(to_write)
written = path.write_text(data=to_write, encoding="utf-8")

return written is not None

Expand Down
Loading