Skip to content

Commit e4d8f40

Browse files
author
Phillip Simonds
committed
Updates per PR review.
1 parent 07a5a24 commit e4d8f40

File tree

2 files changed

+17
-38
lines changed

2 files changed

+17
-38
lines changed

infrahub_sdk/ctl/cli_commands.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,6 @@ def _run_transform(
208208
query_name: Name of the query to load (e.g. tags_query)
209209
variables: Dictionary of variables used for graphql query
210210
transformer_func: The function responsible for transforming data received from graphql
211-
transform: A function used to transform the return from the graphql query into a different form
212211
branch: Name of the *infrahub* branch that should be queried for data
213212
debug: Prints debug info to the command line
214213
repository_config: Repository config object. This is used to load the graphql query from the repository.
@@ -220,9 +219,10 @@ def _run_transform(
220219
query=query_name, variables_dict=variables, branch=branch, debug=debug, repository_config=repository_config
221220
)
222221

223-
if debug:
224-
message = ("-" * 40, f"Response for GraphQL Query {query_name}", response, "-" * 40)
225-
console.print("\n".join(message))
222+
# TODO: response is a dict and can't be printed to the console in this way.
223+
# if debug:
224+
# message = ("-" * 40, f"Response for GraphQL Query {query_name}", response, "-" * 40)
225+
# console.print("\n".join(message))
226226
except QueryNotFoundError as exc:
227227
console.print(f"[red]Unable to find query : {exc}")
228228
raise typer.Exit(1) from exc
@@ -342,19 +342,20 @@ def transform(
342342
transform = get_transform_class_instance(
343343
transform_config=transform_config,
344344
branch=branch,
345-
repository_config=repository_config,
346345
client=client,
347346
)
348347
except InfrahubTransformNotFoundError as exc:
349348
console.print(f"Unable to load {transform_name} from python_transforms")
350349
raise typer.Exit(1) from exc
351350

352-
# Load query config
353-
query_config_obj = InfrahubRepositoryGraphQLConfig(name=transform.query, file_path=Path(transform.query + ".gql"))
354-
repository_config.queries.append(query_config_obj)
351+
# Get data
352+
query_str = repository_config.get_query(name=transform.query).load_query()
353+
data = asyncio.run(
354+
transform.client.execute_graphql(query=query_str, variables=variables_dict, branch_name=transform.branch_name)
355+
)
355356

356357
# Run Transform
357-
result = asyncio.run(transform.run(variables=variables_dict))
358+
result = asyncio.run(transform.run(data=data))
358359

359360
json_string = ujson.dumps(result, indent=2, sort_keys=True)
360361
if out:

infrahub_sdk/transforms.py

Lines changed: 7 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
from abc import abstractmethod
88
from typing import TYPE_CHECKING, Any, Optional
99

10-
import httpx
1110
from git import Repo
1211

1312
from infrahub_sdk import InfrahubClient
@@ -17,7 +16,7 @@
1716
if TYPE_CHECKING:
1817
from pathlib import Path
1918

20-
from .schema import InfrahubPythonTransformConfig, InfrahubRepositoryConfig
19+
from .schema import InfrahubPythonTransformConfig
2120

2221
INFRAHUB_TRANSFORM_VARIABLE_TO_IMPORT = "INFRAHUB_TRANSFORMS"
2322

@@ -33,14 +32,12 @@ def __init__(
3332
root_directory: str = "",
3433
server_url: str = "",
3534
client: Optional[InfrahubClient] = None,
36-
repository_config: Optional[InfrahubRepositoryConfig] = None,
3735
):
3836
self.git: Repo
3937

4038
self.branch = branch
4139
self.server_url = server_url or os.environ.get("INFRAHUB_URL", "http://127.0.0.1:8000")
4240
self.root_directory = root_directory or os.getcwd()
43-
self.repository_config = repository_config
4441

4542
self._client = client
4643

@@ -61,7 +58,7 @@ def client(self) -> InfrahubClient:
6158
async def init(cls, client: Optional[InfrahubClient] = None, *args: Any, **kwargs: Any) -> InfrahubTransform:
6259
"""Async init method, If an existing InfrahubClient client hasn't been provided, one will be created automatically."""
6360
warnings.warn(
64-
"InfrahubClient.init has been deprecated and will be removed in Infrahub SDK 0.14.0 or the next major version",
61+
f"{cls.__class__.__name__}.init has been deprecated and will be removed in Infrahub SDK 0.15.0 or the next major version",
6562
DeprecationWarning,
6663
stacklevel=1,
6764
)
@@ -90,39 +87,24 @@ def branch_name(self) -> str:
9087
def transform(self, data: dict) -> Any:
9188
pass
9289

93-
async def collect_data(self, variables: Optional[dict] = None) -> dict:
90+
async def collect_data(self) -> dict:
9491
"""Query the result of the GraphQL Query defined in self.query and return the result"""
9592

96-
if not variables:
97-
variables = {}
93+
return await self.client.query_gql_query(name=self.query, branch_name=self.branch_name)
9894

99-
# Try getting data from stored graphql query endpoint
100-
try:
101-
return await self.client.query_gql_query(name=self.query, branch_name=self.branch_name, variables=variables)
102-
# If we run into an error, the stored graphql query may not exist. Try to query the GraphQL API directly instead.
103-
except httpx.HTTPStatusError:
104-
if not self.repository_config:
105-
raise
106-
query_str = self.repository_config.get_query(name=self.query).load_query()
107-
return await self.client.execute_graphql(query=query_str, variables=variables, branch_name=self.branch_name)
108-
109-
async def run(self, data: Optional[dict] = None, variables: Optional[dict] = None) -> Any:
95+
async def run(self, data: Optional[dict] = None) -> Any:
11096
"""Execute the transformation after collecting the data from the GraphQL query.
11197
11298
The result of the check is determined based on the presence or not of ERROR log messages.
11399
114100
Args:
115101
data: The data on which to run the transform. Data will be queried from the API if not provided
116-
variables: Variables to use in the graphQL query to filter returned data
117102
118103
Returns: Transformed data
119104
"""
120105

121-
if not variables:
122-
variables = {}
123-
124106
if not data:
125-
data = await self.collect_data(variables=variables)
107+
data = await self.collect_data()
126108

127109
unpacked = data.get("data") or data
128110

@@ -136,7 +118,6 @@ def get_transform_class_instance(
136118
transform_config: InfrahubPythonTransformConfig,
137119
search_path: Optional[Path] = None,
138120
branch: str = "",
139-
repository_config: Optional[InfrahubRepositoryConfig] = None,
140121
client: Optional[InfrahubClient] = None,
141122
) -> InfrahubTransform:
142123
"""Gets an instance of the InfrahubTransform class.
@@ -146,9 +127,6 @@ def get_transform_class_instance(
146127
search_path: The path in which to search for a python file containing the transform. The current directory is
147128
assumed if not speicifed.
148129
branch: Infrahub branch which will be targeted in graphql query used to acquire data for transformation.
149-
repository_config: Repository config object. This is dpendency injected into the InfrahubTransform instance
150-
providing it with the ability to interact with other data in the repository where the transform is defined
151-
(e.g. a graphql query file).
152130
client: InfrahubClient used to interact with infrahub API.
153131
"""
154132
if transform_config.file_path.is_absolute() or search_path is None:
@@ -165,7 +143,7 @@ def get_transform_class_instance(
165143
transform_class = getattr(module, transform_config.class_name)
166144

167145
# Create an instance of the class
168-
transform_instance = transform_class(branch=branch, client=client, repository_config=repository_config)
146+
transform_instance = transform_class(branch=branch, client=client)
169147

170148
except (FileNotFoundError, AttributeError) as exc:
171149
raise InfrahubTransformNotFoundError(name=transform_config.name) from exc

0 commit comments

Comments
 (0)