any2tosca 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- any2tosca/__init__.py +26 -0
- any2tosca/cli.py +371 -0
- any2tosca/converter.py +2060 -0
- any2tosca/openapi.py +142 -0
- any2tosca/redfish.py +177 -0
- any2tosca/yaml_utils.py +83 -0
- any2tosca/yang.py +239 -0
- any2tosca-0.1.0.dist-info/METADATA +419 -0
- any2tosca-0.1.0.dist-info/RECORD +13 -0
- any2tosca-0.1.0.dist-info/WHEEL +5 -0
- any2tosca-0.1.0.dist-info/entry_points.txt +5 -0
- any2tosca-0.1.0.dist-info/licenses/LICENSE +202 -0
- any2tosca-0.1.0.dist-info/top_level.txt +1 -0
any2tosca/openapi.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""
|
|
2
|
+
openapi.py
|
|
3
|
+
----------
|
|
4
|
+
Pre-processor that extracts JSON Schema from OpenAPI 2.0 and 3.x documents
|
|
5
|
+
and identifies which schemas should become TOSCA node types.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
__author__ = "Chris Lauwers"
|
|
11
|
+
__copyright__ = "Copyright (c) 2022-2026, Ubicity Corp."
|
|
12
|
+
__email__ = "info@ubicity.com"
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
__all__ = ["OpenAPIExtractor"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class OpenAPIExtractor:
|
|
21
|
+
"""
|
|
22
|
+
Extracts and normalizes JSON Schema from an OpenAPI document.
|
|
23
|
+
|
|
24
|
+
Usage::
|
|
25
|
+
|
|
26
|
+
extractor = OpenAPIExtractor()
|
|
27
|
+
root_schema, node_type_names = extractor.extract(openapi_doc)
|
|
28
|
+
result = Converter().convert_schema(root_schema, "api", node_type_names)
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def extract(self, openapi_doc: dict[str, Any]) -> tuple[dict[str, Any], set[str]]:
|
|
32
|
+
"""
|
|
33
|
+
Convert an OpenAPI document into a normalized JSON Schema dict and
|
|
34
|
+
a set of schema names that should become TOSCA node types.
|
|
35
|
+
|
|
36
|
+
Schemas referenced in POST request bodies are classified as node types.
|
|
37
|
+
|
|
38
|
+
Returns
|
|
39
|
+
-------
|
|
40
|
+
tuple[dict, set[str]]
|
|
41
|
+
``(root_schema, node_type_names)`` ready to pass to
|
|
42
|
+
``Converter.convert_schema()``.
|
|
43
|
+
"""
|
|
44
|
+
version = str(openapi_doc.get("openapi", openapi_doc.get("swagger", "")))
|
|
45
|
+
if version.startswith("3."):
|
|
46
|
+
return self._extract_3x(openapi_doc)
|
|
47
|
+
return self._extract_2x(openapi_doc)
|
|
48
|
+
|
|
49
|
+
# ── OpenAPI 3.x ───────────────────────────────────────────────────────────
|
|
50
|
+
|
|
51
|
+
def _extract_3x(self, doc: dict[str, Any]) -> tuple[dict[str, Any], set[str]]:
|
|
52
|
+
schemas = copy.deepcopy(doc.get("components", {}).get("schemas", {}))
|
|
53
|
+
for name in list(schemas):
|
|
54
|
+
schemas[name] = self._normalize_schema(schemas[name])
|
|
55
|
+
|
|
56
|
+
# Rewrite all $refs before handing off to the converter
|
|
57
|
+
root_schema: dict[str, Any] = self._rewrite_refs_3x({"definitions": schemas})
|
|
58
|
+
|
|
59
|
+
node_type_names = self._post_schema_names_3x(doc)
|
|
60
|
+
return root_schema, node_type_names
|
|
61
|
+
|
|
62
|
+
def _rewrite_refs_3x(self, obj: Any) -> Any:
|
|
63
|
+
"""Rewrite ``#/components/schemas/X`` refs to ``#/definitions/X``."""
|
|
64
|
+
if isinstance(obj, dict):
|
|
65
|
+
return {
|
|
66
|
+
k: (
|
|
67
|
+
"#/definitions/" + v.split("/")[-1]
|
|
68
|
+
if k == "$ref" and isinstance(v, str)
|
|
69
|
+
and v.startswith("#/components/schemas/")
|
|
70
|
+
else self._rewrite_refs_3x(v)
|
|
71
|
+
)
|
|
72
|
+
for k, v in obj.items()
|
|
73
|
+
}
|
|
74
|
+
if isinstance(obj, list):
|
|
75
|
+
return [self._rewrite_refs_3x(item) for item in obj]
|
|
76
|
+
return obj
|
|
77
|
+
|
|
78
|
+
def _post_schema_names_3x(self, doc: dict[str, Any]) -> set[str]:
|
|
79
|
+
"""Return schema names used as POST requestBody schemas (OpenAPI 3.x)."""
|
|
80
|
+
names: set[str] = set()
|
|
81
|
+
for path_item in doc.get("paths", {}).values():
|
|
82
|
+
post = path_item.get("post", {})
|
|
83
|
+
for media in post.get("requestBody", {}).get("content", {}).values():
|
|
84
|
+
ref = media.get("schema", {}).get("$ref", "")
|
|
85
|
+
if ref.startswith("#/components/schemas/"):
|
|
86
|
+
names.add(ref.split("/")[-1])
|
|
87
|
+
return names
|
|
88
|
+
|
|
89
|
+
# ── OpenAPI 2.0 (Swagger) ─────────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
def _extract_2x(self, doc: dict[str, Any]) -> tuple[dict[str, Any], set[str]]:
|
|
92
|
+
schemas = copy.deepcopy(doc.get("definitions", {}))
|
|
93
|
+
for name in list(schemas):
|
|
94
|
+
schemas[name] = self._normalize_schema(schemas[name])
|
|
95
|
+
|
|
96
|
+
root_schema: dict[str, Any] = {"definitions": schemas}
|
|
97
|
+
node_type_names = self._post_schema_names_2x(doc)
|
|
98
|
+
return root_schema, node_type_names
|
|
99
|
+
|
|
100
|
+
def _post_schema_names_2x(self, doc: dict[str, Any]) -> set[str]:
|
|
101
|
+
"""Return schema names used as POST body parameters (OpenAPI 2.0)."""
|
|
102
|
+
names: set[str] = set()
|
|
103
|
+
for path_item in doc.get("paths", {}).values():
|
|
104
|
+
for param in path_item.get("post", {}).get("parameters", []):
|
|
105
|
+
if param.get("in") == "body":
|
|
106
|
+
ref = param.get("schema", {}).get("$ref", "")
|
|
107
|
+
if ref.startswith("#/definitions/"):
|
|
108
|
+
names.add(ref.split("/")[-1])
|
|
109
|
+
return names
|
|
110
|
+
|
|
111
|
+
# ── Schema normalization ───────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
def _normalize_schema(self, schema: Any) -> Any:
|
|
114
|
+
"""Recursively normalize a schema fragment to plain JSON Schema."""
|
|
115
|
+
if not isinstance(schema, dict):
|
|
116
|
+
return schema
|
|
117
|
+
|
|
118
|
+
# Flatten anyOf/oneOf where the only variation is a null alternative
|
|
119
|
+
for kw in ("anyOf", "oneOf"):
|
|
120
|
+
if kw in schema:
|
|
121
|
+
non_null = [
|
|
122
|
+
s for s in schema[kw]
|
|
123
|
+
if not (isinstance(s, dict) and s.get("type") == "null")
|
|
124
|
+
]
|
|
125
|
+
if len(non_null) == 1 and len(schema[kw]) > len(non_null):
|
|
126
|
+
merged = {**non_null[0], **{k: v for k, v in schema.items() if k != kw}}
|
|
127
|
+
return self._normalize_schema(merged)
|
|
128
|
+
|
|
129
|
+
# Drop OpenAPI 3.0 nullable extension (TOSCA has no null type)
|
|
130
|
+
schema = {k: v for k, v in schema.items() if k != "nullable"}
|
|
131
|
+
|
|
132
|
+
# Recurse into sub-schemas
|
|
133
|
+
if "properties" in schema:
|
|
134
|
+
schema["properties"] = {
|
|
135
|
+
k: self._normalize_schema(v) for k, v in schema["properties"].items()
|
|
136
|
+
}
|
|
137
|
+
if "items" in schema:
|
|
138
|
+
schema["items"] = self._normalize_schema(schema["items"])
|
|
139
|
+
if isinstance(schema.get("additionalProperties"), dict):
|
|
140
|
+
schema["additionalProperties"] = self._normalize_schema(schema["additionalProperties"])
|
|
141
|
+
|
|
142
|
+
return schema
|
any2tosca/redfish.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""
|
|
2
|
+
redfish.py
|
|
3
|
+
----------
|
|
4
|
+
Pre-processor that normalizes Redfish JSON Schema for use with the Converter.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
__author__ = "Chris Lauwers"
|
|
10
|
+
__copyright__ = "Copyright (c) 2022-2026, Ubicity Corp."
|
|
11
|
+
__email__ = "info@ubicity.com"
|
|
12
|
+
|
|
13
|
+
import copy
|
|
14
|
+
import re
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
__all__ = ["RedfishNormalizer"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RedfishNormalizer:
|
|
21
|
+
"""
|
|
22
|
+
Normalizes a Redfish JSON Schema document into plain JSON Schema.
|
|
23
|
+
|
|
24
|
+
Redfish quirks handled:
|
|
25
|
+
|
|
26
|
+
- The top-level ``$ref`` identifies the resource type → becomes a node type.
|
|
27
|
+
- ``anyOf: [{$ref: ...}, {type: null}]`` → flattened to the non-null schema.
|
|
28
|
+
- ``@odata.*`` and ``@Redfish.*`` properties are dropped.
|
|
29
|
+
- ``x-longDescription`` is promoted to ``description`` when no description
|
|
30
|
+
is present.
|
|
31
|
+
- All other ``x-*`` extension keywords are dropped.
|
|
32
|
+
- External ``$ref`` URIs are left as-is; the converter treats them as
|
|
33
|
+
unresolvable and skips them gracefully.
|
|
34
|
+
|
|
35
|
+
Usage::
|
|
36
|
+
|
|
37
|
+
normalizer = RedfishNormalizer()
|
|
38
|
+
root_schema, node_type_names = normalizer.normalize(redfish_schema)
|
|
39
|
+
result = Converter().convert_schema(root_schema, "api", node_type_names)
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
#: Property name prefixes that are Redfish/OData annotations, not data.
|
|
43
|
+
EXCLUDED_PREFIXES: tuple[str, ...] = ("@odata.", "@Redfish.")
|
|
44
|
+
|
|
45
|
+
def normalize(self, redfish_schema: dict[str, Any]) -> tuple[dict[str, Any], set[str]]:
|
|
46
|
+
"""
|
|
47
|
+
Normalize a Redfish schema into a plain JSON Schema dict and
|
|
48
|
+
a set of definition names that should become TOSCA node types.
|
|
49
|
+
|
|
50
|
+
Two schema layouts are handled:
|
|
51
|
+
|
|
52
|
+
- **Definitions-based** (typical): a top-level ``$ref`` names the
|
|
53
|
+
resource; all types live under ``definitions``.
|
|
54
|
+
- **Flat** (e.g. ``Resource.json``): properties are defined directly
|
|
55
|
+
at the top level with no ``definitions`` section. The resource name
|
|
56
|
+
is derived from the ``title`` field.
|
|
57
|
+
|
|
58
|
+
Returns
|
|
59
|
+
-------
|
|
60
|
+
tuple[dict, set[str]]
|
|
61
|
+
``(root_schema, node_type_names)`` ready to pass to
|
|
62
|
+
``Converter.convert_schema()``.
|
|
63
|
+
"""
|
|
64
|
+
resource_name = self._resource_name(redfish_schema) or self._title_name(redfish_schema)
|
|
65
|
+
|
|
66
|
+
definitions: dict[str, Any] = {}
|
|
67
|
+
for name, schema in redfish_schema.get("definitions", {}).items():
|
|
68
|
+
if isinstance(schema, dict):
|
|
69
|
+
definitions[name] = self._normalize_schema(schema)
|
|
70
|
+
|
|
71
|
+
if definitions:
|
|
72
|
+
root_schema: dict[str, Any] = {"definitions": definitions}
|
|
73
|
+
else:
|
|
74
|
+
# Flat schema: properties live at the top level — normalize directly.
|
|
75
|
+
_skip = {"$schema", "$id", "$ref", "title", "definitions", "$defs"}
|
|
76
|
+
root_schema = self._normalize_schema(
|
|
77
|
+
{k: v for k, v in redfish_schema.items() if k not in _skip}
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
node_type_names: set[str] = {resource_name} if resource_name else set()
|
|
81
|
+
return root_schema, node_type_names
|
|
82
|
+
|
|
83
|
+
# ── Helpers ───────────────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
def _resource_name(self, redfish_schema: dict[str, Any]) -> str | None:
|
|
86
|
+
"""Return the definition name pointed to by the top-level ``$ref``."""
|
|
87
|
+
ref = redfish_schema.get("$ref", "")
|
|
88
|
+
if ref.startswith("#/definitions/"):
|
|
89
|
+
return ref.split("/")[-1]
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
#: Matches Redfish version suffix segments like ``v1_7_0`` or ``v1.7.0``.
|
|
93
|
+
_VER_SEGMENT = re.compile(r"^v\d+[._]\d+[._]\d+")
|
|
94
|
+
|
|
95
|
+
def _title_name(self, redfish_schema: dict[str, Any]) -> str | None:
|
|
96
|
+
"""
|
|
97
|
+
Derive a type name from the ``title`` field.
|
|
98
|
+
|
|
99
|
+
Redfish titles look like ``"#Resource.Resource"``, ``"#ProcessorCollection.ProcessorCollection"``,
|
|
100
|
+
or ``"#Redundancy.v1_7_0"`` (versioned). We strip the leading ``#``,
|
|
101
|
+
split on ``.``, skip any trailing version segment, then return the last segment.
|
|
102
|
+
"""
|
|
103
|
+
title = redfish_schema.get("title", "").lstrip("#")
|
|
104
|
+
if not title:
|
|
105
|
+
return None
|
|
106
|
+
parts = title.split(".")
|
|
107
|
+
# Drop a trailing version segment (e.g. "v1_7_0") to get the base type name.
|
|
108
|
+
if len(parts) >= 2 and self._VER_SEGMENT.match(parts[-1]):
|
|
109
|
+
parts = parts[:-1]
|
|
110
|
+
return parts[-1] or None
|
|
111
|
+
|
|
112
|
+
def _normalize_schema(self, schema: dict[str, Any]) -> dict[str, Any]:
|
|
113
|
+
"""Normalize a definition schema."""
|
|
114
|
+
schema = copy.deepcopy(schema)
|
|
115
|
+
|
|
116
|
+
# Promote x-longDescription to description
|
|
117
|
+
if "description" not in schema and "x-longDescription" in schema:
|
|
118
|
+
schema["description"] = schema["x-longDescription"]
|
|
119
|
+
|
|
120
|
+
# Drop all x-* extension keywords
|
|
121
|
+
schema = {k: v for k, v in schema.items() if not k.startswith("x-")}
|
|
122
|
+
|
|
123
|
+
if "properties" in schema:
|
|
124
|
+
schema["properties"] = self._normalize_properties(schema["properties"])
|
|
125
|
+
if not schema["properties"]:
|
|
126
|
+
del schema["properties"]
|
|
127
|
+
|
|
128
|
+
if "items" in schema:
|
|
129
|
+
schema["items"] = self._normalize_property_schema(schema["items"])
|
|
130
|
+
|
|
131
|
+
if isinstance(schema.get("additionalProperties"), dict):
|
|
132
|
+
schema["additionalProperties"] = self._normalize_property_schema(
|
|
133
|
+
schema["additionalProperties"]
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
return schema
|
|
137
|
+
|
|
138
|
+
def _normalize_properties(self, properties: dict[str, Any]) -> dict[str, Any]:
|
|
139
|
+
"""Filter and normalize a properties dict."""
|
|
140
|
+
result: dict[str, Any] = {}
|
|
141
|
+
for name, prop_schema in properties.items():
|
|
142
|
+
if any(name.startswith(prefix) for prefix in self.EXCLUDED_PREFIXES):
|
|
143
|
+
continue
|
|
144
|
+
result[name] = self._normalize_property_schema(prop_schema)
|
|
145
|
+
return result
|
|
146
|
+
|
|
147
|
+
def _normalize_property_schema(self, schema: Any) -> Any:
|
|
148
|
+
"""Normalize a property schema, flattening anyOf/null patterns."""
|
|
149
|
+
if not isinstance(schema, dict):
|
|
150
|
+
return schema
|
|
151
|
+
|
|
152
|
+
# Flatten anyOf: [{...}, {type: null}] → the non-null alternative
|
|
153
|
+
if "anyOf" in schema:
|
|
154
|
+
non_null = [
|
|
155
|
+
s for s in schema["anyOf"]
|
|
156
|
+
if not (isinstance(s, dict) and s.get("type") == "null")
|
|
157
|
+
]
|
|
158
|
+
if len(non_null) == 1:
|
|
159
|
+
merged = {**non_null[0], **{k: v for k, v in schema.items() if k != "anyOf"}}
|
|
160
|
+
return self._normalize_property_schema(merged)
|
|
161
|
+
|
|
162
|
+
# Promote x-longDescription
|
|
163
|
+
if "description" not in schema and "x-longDescription" in schema:
|
|
164
|
+
schema = dict(schema)
|
|
165
|
+
schema["description"] = schema["x-longDescription"]
|
|
166
|
+
|
|
167
|
+
# Drop x-* extensions
|
|
168
|
+
schema = {k: v for k, v in schema.items() if not k.startswith("x-")}
|
|
169
|
+
|
|
170
|
+
# Recurse into nested properties and array items
|
|
171
|
+
if "properties" in schema:
|
|
172
|
+
schema["properties"] = self._normalize_properties(schema["properties"])
|
|
173
|
+
|
|
174
|
+
if "items" in schema:
|
|
175
|
+
schema["items"] = self._normalize_property_schema(schema["items"])
|
|
176
|
+
|
|
177
|
+
return schema
|
any2tosca/yaml_utils.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""
|
|
2
|
+
yaml_utils.py
|
|
3
|
+
-------------
|
|
4
|
+
YAML serialisation helpers for TOSCA output.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
__author__ = "Chris Lauwers"
|
|
10
|
+
__copyright__ = "Copyright (c) 2022-2026, Ubicity Corp."
|
|
11
|
+
__email__ = "info@ubicity.com"
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import yaml
|
|
17
|
+
|
|
18
|
+
__all__ = ["dump_tosca_yaml", "FoldedStr", "CommentedOut"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FoldedStr(str):
|
|
22
|
+
"""A str subclass that serialises with YAML folded block style (``>``)."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CommentedOut(str):
|
|
26
|
+
"""A string value that should be emitted as a commented-out YAML line.
|
|
27
|
+
|
|
28
|
+
When a dict entry has a ``CommentedOut`` value the entire ``key: value``
|
|
29
|
+
line is rendered as a YAML comment: ``# key: value``. Used to annotate
|
|
30
|
+
circular-import type references that cannot be resolved without creating
|
|
31
|
+
a cycle (e.g. mutually-referencing Redfish schema families).
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ── Custom representers ────────────────────────────────────────────────────────
|
|
36
|
+
|
|
37
|
+
def _str_representer(dumper: yaml.Dumper, data: str) -> yaml.Node:
|
|
38
|
+
if "\n" in data:
|
|
39
|
+
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
|
|
40
|
+
return dumper.represent_scalar("tag:yaml.org,2002:str", data)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _folded_str_representer(dumper: yaml.Dumper, data: FoldedStr) -> yaml.Node:
|
|
44
|
+
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style=">")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _commented_out_representer(dumper: yaml.Dumper, data: CommentedOut) -> yaml.Node:
|
|
48
|
+
"""Emit with the local tag ``!co`` so post-processing can detect and comment out."""
|
|
49
|
+
return dumper.represent_scalar("!co", str(data))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
_dumper = yaml.Dumper
|
|
53
|
+
_dumper.add_representer(str, _str_representer)
|
|
54
|
+
_dumper.add_representer(FoldedStr, _folded_str_representer)
|
|
55
|
+
_dumper.add_representer(CommentedOut, _commented_out_representer)
|
|
56
|
+
|
|
57
|
+
# Regex that matches a YAML line whose value was tagged !co by the representer.
|
|
58
|
+
# Captures: (indent)(key)(value-possibly-quoted)
|
|
59
|
+
_CO_RE = re.compile(
|
|
60
|
+
r"^(\s+)([^:\n]+):\s+!co\s+(.*?)\s*$",
|
|
61
|
+
re.MULTILINE,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _uncomment_line(m: re.Match[str]) -> str:
|
|
66
|
+
"""Replace ``indent key: !co value`` with ``indent # key: value``."""
|
|
67
|
+
val = m.group(3)
|
|
68
|
+
# Strip surrounding single or double quotes that PyYAML may have added
|
|
69
|
+
if len(val) >= 2 and val[0] == val[-1] and val[0] in ("'", '"'):
|
|
70
|
+
val = val[1:-1]
|
|
71
|
+
return f"{m.group(1)}# {m.group(2)}: {val}"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def dump_tosca_yaml(data: dict[str, Any]) -> str:
|
|
75
|
+
"""Serialise *data* to a TOSCA-friendly YAML string."""
|
|
76
|
+
raw = yaml.dump(
|
|
77
|
+
data,
|
|
78
|
+
Dumper=_dumper,
|
|
79
|
+
default_flow_style=False,
|
|
80
|
+
sort_keys=False,
|
|
81
|
+
allow_unicode=True,
|
|
82
|
+
)
|
|
83
|
+
return _CO_RE.sub(_uncomment_line, raw)
|
any2tosca/yang.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""
|
|
2
|
+
yang.py
|
|
3
|
+
-------
|
|
4
|
+
Pre-processor that converts YANG modules to a JSON Schema-like dict
|
|
5
|
+
for use with the Converter.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
__author__ = "Chris Lauwers"
|
|
11
|
+
__copyright__ = "Copyright (c) 2022-2026, Ubicity Corp."
|
|
12
|
+
__email__ = "info@ubicity.com"
|
|
13
|
+
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from pyang.context import Context
|
|
18
|
+
from pyang.repository import FileRepository
|
|
19
|
+
|
|
20
|
+
__all__ = ["YANGNormalizer"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _to_int(s: str) -> int | None:
|
|
24
|
+
try:
|
|
25
|
+
return int(s)
|
|
26
|
+
except (ValueError, TypeError):
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class YANGNormalizer:
|
|
31
|
+
"""
|
|
32
|
+
Converts a YANG module file to a plain JSON Schema-like dict.
|
|
33
|
+
|
|
34
|
+
Top-level ``container`` and ``list`` statements become TOSCA node types.
|
|
35
|
+
``typedef`` statements become TOSCA data types.
|
|
36
|
+
``grouping`` statements expanded via ``uses`` are inlined automatically
|
|
37
|
+
by pyang during validation.
|
|
38
|
+
|
|
39
|
+
Usage::
|
|
40
|
+
|
|
41
|
+
normalizer = YANGNormalizer()
|
|
42
|
+
root_schema, node_type_names = normalizer.normalize(Path("server.yang"))
|
|
43
|
+
result = Converter().convert_schema(root_schema, normalizer.module_name,
|
|
44
|
+
node_type_names, base_path=path.parent)
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
# YANG built-in type names → JSON Schema type strings
|
|
48
|
+
YANG_TO_JSON: dict[str, str] = {
|
|
49
|
+
"string": "string",
|
|
50
|
+
"boolean": "boolean",
|
|
51
|
+
"int8": "integer",
|
|
52
|
+
"int16": "integer",
|
|
53
|
+
"int32": "integer",
|
|
54
|
+
"int64": "integer",
|
|
55
|
+
"uint8": "integer",
|
|
56
|
+
"uint16": "integer",
|
|
57
|
+
"uint32": "integer",
|
|
58
|
+
"uint64": "integer",
|
|
59
|
+
"decimal64": "number",
|
|
60
|
+
"binary": "string",
|
|
61
|
+
"empty": "null",
|
|
62
|
+
"anyxml": "string",
|
|
63
|
+
"anydata": "string",
|
|
64
|
+
"leafref": "string",
|
|
65
|
+
"identityref": "string",
|
|
66
|
+
"instance-identifier": "string",
|
|
67
|
+
"bits": "string",
|
|
68
|
+
"counter32": "integer",
|
|
69
|
+
"counter64": "integer",
|
|
70
|
+
"gauge32": "integer",
|
|
71
|
+
"gauge64": "integer",
|
|
72
|
+
"timeticks": "integer",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
def __init__(self) -> None:
|
|
76
|
+
self.module_name: str = ""
|
|
77
|
+
|
|
78
|
+
def normalize(self, yang_path: Path) -> tuple[dict[str, Any], set[str]]:
|
|
79
|
+
"""
|
|
80
|
+
Parse *yang_path* and return a JSON Schema-like dict plus the set of
|
|
81
|
+
names that should become TOSCA node types.
|
|
82
|
+
|
|
83
|
+
All YANG files in the same directory are added to the pyang search
|
|
84
|
+
path so that ``import`` and ``include`` statements resolve correctly.
|
|
85
|
+
|
|
86
|
+
Returns
|
|
87
|
+
-------
|
|
88
|
+
tuple[dict, set[str]]
|
|
89
|
+
``(root_schema, node_type_names)`` ready for
|
|
90
|
+
``Converter.convert_schema()``.
|
|
91
|
+
"""
|
|
92
|
+
ctx = Context(FileRepository(str(yang_path.parent)))
|
|
93
|
+
with open(yang_path, encoding="utf-8") as fh:
|
|
94
|
+
text = fh.read()
|
|
95
|
+
mod_stmt = ctx.add_module(str(yang_path), text)
|
|
96
|
+
ctx.validate()
|
|
97
|
+
|
|
98
|
+
mod = ctx.get_module(mod_stmt.arg, None)
|
|
99
|
+
self.module_name = mod.arg
|
|
100
|
+
|
|
101
|
+
definitions: dict[str, Any] = {}
|
|
102
|
+
node_type_names: set[str] = set()
|
|
103
|
+
|
|
104
|
+
# typedefs → definitions (data types)
|
|
105
|
+
for stmt in mod.substmts:
|
|
106
|
+
if stmt.keyword == "typedef":
|
|
107
|
+
definitions[stmt.arg] = self._typedef_to_schema(stmt)
|
|
108
|
+
|
|
109
|
+
# top-level containers and lists → definitions + node types
|
|
110
|
+
for stmt in getattr(mod, "i_children", []) or []:
|
|
111
|
+
if stmt.keyword in ("container", "list"):
|
|
112
|
+
definitions[stmt.arg] = self._container_to_schema(stmt)
|
|
113
|
+
node_type_names.add(stmt.arg)
|
|
114
|
+
|
|
115
|
+
return {"definitions": definitions}, node_type_names
|
|
116
|
+
|
|
117
|
+
# ── Conversion helpers ────────────────────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
def _typedef_to_schema(self, typedef: Any) -> dict[str, Any]:
|
|
120
|
+
type_stmt = typedef.search_one("type")
|
|
121
|
+
schema = self._type_to_schema(type_stmt) if type_stmt else {"type": "string"}
|
|
122
|
+
desc = typedef.search_one("description")
|
|
123
|
+
if desc:
|
|
124
|
+
schema["description"] = desc.arg
|
|
125
|
+
return schema
|
|
126
|
+
|
|
127
|
+
def _container_to_schema(self, stmt: Any) -> dict[str, Any]:
|
|
128
|
+
schema: dict[str, Any] = {"type": "object"}
|
|
129
|
+
desc = stmt.search_one("description")
|
|
130
|
+
if desc:
|
|
131
|
+
schema["description"] = desc.arg
|
|
132
|
+
|
|
133
|
+
properties: dict[str, Any] = {}
|
|
134
|
+
required: list[str] = []
|
|
135
|
+
|
|
136
|
+
for child in getattr(stmt, "i_children", []) or []:
|
|
137
|
+
prop = self._child_to_schema(child)
|
|
138
|
+
if prop is None:
|
|
139
|
+
continue
|
|
140
|
+
properties[child.arg] = prop
|
|
141
|
+
mandatory = child.search_one("mandatory")
|
|
142
|
+
if mandatory and mandatory.arg == "true":
|
|
143
|
+
required.append(child.arg)
|
|
144
|
+
|
|
145
|
+
if properties:
|
|
146
|
+
schema["properties"] = properties
|
|
147
|
+
if required:
|
|
148
|
+
schema["required"] = required
|
|
149
|
+
|
|
150
|
+
return schema
|
|
151
|
+
|
|
152
|
+
def _child_to_schema(self, stmt: Any) -> dict[str, Any] | None:
|
|
153
|
+
kw = stmt.keyword
|
|
154
|
+
desc = stmt.search_one("description")
|
|
155
|
+
|
|
156
|
+
if kw == "leaf":
|
|
157
|
+
type_stmt = stmt.search_one("type")
|
|
158
|
+
prop = self._type_to_schema(type_stmt) if type_stmt else {"type": "string"}
|
|
159
|
+
if desc:
|
|
160
|
+
prop["description"] = desc.arg
|
|
161
|
+
return prop
|
|
162
|
+
|
|
163
|
+
if kw == "leaf-list":
|
|
164
|
+
type_stmt = stmt.search_one("type")
|
|
165
|
+
items = self._type_to_schema(type_stmt) if type_stmt else {"type": "string"}
|
|
166
|
+
prop: dict[str, Any] = {"type": "array", "items": items}
|
|
167
|
+
if desc:
|
|
168
|
+
prop["description"] = desc.arg
|
|
169
|
+
return prop
|
|
170
|
+
|
|
171
|
+
if kw == "container":
|
|
172
|
+
return self._container_to_schema(stmt)
|
|
173
|
+
|
|
174
|
+
if kw == "list":
|
|
175
|
+
# A YANG list is an array of objects; expose the item schema
|
|
176
|
+
item_schema = self._container_to_schema(stmt)
|
|
177
|
+
prop = {"type": "array", "items": item_schema}
|
|
178
|
+
if desc:
|
|
179
|
+
prop["description"] = desc.arg
|
|
180
|
+
return prop
|
|
181
|
+
|
|
182
|
+
return None # rpc, notification, action, etc. — skip
|
|
183
|
+
|
|
184
|
+
def _type_to_schema(self, type_stmt: Any) -> dict[str, Any]:
|
|
185
|
+
type_name = type_stmt.arg
|
|
186
|
+
|
|
187
|
+
if type_name == "enumeration":
|
|
188
|
+
enums = [e.arg for e in type_stmt.search("enum")]
|
|
189
|
+
return {"type": "string", "enum": enums}
|
|
190
|
+
|
|
191
|
+
if type_name == "union":
|
|
192
|
+
for member in type_stmt.search("type"):
|
|
193
|
+
candidate = self._type_to_schema(member)
|
|
194
|
+
if candidate.get("type") not in (None, "null"):
|
|
195
|
+
return candidate
|
|
196
|
+
return {"type": "string"}
|
|
197
|
+
|
|
198
|
+
json_type = self.YANG_TO_JSON.get(type_name)
|
|
199
|
+
if json_type is None:
|
|
200
|
+
# Named typedef reference
|
|
201
|
+
return {"$ref": f"#/definitions/{type_name}"}
|
|
202
|
+
|
|
203
|
+
schema: dict[str, Any] = {"type": json_type}
|
|
204
|
+
|
|
205
|
+
# Range → numeric min/max constraints
|
|
206
|
+
range_stmt = type_stmt.search_one("range")
|
|
207
|
+
if range_stmt and json_type in ("integer", "number"):
|
|
208
|
+
lo, hi = self._parse_range(range_stmt.arg)
|
|
209
|
+
if lo is not None:
|
|
210
|
+
schema["minimum"] = lo
|
|
211
|
+
if hi is not None:
|
|
212
|
+
schema["maximum"] = hi
|
|
213
|
+
|
|
214
|
+
# Length → string minLength/maxLength
|
|
215
|
+
length_stmt = type_stmt.search_one("length")
|
|
216
|
+
if length_stmt and json_type == "string":
|
|
217
|
+
lo, hi = self._parse_range(length_stmt.arg)
|
|
218
|
+
if lo is not None:
|
|
219
|
+
schema["minLength"] = lo
|
|
220
|
+
if hi is not None:
|
|
221
|
+
schema["maxLength"] = hi
|
|
222
|
+
|
|
223
|
+
# Pattern constraint
|
|
224
|
+
pattern_stmt = type_stmt.search_one("pattern")
|
|
225
|
+
if pattern_stmt:
|
|
226
|
+
schema["pattern"] = pattern_stmt.arg
|
|
227
|
+
|
|
228
|
+
return schema
|
|
229
|
+
|
|
230
|
+
def _parse_range(self, range_str: str) -> tuple[int | None, int | None]:
|
|
231
|
+
"""Parse a YANG range/length string like ``'1..100'`` into ``(min, max)``."""
|
|
232
|
+
part = range_str.split("|")[0].strip()
|
|
233
|
+
if ".." in part:
|
|
234
|
+
lo_str, hi_str = part.split("..", 1)
|
|
235
|
+
lo = None if lo_str.strip() in ("min", "") else _to_int(lo_str.strip())
|
|
236
|
+
hi = None if hi_str.strip() in ("max", "") else _to_int(hi_str.strip())
|
|
237
|
+
return lo, hi
|
|
238
|
+
v = _to_int(part)
|
|
239
|
+
return v, v
|