|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# VulnerableCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. |
| 6 | +# See https://github.com/nexB/vulnerablecode for support or download. |
| 7 | +# See https://aboutcode.org for more information about nexB OSS projects. |
| 8 | +# |
| 9 | + |
| 10 | +import json |
| 11 | + |
| 12 | +from django.core.management.base import BaseCommand |
| 13 | +from pydantic.json_schema import GenerateJsonSchema |
| 14 | + |
| 15 | +from fedcode import schemas |
| 16 | + |
| 17 | + |
| 18 | +class GenerateFederatedCodeJsonSchema(GenerateJsonSchema): |
| 19 | + def generate(self, schema, mode="validation"): |
| 20 | + json_schema = super().generate(schema, mode=mode) |
| 21 | + json_schema["$schema"] = self.schema_dialect |
| 22 | + return json_schema |
| 23 | + |
| 24 | + |
| 25 | +def get_ordered_schema(schema, schema_path): |
| 26 | + schema["$id"] = f"https://raw.githubusercontent.com/nexB/federatedcode/main/{schema_path}" |
| 27 | + desired_order = [ |
| 28 | + "$schema", |
| 29 | + "$id", |
| 30 | + "title", |
| 31 | + "type", |
| 32 | + ] |
| 33 | + |
| 34 | + ordered_schema = {key: schema[key] for key in desired_order} |
| 35 | + ordered_schema.update({key: schema[key] for key in schema if key not in desired_order}) |
| 36 | + return ordered_schema |
| 37 | + |
| 38 | + |
| 39 | +def gen_schema(model_schema, path): |
| 40 | + schema = model_schema.model_json_schema(schema_generator=GenerateFederatedCodeJsonSchema) |
| 41 | + ordered_schema = get_ordered_schema(schema=schema, schema_path=path) |
| 42 | + with open(path, "w", encoding="utf-8") as f: |
| 43 | + json.dump(ordered_schema, f, indent=2) |
| 44 | + |
| 45 | + |
| 46 | +class Command(BaseCommand): |
| 47 | + def handle(self, *args, **options): |
| 48 | + gen_schema( |
| 49 | + model_schema=schemas.Vulnerability, |
| 50 | + path="schemas/vulnerability.schema.json", |
| 51 | + ) |
| 52 | + gen_schema( |
| 53 | + model_schema=schemas.Package, |
| 54 | + path="schemas/package.schema.json", |
| 55 | + ) |
0 commit comments