1/*
2Copyright 2018 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package openapi
18
19import (
20	"encoding/json"
21
22	"github.com/go-openapi/spec"
23	"github.com/googleapis/gnostic/compiler"
24	openapi_v2 "github.com/googleapis/gnostic/openapiv2"
25	yaml "gopkg.in/yaml.v2"
26
27	"k8s.io/kube-openapi/pkg/util/proto"
28)
29
30// ToProtoModels builds the proto formatted models from OpenAPI spec
31func ToProtoModels(openAPISpec *spec.Swagger) (proto.Models, error) {
32	specBytes, err := json.MarshalIndent(openAPISpec, " ", " ")
33	if err != nil {
34		return nil, err
35	}
36
37	var info yaml.MapSlice
38	err = yaml.Unmarshal(specBytes, &info)
39	if err != nil {
40		return nil, err
41	}
42
43	doc, err := openapi_v2.NewDocument(info, compiler.NewContext("$root", nil))
44	if err != nil {
45		return nil, err
46	}
47
48	models, err := proto.NewOpenAPIData(doc)
49	if err != nil {
50		return nil, err
51	}
52
53	return models, nil
54}
55