Skip to content
Merged
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
1 change: 1 addition & 0 deletions changelog/8.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make `infrahubctl transform` command set up the InfrahubTransform class with an InfrahubClient instance
12 changes: 6 additions & 6 deletions infrahub_sdk/ctl/branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@

logging.getLogger("infrahub_sdk").setLevel(logging.CRITICAL)

client = await initialize_client()
client = initialize_client()
branches = await client.branch.all()

table = Table(title="List of all branches")
Expand Down Expand Up @@ -91,7 +91,7 @@

logging.getLogger("infrahub_sdk").setLevel(logging.CRITICAL)

client = await initialize_client()
client = initialize_client()
branch = await client.branch.create(branch_name=branch_name, description=description, sync_with_git=sync_with_git)
console.print(f"Branch {branch_name!r} created successfully ({branch.id}).")

Expand All @@ -103,7 +103,7 @@

logging.getLogger("infrahub_sdk").setLevel(logging.CRITICAL)

client = await initialize_client()
client = initialize_client()

Check warning on line 106 in infrahub_sdk/ctl/branch.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/branch.py#L106

Added line #L106 was not covered by tests
await client.branch.delete(branch_name=branch_name)
console.print(f"Branch '{branch_name}' deleted successfully.")

Expand All @@ -115,7 +115,7 @@

logging.getLogger("infrahub_sdk").setLevel(logging.CRITICAL)

client = await initialize_client()
client = initialize_client()

Check warning on line 118 in infrahub_sdk/ctl/branch.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/branch.py#L118

Added line #L118 was not covered by tests
await client.branch.rebase(branch_name=branch_name)
console.print(f"Branch '{branch_name}' rebased successfully.")

Expand All @@ -127,7 +127,7 @@

logging.getLogger("infrahub_sdk").setLevel(logging.CRITICAL)

client = await initialize_client()
client = initialize_client()

Check warning on line 130 in infrahub_sdk/ctl/branch.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/branch.py#L130

Added line #L130 was not covered by tests
await client.branch.merge(branch_name=branch_name)
console.print(f"Branch '{branch_name}' merged successfully.")

Expand All @@ -137,6 +137,6 @@
async def validate(branch_name: str, _: str = CONFIG_PARAM) -> None:
"""Validate if a branch has some conflict and is passing all the tests (NOT IMPLEMENTED YET)."""

client = await initialize_client()
client = initialize_client()

Check warning on line 140 in infrahub_sdk/ctl/branch.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/branch.py#L140

Added line #L140 was not covered by tests
await client.branch.validate(branch_name=branch_name)
console.print(f"Branch '{branch_name}' is valid.")
2 changes: 1 addition & 1 deletion infrahub_sdk/ctl/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@
log = logging.getLogger("infrahub")

check_summary: list[bool] = []
client = await initialize_client()
client = initialize_client()

Check warning on line 199 in infrahub_sdk/ctl/check.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/check.py#L199

Added line #L199 was not covered by tests
for check_module in check_modules:
if check_module.definition.targets:
result = await run_targeted_check(
Expand Down
77 changes: 54 additions & 23 deletions infrahub_sdk/ctl/cli_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@
if not hasattr(module, method):
raise typer.Abort(f"Unable to Load the method {method} in the Python script at {script}")

client = await initialize_client(
client = initialize_client(

Check warning on line 166 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L166

Added line #L166 was not covered by tests
branch=branch, timeout=timeout, max_concurrent_execution=concurrent, identifier=module_name
)
func = getattr(module, method)
Expand Down Expand Up @@ -201,19 +201,35 @@


def _run_transform(
query: str,
query_name: str,
variables: dict[str, Any],
transformer: Callable,
transform_func: Callable,
branch: str,
debug: bool,
repository_config: InfrahubRepositoryConfig,
):
"""
Query GraphQL for the required data then run a transform on that data.

Args:
query_name: Name of the query to load (e.g. tags_query)
variables: Dictionary of variables used for graphql query
transform_func: The function responsible for transforming data received from graphql
branch: Name of the *infrahub* branch that should be queried for data
debug: Prints debug info to the command line
repository_config: Repository config object. This is used to load the graphql query from the repository.
"""
branch = get_branch(branch)

try:
response = execute_graphql_query(
query=query, variables_dict=variables, branch=branch, debug=debug, repository_config=repository_config
query=query_name, variables_dict=variables, branch=branch, debug=debug, repository_config=repository_config
)

# TODO: response is a dict and can't be printed to the console in this way.
# if debug:
# message = ("-" * 40, f"Response for GraphQL Query {query_name}", response, "-" * 40)
# console.print("\n".join(message))
except QueryNotFoundError as exc:
console.print(f"[red]Unable to find query : {exc}")
raise typer.Exit(1) from exc
Expand All @@ -228,10 +244,10 @@
console.print("[yellow] you can specify a different branch with --branch")
raise typer.Abort()

if asyncio.iscoroutinefunction(transformer.func):
output = asyncio.run(transformer(response))
if asyncio.iscoroutinefunction(transform_func):
output = asyncio.run(transform_func(response))

Check warning on line 248 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L248

Added line #L248 was not covered by tests
else:
output = transformer(response)
output = transform_func(response)

Check warning on line 250 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L250

Added line #L250 was not covered by tests
return output


Expand All @@ -257,23 +273,28 @@
list_jinja2_transforms(config=repository_config)
return

# Load transform config
try:
transform_config = repository_config.get_jinja2_transform(name=transform_name)
except KeyError as exc:
console.print(f'[red]Unable to find "{transform_name}" in {config.INFRAHUB_REPO_CONFIG_FILE}')
list_jinja2_transforms(config=repository_config)
raise typer.Exit(1) from exc

transformer = functools.partial(render_jinja2_template, transform_config.template_path, variables_dict)
# Construct transform function used to transform data returned from the API
transform_func = functools.partial(render_jinja2_template, transform_config.template_path, variables_dict)

Check warning on line 285 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L285

Added line #L285 was not covered by tests

# Query GQL and run the transform
result = _run_transform(
query=transform_config.query,
query_name=transform_config.query,
variables=variables_dict,
transformer=transformer,
transform_func=transform_func,
branch=branch,
debug=debug,
repository_config=repository_config,
)

# Output data
if out:
write_to_file(Path(out), result)
else:
Expand Down Expand Up @@ -302,31 +323,41 @@
list_transforms(config=repository_config)
return

matched = [transform for transform in repository_config.python_transforms if transform.name == transform_name] # pylint: disable=not-an-iterable

if not matched:
# Load transform config
try:

Check warning on line 327 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L327

Added line #L327 was not covered by tests
matched = [transform for transform in repository_config.python_transforms if transform.name == transform_name] # pylint: disable=not-an-iterable
if not matched:
raise ValueError(f"{transform_name} does not exist")
except ValueError as exc:

Check warning on line 331 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L330-L331

Added lines #L330 - L331 were not covered by tests
console.print(f"[red]Unable to find requested transform: {transform_name}")
list_transforms(config=repository_config)
return
raise typer.Exit(1) from exc

Check warning on line 334 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L334

Added line #L334 was not covered by tests

transform_config = matched[0]

# Get client
client = initialize_client()

Check warning on line 339 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L339

Added line #L339 was not covered by tests

# Get python transform class instance
try:
transform_instance = get_transform_class_instance(transform_config=transform_config)
transform = get_transform_class_instance(

Check warning on line 343 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L343

Added line #L343 was not covered by tests
transform_config=transform_config,
branch=branch,
client=client,
)
except InfrahubTransformNotFoundError as exc:
console.print(f"Unable to load {transform_name} from python_transforms")
raise typer.Exit(1) from exc

transformer = functools.partial(transform_instance.transform)
result = _run_transform(
query=transform_instance.query,
variables=variables_dict,
transformer=transformer,
branch=branch,
debug=debug,
repository_config=repository_config,
# Get data
query_str = repository_config.get_query(name=transform.query).load_query()
data = asyncio.run(

Check warning on line 354 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L353-L354

Added lines #L353 - L354 were not covered by tests
transform.client.execute_graphql(query=query_str, variables=variables_dict, branch_name=transform.branch_name)
)

# Run Transform
result = asyncio.run(transform.run(data=data))

Check warning on line 359 in infrahub_sdk/ctl/cli_commands.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/cli_commands.py#L359

Added line #L359 was not covered by tests

json_string = ujson.dumps(result, indent=2, sort_keys=True)
if out:
write_to_file(Path(out), json_string)
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/ctl/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from infrahub_sdk.ctl import config


async def initialize_client(
def initialize_client(
branch: Optional[str] = None,
identifier: Optional[str] = None,
timeout: Optional[int] = None,
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/ctl/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
if param_key:
identifier = param_key[0]

client = await initialize_client()
client = initialize_client()

Check warning on line 46 in infrahub_sdk/ctl/generator.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/generator.py#L46

Added line #L46 was not covered by tests
if variables_dict:
data = execute_graphql_query(
query=generator_config.query,
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/ctl/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
logging.getLogger("infrahub_sdk").setLevel(logging.INFO)

files = load_yamlfile_from_disk_and_exit(paths=menus, file_type=MenuFile, console=console)
client = await initialize_client()
client = initialize_client()

Check warning on line 41 in infrahub_sdk/ctl/menu.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/menu.py#L41

Added line #L41 was not covered by tests

for file in files:
file.validate_content()
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/ctl/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
logging.getLogger("infrahub_sdk").setLevel(logging.INFO)

files = load_yamlfile_from_disk_and_exit(paths=paths, file_type=ObjectFile, console=console)
client = await initialize_client()
client = initialize_client()

Check warning on line 41 in infrahub_sdk/ctl/object.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/object.py#L41

Added line #L41 was not covered by tests

for file in files:
file.validate_content()
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/ctl/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
},
}

client = await initialize_client()
client = initialize_client()

Check warning on line 91 in infrahub_sdk/ctl/repository.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/repository.py#L91

Added line #L91 was not covered by tests

if username:
credential = await client.create(kind="CorePasswordCredential", name=name, username=username, password=password)
Expand Down
4 changes: 2 additions & 2 deletions infrahub_sdk/ctl/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@

schemas_data = load_yamlfile_from_disk_and_exit(paths=schemas, file_type=SchemaFile, console=console)
schema_definition = "schema" if len(schemas_data) == 1 else "schemas"
client = await initialize_client()
client = initialize_client()
validate_schema_content_and_exit(client=client, schemas=schemas_data)

start_time = time.time()
Expand Down Expand Up @@ -164,7 +164,7 @@
init_logging(debug=debug)

schemas_data = load_yamlfile_from_disk_and_exit(paths=schemas, file_type=SchemaFile, console=console)
client = await initialize_client()
client = initialize_client()

Check warning on line 167 in infrahub_sdk/ctl/schema.py

View check run for this annotation

Codecov / codecov/patch

infrahub_sdk/ctl/schema.py#L167

Added line #L167 was not covered by tests
validate_schema_content_and_exit(client=client, schemas=schemas_data)

success, response = await client.schema.check(schemas=[item.content for item in schemas_data], branch=branch)
Expand Down
2 changes: 1 addition & 1 deletion infrahub_sdk/ctl/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def validate_schema(schema: Path, _: str = CONFIG_PARAM) -> None:
console.print("[red]Invalid JSON file")
raise typer.Exit(1) from exc

client = await initialize_client()
client = initialize_client()

try:
client.schema.validate(schema_data)
Expand Down
Loading