Skip to content

Commit

Permalink
Implement scripts to generate the schema / example ... move scripts t…
Browse files Browse the repository at this point in the history
…o version specific source_build directory #143
  • Loading branch information
jh-RLI committed Jun 5, 2024
1 parent aca7f3c commit 2901b7c
Show file tree
Hide file tree
Showing 4 changed files with 132 additions and 108 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Title: create example from json schema
Description: Create example from json schema.
Author: jh-RLI
Email: [email protected]
Date: 2024-05-30
Version: 1.0.0
"""

# Standard Library Imports
# import os
from os.path import dirname

import sys
import json
import logging

# from datetime import datetime
from pathlib import Path

from jsonschema import validate, ValidationError

# Configuration
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
logger = logging.getLogger(__name__)

# Constants
BASE_PATH = Path("metadata/")
VERSION = "v200_draft"
VERSION_PATH = BASE_PATH / VERSION
SCHEMA_BUILD_PATH = VERSION_PATH / "build_source"
MAIN_SCHEMA_PATH = SCHEMA_BUILD_PATH / "schema_structure.json"
SCHEMA_REFS = SCHEMA_BUILD_PATH / "schemas"
RESOLVED_SCHEMA_FILE_NAME = VERSION_PATH / "res_schema.json"
EXPECTED_SCHEMA_PATH = VERSION_PATH / "schema.json"
EXAMPLE_PATH = VERSION_PATH / "resolved_example.json"


def generate_example(schema):
if isinstance(schema, bool):
return {} if schema else None

if "type" not in schema and "properties" not in schema and "items" not in schema:
return None

schema_type = schema.get("type")

if isinstance(schema_type, list):
schema_type = schema_type[0]

if "example" in schema:
example = schema["example"]
# Convert example string to actual type if necessary
if schema_type == "array" and isinstance(example, str):
try:
example = json.loads(example.replace("'", '"'))
except json.JSONDecodeError:
pass
return example

if schema_type == "object" or "properties" in schema:
example = {}
properties = schema.get("properties", {})
for prop, prop_schema in properties.items():
example[prop] = generate_example(prop_schema)
additional_properties = schema.get("additionalProperties", True)
if isinstance(additional_properties, dict):
example["additional_property"] = generate_example(additional_properties)
return example

if schema_type == "array":
item_schema = schema.get("items", {})
return [generate_example(item_schema)]

if schema_type == "string":
return ""

if schema_type == "number":
return 0

if schema_type == "integer":
return 0

if schema_type == "boolean":
return False

return None


def main():
schema_file_path = RESOLVED_SCHEMA_FILE_NAME

with open(schema_file_path, "r", encoding="utf-8") as schema_file:
schema = json.load(schema_file)

example = generate_example(schema)

example_file_path = EXAMPLE_PATH
with open(example_file_path, "w", encoding="utf-8") as example_file:
json.dump(example, example_file, indent=2, ensure_ascii=False)

print(f"Example JSON generated and saved to {example_file_path}")


if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@
BASE_PATH = Path("metadata/")
VERSION = "v200_draft"
VERSION_PATH = BASE_PATH / VERSION
SCHEMA_BUILD_PATH = VERSION_PATH / "build"
MAIN_SCHEMA_PATH = SCHEMA_BUILD_PATH / "main_schema.json"
SCHEMA_BUILD_PATH = VERSION_PATH / "build_source"
MAIN_SCHEMA_PATH = SCHEMA_BUILD_PATH / "schema_structure.json"
SCHEMA_REFS = SCHEMA_BUILD_PATH / "schemas"
RESOLVED_SCHEMA_FILE_NAME = VERSION_PATH / "res_schema.json"
RESOLVED_SCHEMA_FILE_NAME = VERSION_PATH / "schema.json"
EXPECTED_SCHEMA_PATH = VERSION_PATH / "schema.json"


Expand All @@ -55,7 +55,7 @@ def setup():

# Load the main schema
def load_schema(schema_path):
with open(schema_path, "r") as file:
with open(schema_path, "r", encoding="utf-8") as file:
return json.load(file)


Expand Down Expand Up @@ -112,7 +112,9 @@ def resolve_references(schema, registry, base_uri):
print(
f"Resolved reference {ref_uri} to {ref_schema.contents}"
) # Debugging
return resolve_references(ref_schema.contents, registry, base_uri)
return ref_schema.contents[
"properties"
] # Return only the properties
except KeyError as e:
raise ValueError(f"Reference {ref_uri} could not be resolved: {e}")
else:
Expand All @@ -125,16 +127,20 @@ def resolve_references(schema, registry, base_uri):
return schema

# Resolve the top-level properties
resolved_properties = {}
for prop, value in schema["properties"].items():
if "$ref" in value:
resolved_value = resolve_references(value, registry, base_uri)
resolved_properties.update(resolved_value["properties"])
else:
resolved_properties[prop] = resolve_references(value, registry, base_uri)

# Replace the properties in the schema with the resolved properties
schema["properties"] = resolved_properties
def resolve_top_level_properties(schema, registry, base_uri):
resolved_properties = {}
for prop, value in schema["properties"].items():
if isinstance(value, dict) and "properties" in value:
resolved_value = resolve_references(
value["properties"], registry, base_uri
)
resolved_properties[prop] = resolved_value
else:
resolved_value = resolve_references(value, registry, base_uri)
resolved_properties[prop] = resolved_value
return resolved_properties

schema["properties"] = resolve_top_level_properties(schema, registry, base_uri)
return schema


Expand Down Expand Up @@ -164,7 +170,7 @@ def main(debug):
resolved_schema = resolve_and_merge(MAIN_SCHEMA_PATH, debug)

# Save the resolved schema to a new file
with open(RESOLVED_SCHEMA_FILE_NAME, "w") as output_file:
with open(RESOLVED_SCHEMA_FILE_NAME, "w", encoding="utf-8") as output_file:
json.dump(resolved_schema, output_file, indent=2)

# Load the expected schema and validate
Expand Down
92 changes: 0 additions & 92 deletions scripts/generate_example_from_schema.py

This file was deleted.

0 comments on commit 2901b7c

Please sign in to comment.