Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
a327204
feat(schema): accept infrahub_version and list the fields a schema ex…
ogenstad Nov 26, 2026
2631a68
test(schema): check that validate_schema accepts infrahub_version [IF…
ogenstad Nov 26, 2026
c405d50
feat(schema): keep the fields a schema load requires in schema export…
ogenstad Nov 26, 2026
3229ece
feat(schema): export the schema through the server export endpoint [I…
ogenstad Nov 26, 2026
513bd03
docs(changelog): describe the schema export through the server endpoi…
ogenstad Nov 26, 2026
e9b8eed
fix(schema): recognize the error an older server sends for the schema…
ogenstad Nov 26, 2026
e59fd9c
docs(schema): correct the parameters changelog entry and the keep_in_…
ogenstad Nov 26, 2026
a5c8240
feat(schema): report each namespace the schema export cannot select […
ogenstad Nov 27, 2026
90f49d4
fix(schema): report schema export errors with the SDK's own exception…
ogenstad Nov 27, 2026
58ced06
fix(schema): report a rejected login and print bracketed paths in the…
ogenstad Nov 27, 2026
efeebb7
fix(schema): write every field the server returns in the schema expor…
ogenstad Nov 27, 2026
32c3902
fix(schema): accept the exported document in split_by_namespace and r…
ogenstad Nov 30, 2026
9cb60d5
fix(ctl): write each value of an exported schema file on one line [IF…
ogenstad Nov 30, 2026
7f4a90d
feat(ctl): write exported schema files in the layout of schema format…
ogenstad Dec 1, 2026
3dd712b
docs(changelog): note that schema export files hold no state field [I…
ogenstad Dec 1, 2026
0a5fd17
docs(ctl): describe the default and the behavior of schema export --d…
ogenstad Dec 1, 2026
07b7f64
fix(ctl): write no partial schema export and keep scalar lists inline…
ogenstad Dec 1, 2026
b969aa3
test(schema): cover a schema export response whose body is not JSON […
ogenstad Dec 1, 2026
ee79914
fix(schema): keep the namespace order when nodes come before generics…
ogenstad Dec 1, 2026
980d2b8
docs(schema): say a kept export field is left out when it holds its d…
ogenstad Dec 1, 2026
4980fc5
docs(changelog): say which generated-kind relationships the export no…
ogenstad Dec 2, 2026
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/+schema-export-client-rules.removed.md
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.
1 change: 1 addition & 0 deletions changelog/+schema-export-document.changed.md
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`.
18 changes: 18 additions & 0 deletions changelog/+schema-export-endpoint.changed.md
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.
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
- 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.
1 change: 1 addition & 0 deletions changelog/+schema-export-options.added.md
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`.
1 change: 1 addition & 0 deletions changelog/+schema-format-infrahub-version.changed.md
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.
6 changes: 4 additions & 2 deletions docs/docs/infrahubctl/infrahubctl-schema.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ $ infrahubctl schema check [OPTIONS] SCHEMAS...

## `infrahubctl schema export`

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.

**Usage**:

Expand All @@ -78,9 +78,11 @@ $ infrahubctl schema export [OPTIONS]

**Options**:

* `--directory PATH`: Directory path to store schema files [default: (dynamic)]
* `--directory PATH`: Directory to write the schema files to. Created if it does not exist; existing files with the same name are overwritten. [default: (./infrahub-schema-export-<YYYYMMDD-HHMMSS>)]
* `--branch TEXT`: Branch from which to export the schema
* `--namespaces TEXT`: Namespace(s) to export (default: all user-defined)
* `--mode [BRIEF|FULL]`: BRIEF leaves out the values Infrahub derives when the schema is loaded; FULL writes every value [default: BRIEF]
* `--single-file`: Write all namespaces to one file, schema.yml
* `--debug / --no-debug`: [default: no-debug]
* `--config-file TEXT`: [env var: INFRAHUBCTL_CONFIG; default: infrahubctl.toml]
* `--help`: Show this message and exit.
Expand Down
133 changes: 110 additions & 23 deletions infrahub_sdk/ctl/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
import difflib
import sys
import time
from datetime import datetime, timezone
from enum import Enum
Expand All @@ -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 (
Expand All @@ -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()

Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _export_payload is the new production path across the SDK/server boundary, but the added CLI tests only mock GET /api/schema/export; add a functional test against a compatible Infrahub server that runs the command and reloads the generated YAML.

(Based on your team's feedback about real-server coverage.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/ctl/schema.py, line 355:

<comment>`_export_payload` is the new production path across the SDK/server boundary, but the added CLI tests only mock `GET /api/schema/export`; add a functional test against a compatible Infrahub server that runs the command and reloads the generated YAML.

(Based on your team's feedback about real-server coverage.) </comment>

<file context>
@@ -294,42 +331,92 @@ def _default_export_directory() -> Path:
-    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)
+    except SchemaNamespaceNotFoundError as exc:
+        for message in exc.messages:
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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")
Expand Down
7 changes: 4 additions & 3 deletions infrahub_sdk/ctl/schema_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

import json
import re
import sys
from dataclasses import dataclass
from io import StringIO
from typing import Any
Expand Down Expand Up @@ -73,7 +74,7 @@
# Canonical key orders. Each pair is (leading keys, trailing keys); any key not
# listed is preserved in its original position between the two groups so the
# formatter never drops data.
FILE_ORDER = ["version", "generics", "nodes", "extensions"]
FILE_ORDER = ["version", "infrahub_version", "generics", "nodes", "extensions"]

NODE_ORDER = [
"name",
Expand Down Expand Up @@ -205,9 +206,9 @@ def _build_yaml() -> YAML:
# Match the schema-library layout: block sequences indented under their key
# (`attributes:\n - name: ...`).
yaml_handler.indent(mapping=2, sequence=4, offset=2)
# A very wide value keeps long scalars (descriptions, Jinja2 templates) on
# An unlimited width keeps long scalars (descriptions, Jinja2 templates) on
# their original line instead of being re-wrapped.
yaml_handler.width = 4096
yaml_handler.width = sys.maxsize
return yaml_handler


Expand Down
2 changes: 2 additions & 0 deletions infrahub_sdk/exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
RateLimitError,
RepositoryFileNotFoundError,
ResourceNotDefinedError,
SchemaNamespaceNotFoundError,
SchemaNotFoundError,
ServerNotReachableError,
ServerNotResponsiveError,
Expand Down Expand Up @@ -106,6 +107,7 @@
"RateLimitError",
"RepositoryFileNotFoundError",
"ResourceNotDefinedError",
"SchemaNamespaceNotFoundError",
"SchemaNotFoundError",
"ServerNotReachableError",
"ServerNotResponsiveError",
Expand Down
16 changes: 16 additions & 0 deletions infrahub_sdk/exceptions/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"RateLimitError",
"RepositoryFileNotFoundError",
"ResourceNotDefinedError",
"SchemaNamespaceNotFoundError",
"SchemaNotFoundError",
"ServerNotReachableError",
"ServerNotResponsiveError",
Expand Down Expand Up @@ -206,6 +207,18 @@ def __reduce__(self) -> tuple[type[TrackingGroupCleanupError], tuple[dict[str, s
return (self.__class__, (self.failures,))


class SchemaNamespaceNotFoundError(ApiError):
"""Raised when a schema export names a namespace that does not exist on the branch or cannot be exported."""

def __init__(self, namespaces: list[str], messages: list[str]) -> None:
self.namespaces = namespaces
self.messages = messages
super().__init__("; ".join(messages))

def __reduce__(self) -> tuple[Any, ...]:
return (_rebuild_error, (type(self), self.args, self.__dict__))


class VersionNotSupportedError(Error):
"""Raised when a feature is used against an Infrahub server version that does not support it."""

Expand All @@ -215,6 +228,9 @@ def __init__(self, feature: str, required_version: str) -> None:
self.message = f"{feature} requires Infrahub {required_version} or later."
super().__init__(self.message)

def __reduce__(self) -> tuple[Any, ...]:
return (_rebuild_error, (type(self), self.args, self.__dict__))


class BranchNotFoundPayload(Protocol):
"""The fields a server-reported BRANCH_NOT_FOUND carries."""
Expand Down
Loading
Loading