-
Notifications
You must be signed in to change notification settings - Fork 6
Add the ability to export the schema in yaml #835
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
Open
BeArchiTek
wants to merge
12
commits into
stable
Choose a base branch
from
bkr-add-schema-exporter
base: stable
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+554
−0
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0587e7f
Improve schema export output readability
BeArchiTek 8ab1c57
Preserve read_only on computed attributes in schema export
BeArchiTek fbf268a
Filter auto-generated relationships and restore hierarchical flag on …
BeArchiTek bbff1e4
Export generics before nodes; strip auto-generated uniqueness_constra…
BeArchiTek c2e5c92
add changelog
BeArchiTek 91fe627
Refactor schema export logic into dedicated module and regenerate docs
BeArchiTek e63783e
rework exporter function
f371427
Fix _default_export_directory return type to match Path annotation
56e0618
Merge origin/stable into bkr-add-schema-exporter
85dc280
following coderabbit and merge from stable
97a7e6b
Address PR review feedback from ogenstad and coderabbit
fd79f90
Replace nested dict return type with SchemaExport/NamespaceExport Pyd…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add `infrahubctl schema export` command to export schemas from Infrahub. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from pydantic import BaseModel, Field | ||
|
|
||
| from .main import GenericSchemaAPI, NodeSchemaAPI | ||
|
|
||
|
|
||
| class NamespaceExport(BaseModel): | ||
| """Export data for a single namespace.""" | ||
|
|
||
| nodes: list[dict[str, Any]] = Field(default_factory=list) | ||
| generics: list[dict[str, Any]] = Field(default_factory=list) | ||
|
|
||
|
|
||
| class SchemaExport(BaseModel): | ||
| """Result of a schema export, organized by namespace.""" | ||
|
|
||
| namespaces: dict[str, NamespaceExport] = Field(default_factory=dict) | ||
|
|
||
| def to_dict(self) -> dict[str, dict[str, list[dict[str, Any]]]]: | ||
| """Convert to plain dict for YAML serialization.""" | ||
| return {ns: data.model_dump(exclude_defaults=True) for ns, data in self.namespaces.items()} | ||
|
|
||
|
|
||
| # Namespaces reserved by the Infrahub server — mirrored from | ||
| # backend/infrahub/core/constants/__init__.py in the opsmill/infrahub repo. | ||
| RESTRICTED_NAMESPACES: list[str] = [ | ||
| "Account", | ||
| "Branch", | ||
| "Builtin", | ||
| "Core", | ||
| "Deprecated", | ||
| "Diff", | ||
| "Infrahub", | ||
| "Internal", | ||
| "Lineage", | ||
| "Schema", | ||
| "Profile", | ||
| "Template", | ||
| ] | ||
|
|
||
| _SCHEMA_EXPORT_EXCLUDE: set[str] = {"hash", "hierarchy", "used_by", "id", "state"} | ||
| # branch is inherited from the node and need not be repeated on each field | ||
| _FIELD_EXPORT_EXCLUDE: set[str] = {"inherited", "allow_override", "hierarchical", "id", "state", "branch"} | ||
|
|
||
| # Attribute field values that match schema loading defaults — omitted for cleaner output | ||
| _ATTR_EXPORT_DEFAULTS: dict[str, Any] = { | ||
| "read_only": False, | ||
| "optional": False, | ||
| } | ||
|
|
||
| # Relationship field values that match schema loading defaults — omitted for cleaner output | ||
| _REL_EXPORT_DEFAULTS: dict[str, Any] = { | ||
| "direction": "bidirectional", | ||
| "on_delete": "no-action", | ||
| "cardinality": "many", | ||
| "optional": True, | ||
| "min_count": 0, | ||
| "max_count": 0, | ||
| "read_only": False, | ||
| } | ||
|
|
||
| # Relationship kinds that Infrahub generates automatically — never user-defined | ||
| _AUTO_GENERATED_REL_KINDS: frozenset[str] = frozenset({"Group", "Profile", "Hierarchy"}) | ||
|
|
||
|
|
||
| def schema_to_export_dict(schema: NodeSchemaAPI | GenericSchemaAPI) -> dict[str, Any]: | ||
| """Convert an API schema object to an export-ready dict (omits API-internal fields).""" | ||
| data = schema.model_dump(exclude=_SCHEMA_EXPORT_EXCLUDE, exclude_none=True) | ||
|
|
||
| # Pop attrs/rels so they can be re-inserted last for better readability | ||
| data.pop("attributes", None) | ||
| data.pop("relationships", None) | ||
|
|
||
| # Generics with Hierarchy relationships were defined with `hierarchical: true`. | ||
| # Restore that flag and drop the auto-generated rels so the schema round-trips cleanly. | ||
| if isinstance(schema, GenericSchemaAPI) and any( | ||
| rel.kind == "Hierarchy" for rel in schema.relationships if not rel.inherited | ||
| ): | ||
| data["hierarchical"] = True | ||
|
|
||
| # Strip uniqueness_constraints that are auto-generated from `unique: true` attributes | ||
| # (single-field entries of the form ["<attr>__value"]). User-defined multi-field | ||
| # constraints are preserved. | ||
| unique_attr_suffixes = {f"{attr.name}__value" for attr in schema.attributes if attr.unique} | ||
| user_constraints = [ | ||
| c | ||
| for c in (data.pop("uniqueness_constraints", None) or []) | ||
| if not (len(c) == 1 and c[0] in unique_attr_suffixes) | ||
| ] | ||
| if user_constraints: | ||
| data["uniqueness_constraints"] = user_constraints | ||
|
|
||
| attributes = [ | ||
| { | ||
| k: v | ||
| for k, v in attr.model_dump(exclude=_FIELD_EXPORT_EXCLUDE, exclude_none=True).items() | ||
| if k not in _ATTR_EXPORT_DEFAULTS or v != _ATTR_EXPORT_DEFAULTS[k] | ||
| } | ||
| for attr in schema.attributes | ||
| if not attr.inherited | ||
| ] | ||
| if attributes: | ||
| data["attributes"] = attributes | ||
|
|
||
| relationships = [ | ||
| { | ||
| k: v | ||
| for k, v in rel.model_dump(exclude=_FIELD_EXPORT_EXCLUDE, exclude_none=True).items() | ||
| if k not in _REL_EXPORT_DEFAULTS or v != _REL_EXPORT_DEFAULTS[k] | ||
| } | ||
| for rel in schema.relationships | ||
| if not rel.inherited and rel.kind not in _AUTO_GENERATED_REL_KINDS | ||
| ] | ||
| if relationships: | ||
| data["relationships"] = relationships | ||
|
|
||
| return data |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.