|
| 1 | +import os |
| 2 | +from dataclasses import dataclass, field |
| 3 | +from typing import Callable, Any |
| 4 | + |
| 5 | +from ogc.na.annotate_schema import SchemaResolver, ReferencedSchema |
| 6 | + |
| 7 | +from ogc.bblocks.models import BuildingBlock, BuildingBlockRegister |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class SchemaNode: |
| 12 | + tag: str | None |
| 13 | + root: 'SchemaNode | None' = None |
| 14 | + preserve_branch = False |
| 15 | + parent: 'SchemaNode | None' = None |
| 16 | + is_properties: bool = False |
| 17 | + subschema: dict | list | None = None |
| 18 | + children: list['SchemaNode'] = field(default_factory=list) |
| 19 | + |
| 20 | + def mark_preserve_branch(self): |
| 21 | + n = self |
| 22 | + while n is not None: |
| 23 | + if n.preserve_branch: |
| 24 | + break |
| 25 | + n.preserve_branch = True |
| 26 | + n = n.parent |
| 27 | + |
| 28 | + |
| 29 | +def process_extension(bblock: BuildingBlock, register: BuildingBlockRegister, |
| 30 | + parent_id: str, extensions: dict[str, str], |
| 31 | + ref_mapper: Callable[[str, Any], str] | None = None): |
| 32 | + |
| 33 | + schema_resolver = register.schema_resolver |
| 34 | + all_register_files = { |
| 35 | + **register.imported_bblock_files, |
| 36 | + **register.local_bblock_files, |
| 37 | + } |
| 38 | + |
| 39 | + if '#' in parent_id or any('#' in k or '#' in v for k, v in extensions.items()): |
| 40 | + raise ValueError('Extension points can only be declared for building blocks, not for fragments. ' |
| 41 | + 'Please check that your extension point declarations contain no fragment identifiers ("#")') |
| 42 | + |
| 43 | + extension_target_schemas = {} |
| 44 | + for extension_bblock_id in extensions.values(): |
| 45 | + local_bblock = register.bblocks.get(extension_bblock_id) |
| 46 | + if local_bblock: |
| 47 | + if local_bblock.annotated_schema: |
| 48 | + extension_target_schemas[extension_bblock_id] = os.path.relpath( |
| 49 | + local_bblock.annotated_schema.resolve(), |
| 50 | + bblock.annotated_path.resolve() |
| 51 | + ) |
| 52 | + # TODO: OpenAPI? |
| 53 | + else: |
| 54 | + imported_bblock = register.imported_bblocks[extension_bblock_id] |
| 55 | + imported_bblock_schema = imported_bblock.get('schema', {}).get('application/yaml') |
| 56 | + if imported_bblock_schema: |
| 57 | + extension_target_schemas[extension_bblock_id] = imported_bblock_schema |
| 58 | + |
| 59 | + # TODO: OpenAPI? |
| 60 | + |
| 61 | + visited_refs = set() |
| 62 | + schema_branches: list[SchemaNode] = [] |
| 63 | + |
| 64 | + def create_schema_node(parent_node: SchemaNode | None, tag: str, is_properties: bool = False, |
| 65 | + subschema: dict | list | None = None) -> SchemaNode: |
| 66 | + if parent_node is None: |
| 67 | + node = SchemaNode(tag=tag, is_properties=is_properties, subschema=subschema) |
| 68 | + node.root = node |
| 69 | + schema_branches.append(node) |
| 70 | + else: |
| 71 | + node = SchemaNode(root=parent_node.root, parent=parent_node, tag=tag, |
| 72 | + is_properties=is_properties, subschema=subschema) |
| 73 | + parent_node.children.append(node) |
| 74 | + return node |
| 75 | + |
| 76 | + def walk_subschema(subschema, from_schema: ReferencedSchema, parent_node: SchemaNode | None): |
| 77 | + if not subschema or not isinstance(subschema, dict): |
| 78 | + return |
| 79 | + |
| 80 | + if '$ref' in subschema: |
| 81 | + if ref_mapper: |
| 82 | + subschema['$ref'] = ref_mapper(subschema['$ref'], subschema) |
| 83 | + target_schema = schema_resolver.resolve_schema(subschema['$ref'], from_schema) |
| 84 | + |
| 85 | + extension_target: str | None = None |
| 86 | + extension_source: str | None = None |
| 87 | + extension_target_id : str | None = None |
| 88 | + if (target_schema.location in all_register_files |
| 89 | + and all_register_files[target_schema.location] in extensions): |
| 90 | + extension_source = all_register_files[target_schema.location] |
| 91 | + extension_target_id = extensions[extension_source] |
| 92 | + extension_target = extension_target_schemas.get(extension_target_id) |
| 93 | + if not extension_target: |
| 94 | + raise ValueError(f'No schema could be found for extension target {extension_target_id}') |
| 95 | + |
| 96 | + if extension_target: |
| 97 | + ref_node = create_schema_node(parent_node, '$ref') |
| 98 | + ref_node.subschema = { |
| 99 | + '$ref': str(extension_target), |
| 100 | + 'x-bblocks-extension-source': extension_source, |
| 101 | + 'x-bblocks-extension-target': extension_target_id, |
| 102 | + } |
| 103 | + ref_node.mark_preserve_branch() |
| 104 | + return |
| 105 | + else: |
| 106 | + # Avoid infinite loops |
| 107 | + target_schema_full_ref = (f"{target_schema.location}#{target_schema.fragment}" |
| 108 | + if target_schema.fragment |
| 109 | + else target_schema.location) |
| 110 | + if target_schema_full_ref in visited_refs: |
| 111 | + return |
| 112 | + visited_refs.add(target_schema_full_ref) |
| 113 | + |
| 114 | + if target_schema: |
| 115 | + walk_subschema(target_schema.subschema, target_schema, parent_node) |
| 116 | + |
| 117 | + for p in ('oneOf', 'allOf', 'anyOf'): |
| 118 | + collection = subschema.get(p) |
| 119 | + if collection and isinstance(collection, list): |
| 120 | + col_node = (create_schema_node(parent_node, p, subschema=collection) |
| 121 | + if p != 'allOf' else parent_node) |
| 122 | + for entry in collection: |
| 123 | + walk_subschema(entry, from_schema, col_node) |
| 124 | + |
| 125 | + for i in ('prefixItems', 'items', 'contains', 'then', 'else', 'additionalProperties'): |
| 126 | + l = subschema.get(i) |
| 127 | + if isinstance(l, dict): |
| 128 | + entry_node = create_schema_node(parent_node, i, subschema=l) |
| 129 | + walk_subschema(l, from_schema, entry_node) |
| 130 | + |
| 131 | + if 'properties' in subschema: |
| 132 | + properties_node = create_schema_node(parent_node, tag='properties') |
| 133 | + for prop_name, prop_schema in subschema['properties'].items(): |
| 134 | + prop_node = create_schema_node(parent_node=properties_node, tag=prop_name, |
| 135 | + is_properties=True, subschema=prop_schema) |
| 136 | + walk_subschema(prop_schema, from_schema, prop_node) |
| 137 | + |
| 138 | + pattern_properties = subschema.get('patternProperties') |
| 139 | + if pattern_properties: |
| 140 | + pps_node = create_schema_node(parent_node, tag='patternProperties') |
| 141 | + for pp_k, pp in pattern_properties.items(): |
| 142 | + if isinstance(pp, dict): |
| 143 | + pp_node = create_schema_node(pps_node, pp_k, is_properties=True) |
| 144 | + walk_subschema(pp, from_schema, pp_node) |
| 145 | + |
| 146 | + parent_bblock = register.bblocks.get(parent_id) |
| 147 | + if parent_bblock: |
| 148 | + root_schema = schema_resolver.resolve_schema(parent_bblock.annotated_schema) |
| 149 | + else: |
| 150 | + imp_bblock = register.imported_bblocks.get(parent_id) |
| 151 | + if not imp_bblock: |
| 152 | + raise ValueError(f"Could not find building block with id {parent_id} in register or imports.") |
| 153 | + bblock_schemas = imp_bblock.get('schema', {}) |
| 154 | + bblock_schema = bblock_schemas.get('application/yaml', bblock_schemas.get('application/json')) |
| 155 | + # TODO: OpenAPI? |
| 156 | + if not bblock_schema: |
| 157 | + raise ValueError(f"Could not find schema for building block with id {parent_id}" |
| 158 | + f" in register or imports.") |
| 159 | + root_schema = schema_resolver.resolve_schema(bblock_schema) |
| 160 | + |
| 161 | + walk_subschema(root_schema.full_contents, root_schema, None) |
| 162 | + |
| 163 | + output_schema = { |
| 164 | + '$schema': 'https://json-schema.org/draft/2020-12/schema', |
| 165 | + 'x-bblocks-extends': parent_id, |
| 166 | + 'x-bblocks-extensions': extensions, |
| 167 | + 'allOf': [], |
| 168 | + } |
| 169 | + for branch in schema_branches: |
| 170 | + if not branch.preserve_branch: |
| 171 | + continue |
| 172 | + |
| 173 | + def walk_branch(node: SchemaNode, parent_schema: dict, force_preserve_branch: bool = False): |
| 174 | + if not force_preserve_branch and not node.preserve_branch: |
| 175 | + return |
| 176 | + if node.tag == '$ref' and node.subschema: |
| 177 | + parent_schema.setdefault('allOf', []).append(node.subschema) |
| 178 | + elif node.tag in ('oneOf', 'anyOf', 'allOf'): |
| 179 | + col_schema = parent_schema.setdefault(node.tag, []) |
| 180 | + for child in node.children: |
| 181 | + child_schema = {} |
| 182 | + col_schema.append(child_schema) |
| 183 | + walk_branch(child, child_schema, force_preserve_branch=node.tag in ('oneOf', 'anyOf')) |
| 184 | + else: |
| 185 | + if not node.children: |
| 186 | + # End of the line, we append the full subschema |
| 187 | + parent_schema[node.tag] = node.subschema |
| 188 | + else: |
| 189 | + parent_schema[node.tag] = {} |
| 190 | + for child in node.children: |
| 191 | + walk_branch(child, parent_schema[node.tag], force_preserve_branch=force_preserve_branch) |
| 192 | + |
| 193 | + branch_entry = {} |
| 194 | + output_schema['allOf'].append(branch_entry) |
| 195 | + walk_branch(branch, branch_entry) |
| 196 | + |
| 197 | + return output_schema |
0 commit comments