-
Notifications
You must be signed in to change notification settings - Fork 127
/
merge.go
81 lines (72 loc) · 2.59 KB
/
merge.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package builder
import (
"github.com/go-openapi/spec"
"k8s.io/kube-openapi/pkg/aggregator"
)
// MergeSpecs aggregates all OpenAPI specs, reusing the metadata of the first, static spec as the basis.
// The static spec has the highest priority, and its paths and definitions won't get overlapped by
// user-defined CRDs. None of the input is mutated, but input and output share data structures.
func MergeSpecs(staticSpec *spec.Swagger, crdSpecs ...*spec.Swagger) (*spec.Swagger, error) {
// create shallow copy of staticSpec, but replace paths and definitions because we modify them.
specToReturn := *staticSpec
if staticSpec.Definitions != nil {
specToReturn.Definitions = spec.Definitions{}
for k, s := range staticSpec.Definitions {
specToReturn.Definitions[k] = s
}
}
if staticSpec.Paths != nil {
specToReturn.Paths = &spec.Paths{
Paths: map[string]spec.PathItem{},
}
for k, p := range staticSpec.Paths.Paths {
specToReturn.Paths.Paths[k] = p
}
}
crdSpec := &spec.Swagger{}
for _, s := range crdSpecs {
// merge specs without checking conflicts, since the naming controller prevents
// conflicts between user-defined CRDs
mergeSpec(crdSpec, s)
}
// The static spec has the highest priority. Resolve conflicts to prevent user-defined
// CRDs potentially overlapping the built-in apiextensions API
if err := aggregator.MergeSpecsIgnorePathConflict(&specToReturn, crdSpec); err != nil {
return nil, err
}
return &specToReturn, nil
}
// mergeSpec copies paths and definitions from source to dest, mutating dest, but not source.
// We assume that conflicts do not matter.
func mergeSpec(dest, source *spec.Swagger) {
if source == nil || source.Paths == nil {
return
}
if dest.Paths == nil {
dest.Paths = &spec.Paths{}
}
for k, v := range source.Definitions {
if dest.Definitions == nil {
dest.Definitions = spec.Definitions{}
}
dest.Definitions[k] = v
}
for k, v := range source.Paths.Paths {
if dest.Paths.Paths == nil {
dest.Paths.Paths = map[string]spec.PathItem{}
}
dest.Paths.Paths[k] = v
}
}