Repository navigation
feat: export the schema through the Infrahub export endpoint [IFC-3669] #1554
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
Changes from all commits
a327204
2631a68
c405d50
3229ece
513bd03
e9b8eed
e59fd9c
a5c8240
90f49d4
58ced06
efeebb7
32c3902
9cb60d5
7f4a90d
3dd712b
0a5fd17
07b7f64
b969aa3
ee79914
980d2b8
4980fc5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Removed `schema_to_export_dict`, `RESTRICTED_NAMESPACES`, `NamespaceExport` and `SchemaExport` from `infrahub_sdk.schema`, because Infrahub now builds the schema export. Use `SchemaExportDocument` and `split_by_namespace` instead. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| `InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits an export, either the `SchemaExportDocument` that `export` returns or the JSON body as a dict, into one dict per namespace. From a dict, it copies every field, including fields this SDK version does not know. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. When the document holds a value this SDK version cannot read, such as an attribute kind added in a later Infrahub release, they raise `InvalidResponseError`. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| `infrahubctl schema export` now asks Infrahub to build the export, so it needs an Infrahub server with the schema export endpoint (Infrahub 1.13.0 or later). With the default `BRIEF` mode, the files it writes differ from the files earlier versions wrote: | ||
|
|
||
| - `branch` on an attribute or relationship is written when it differs from the value Infrahub derives from the node or the peer. | ||
| - Values that Infrahub derives when it loads the schema, such as a `label` taken from the name, are left out. | ||
| - When an attribute has `unique: true`, the `human_friendly_id` and `uniqueness_constraints` that Infrahub derives from it are left out, and `unique` is written. | ||
| - The relationship `identifier`, `cardinality` and `optional`, and the attribute `read_only` and `choices`, are written when they differ from their default value. | ||
| - `IpamNamespace` is no longer written. | ||
| - A relationship of kind `Group`, `Profile`, `Hierarchy` or `Template` that you defined is now written. A relationship with the kind, name and identifier of one that Infrahub generates, such as `member_of_groups` or `object_template`, is written only when it differs from the relationship Infrahub generates. Earlier versions left out every relationship of kind `Group`, `Profile` or `Hierarchy`, and wrote the `object_template` relationship that Infrahub generates. | ||
| - On a `Text` or `TextArea` attribute, `regex`, `min_length` and `max_length` are written under `parameters`. On a `List` attribute, `regex` is written under `parameters`, and `min_length` and `max_length` stay at the top level. On an attribute of any other kind, these settings stay at the top level. | ||
| - NumberPool `start_range` and `end_range` are written as one entry of `ranges`. | ||
| - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. | ||
| - The files hold every field the server returned, including fields that a later Infrahub release adds and this SDK version does not know. | ||
| - A value without a line break is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. | ||
| - The files are laid out as `infrahubctl schema format` lays out a schema file: they start with `---` and the `yaml-language-server` comment, and the keys of each node, generic, attribute, relationship and dropdown choice are in the order that command uses. A list that holds no mapping, such as `human_friendly_id` or `uniqueness_constraints`, is written on one line, as in `[[device, name__value]]`. When a file cannot be formatted without changing a value, the command writes no file, prints the error and exits with code 1. | ||
| - The deprecated `default_filter` of a node or generic is no longer written. A `FULL` export still writes it. | ||
| - No `state` field is written on a node, generic, attribute, relationship or dropdown choice, in either mode. | ||
|
|
||
| `--namespaces` with a namespace that does not exist on the branch, or with a namespace reserved for Infrahub such as `Core`, now prints an error for each such namespace and exits with code 1. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Added the `--mode` option to `infrahubctl schema export`: `BRIEF`, the default, leaves out the values Infrahub derives when it loads the schema, and `FULL` writes every value. Added the `--single-file` option, which writes all namespaces to one file, `schema.yml`. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| `infrahubctl schema format` writes the `infrahub_version` field of a schema file directly after `version`. It no longer splits a value longer than 4096 characters over several lines, so such a value in an existing file is written on one line the next time you format the file. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,7 @@ | |
|
|
||
| import asyncio | ||
| import difflib | ||
| import sys | ||
| import time | ||
| from datetime import datetime, timezone | ||
| from enum import Enum | ||
|
|
@@ -17,8 +18,24 @@ | |
| from ..async_typer import AsyncTyper | ||
| from ..ctl.client import initialize_client | ||
| from ..ctl.utils import catch_exception, init_logging | ||
| from ..exceptions import ( | ||
| ApiError, | ||
| AuthenticationError, | ||
| InvalidResponseError, | ||
| JsonDecodeError, | ||
| SchemaNamespaceNotFoundError, | ||
| URLNotFoundError, | ||
| VersionNotSupportedError, | ||
| ) | ||
| from ..queries import SCHEMA_HASH_SYNC_STATUS | ||
| from ..schema import NodeSchemaAPI, SchemaWarning, validate_schema | ||
| from ..schema import ( | ||
| NodeSchemaAPI, | ||
| SchemaExportMode, | ||
| SchemaWarning, | ||
| split_by_namespace, | ||
| validate_schema, | ||
| ) | ||
| from ..schema.export import EXPORT_ELEMENT_SECTIONS | ||
| from ..yaml import SchemaFile | ||
| from .parameters import CONFIG_PARAM | ||
| from .schema_format import ( | ||
|
|
@@ -32,6 +49,26 @@ | |
|
|
||
| SchemaContainer = Literal["nodes", "generics", "relationships"] | ||
|
|
||
| _EXPORT_LINE_WIDTH = sys.maxsize | ||
| """Line width for the exported files, so that a long value such as a Jinja2 template stays on one line.""" | ||
|
|
||
|
|
||
| class _ExportDumper(yaml.SafeDumper): | ||
| """Writes a list that holds no mapping inline, as in `[[device, name__value]]`, as schema files usually do.""" | ||
|
|
||
|
|
||
| def _represent_export_list(dumper: yaml.SafeDumper, data: list[Any]) -> yaml.Node: | ||
| return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=not _holds_mapping(data)) | ||
|
|
||
|
|
||
| def _holds_mapping(value: Any) -> bool: | ||
| if isinstance(value, dict): | ||
| return True | ||
| return isinstance(value, list) and any(_holds_mapping(item) for item in value) | ||
|
|
||
|
|
||
| _ExportDumper.add_representer(list, _represent_export_list) | ||
|
|
||
| app = AsyncTyper() | ||
| console = Console() | ||
|
|
||
|
|
@@ -294,42 +331,92 @@ def _default_export_directory() -> Path: | |
| @app.command() | ||
| @catch_exception(console=console) | ||
| async def export( | ||
| directory: Path = typer.Option(_default_export_directory, help="Directory path to store schema files"), | ||
| directory: Path = typer.Option( | ||
| _default_export_directory, | ||
| show_default="./infrahub-schema-export-<YYYYMMDD-HHMMSS>", | ||
| help="Directory to write the schema files to. Created if it does not exist; existing files with the same name are overwritten.", | ||
| ), | ||
| branch: str = typer.Option(None, help="Branch from which to export the schema"), | ||
| namespaces: list[str] = typer.Option([], help="Namespace(s) to export (default: all user-defined)"), | ||
| mode: SchemaExportMode = typer.Option( | ||
| SchemaExportMode.BRIEF, | ||
| help="BRIEF leaves out the values Infrahub derives when the schema is loaded; FULL writes every value", | ||
| ), | ||
| single_file: bool = typer.Option(False, "--single-file", help="Write all namespaces to one file, schema.yml"), | ||
| debug: bool = False, | ||
| _: str = CONFIG_PARAM, | ||
| ) -> None: | ||
| """Export the schema from Infrahub as YAML files, one per namespace.""" | ||
| """Export the schema from Infrahub as YAML files: one per namespace, or one file with --single-file.""" | ||
| init_logging(debug=debug) | ||
|
|
||
| client = initialize_client() | ||
| user_schemas = await client.schema.export( | ||
| branch=branch, | ||
| namespaces=namespaces or None, | ||
| ) | ||
|
|
||
| if not user_schemas.namespaces: | ||
| try: | ||
| # Written as received, so the files keep the fields an older SDK version does not know. | ||
| document = await client.schema._export_payload(branch=branch, namespaces=namespaces or None, mode=mode) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: (Based on your team's feedback about real-server coverage.) Prompt for AI agents
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, this is a problem with the current testing setup with testcontainers. We'll have a follow up issue for this test. |
||
| except SchemaNamespaceNotFoundError as exc: | ||
| for message in exc.messages: | ||
| console.print(f"[red]Error: {escape(message)}") | ||
| raise typer.Exit(code=1) from exc | ||
| except ( | ||
| VersionNotSupportedError, | ||
| URLNotFoundError, | ||
| JsonDecodeError, | ||
| InvalidResponseError, | ||
| ApiError, | ||
| ) as exc: | ||
| if isinstance(exc, AuthenticationError): | ||
| raise | ||
| console.print(f"[red]Error: {escape(str(exc))}") | ||
| raise typer.Exit(code=1) from exc | ||
|
|
||
| if not any(document.get(section) for section in EXPORT_ELEMENT_SECTIONS): | ||
| console.print("[yellow]No user-defined schema found to export.") | ||
| return | ||
|
|
||
| if single_file: | ||
| output_file = directory / "schema.yml" | ||
| files = [(output_file, document, f"Exported schema to {escape(str(output_file))}")] | ||
| else: | ||
| files = [ | ||
| ( | ||
| directory / f"{ns.lower()}.yml", | ||
| namespace_document, | ||
| f"Exported namespace '{escape(ns)}' to {escape(str(directory / f'{ns.lower()}.yml'))}", | ||
| ) | ||
| for ns, namespace_document in sorted(split_by_namespace(document).items()) | ||
| ] | ||
|
|
||
| try: | ||
| # Every file is rendered before any is written, so a failure leaves no partial export behind. | ||
| rendered = [(output_file, _render_schema_file(content), message) for output_file, content, message in files] | ||
| except FormatError as exc: | ||
| console.print(f"[red]Error: {escape(str(exc))}") | ||
| raise typer.Exit(code=1) from exc | ||
|
|
||
| directory.mkdir(parents=True, exist_ok=True) | ||
| for output_file, text, message in rendered: | ||
| output_file.write_text(text, encoding="utf-8") | ||
| console.print(f"[green] {message}") | ||
|
|
||
| for ns, data in sorted(user_schemas.namespaces.items()): | ||
| payload: dict[str, Any] = {"version": "1.0"} | ||
| if data.generics: | ||
| payload["generics"] = data.generics | ||
| if data.nodes: | ||
| payload["nodes"] = data.nodes | ||
|
|
||
| output_file = directory / f"{ns.lower()}.yml" | ||
| output_file.write_text( | ||
| yaml.dump(payload, default_flow_style=False, sort_keys=False, allow_unicode=True), | ||
| encoding="utf-8", | ||
| ) | ||
| console.print(f"[green] Exported namespace '{ns}' to {output_file}") | ||
| console.print(f"[green] Schema exported to {escape(str(directory))}") | ||
|
|
||
|
|
||
| def _render_schema_file(document: dict[str, Any]) -> str: | ||
| """Return an exported document as YAML in the layout that `infrahubctl schema format` gives a schema file. | ||
|
|
||
| console.print(f"[green] Schema exported to {directory}") | ||
| Raises: | ||
| FormatError: When formatting would change a value of the document. | ||
|
|
||
| """ | ||
| text = yaml.dump( | ||
| document, | ||
| Dumper=_ExportDumper, | ||
| default_flow_style=False, | ||
| sort_keys=False, | ||
| allow_unicode=True, | ||
| width=_EXPORT_LINE_WIDTH, | ||
| ) | ||
| return format_schema_text(text) | ||
|
|
||
|
|
||
| @app.command(name="list") | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.