Skip to content

Instantly share code, notes, and snippets.

@aespinosa
Last active September 30, 2022 15:22
Show Gist options
  • Save aespinosa/eacb29d2530ffacc0f2d85fa59a668e5 to your computer and use it in GitHub Desktop.
Save aespinosa/eacb29d2530ffacc0f2d85fa59a668e5 to your computer and use it in GitHub Desktop.
V1CustomResourceDefinition crd = Yaml.loadAs(new File("mycrd.yaml"), V1CustomResourceDefinition.class);
JSON crdSerializer = new JSON();
ObjectMapper oasSerializer = Json.mapper();
OpenAPI openapi = new OpenAPI().components(new Components());
Components components = openapi.getComponents();
for (V1CustomResourceDefinitionVersion version : crd.getSpec().getVersions()) {
V1JSONSchemaProps crdSchema = version.getSchema().getOpenAPIV3Schema();
JsonSchema oasSchema = oasSerializer.readValue(crdSerializer.serialize(crdSchema), JsonSchema.class);
oasSchema.extensions(new HashMap<>())
.addExtension("x-kubernetes-group-version-kind", List.of(Map.of("kind", crd.getSpec().getNames().getKind(), "group", crd.getSpec().getGroup(), "version", version.getName())));
oasSchema.addProperty("kind", new Schema<>().type("string"));
oasSchema.addProperty("apiVersion", new Schema<>().type("string"));
// Add metadata
oasSchema.addProperty("metadata", new JsonSchema().$ref("#/components/schemas/v1.ObjectMeta"));
oasSchema.addExtension("x-implements", "io.kubernetes.client.common.KubernetesObject");
components.addSchemas(version.getName() + "." + crd.getSpec().getNames().getKind(), oasSchema);
JsonSchema list = new JsonSchema();
list.extensions(new HashMap<>())
.addExtension("x-kubernetes-group-version-kind", List.of(Map.of("kind", crd.getSpec().getNames().getListKind(), "group", crd.getSpec().getGroup(), "version", version.getName())));
list.addExtension("x-implements", "io.kubernetes.client.common.KubernetesListObject");
list.addProperty("kind", new Schema<>().type("string"));
list.addProperty("apiVersion", new Schema<>().type("string"));
// Add metadata
list.addProperty("metadata", new JsonSchema().$ref("#/components/schemas/v1.ListMeta"));
list.addProperty("items", new JsonSchema().$ref("#/components/schemas/" + version.getName() + "." + crd.getSpec().getNames().getKind()));
components.addSchemas(version.getName() + "." + crd.getSpec().getNames().getListKind(), oasSchema);
}
System.out.println(oasSerializer.pretty(openapi));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment