Skip to content

Commit d68b122

Browse files
authored
Merge pull request #605 from Jougan-0/namespaceforOpenApi
assign missing namespace w/signoff
2 parents 0777946 + d799564 commit d68b122

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

utils/component/openapi_generator.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"errors"
66
"fmt"
7+
"strings"
78

89
"cuelang.org/go/cue"
910
"cuelang.org/go/cue/cuecontext"
@@ -100,6 +101,26 @@ func GenerateFromOpenAPI(resource string, pkg models.Package) ([]component.Compo
100101
continue
101102
}
102103

104+
// Determine if the resource is namespaced
105+
var isNamespaced bool
106+
107+
scopeCue, err := utils.Lookup(fieldVal, `"x-kubernetes-resource".scope`)
108+
if err == nil {
109+
scope, err := scopeCue.String()
110+
if err == nil {
111+
if scope == "Namespaced" {
112+
isNamespaced = true
113+
} else if scope == "Cluster" {
114+
isNamespaced = false
115+
}
116+
}
117+
} else {
118+
isNamespaced, err = getResourceScope(resource, kind)
119+
if err != nil {
120+
isNamespaced = false
121+
}
122+
}
123+
103124
c := component.ComponentDefinition{
104125
SchemaVersion: v1beta1.ComponentSchemaVersion,
105126
Format: component.JSON,
@@ -109,6 +130,9 @@ func GenerateFromOpenAPI(resource string, pkg models.Package) ([]component.Compo
109130
Schema: string(crd),
110131
},
111132
DisplayName: manifests.FormatToReadableString(kind),
133+
Metadata: component.ComponentDefinition_Metadata{
134+
IsNamespaced: isNamespaced,
135+
},
112136
Model: model.ModelDefinition{
113137
SchemaVersion: v1beta1.ModelSchemaVersion,
114138
Model: model.Model{
@@ -127,7 +151,27 @@ func GenerateFromOpenAPI(resource string, pkg models.Package) ([]component.Compo
127151
components = append(components, c)
128152
}
129153
return components, nil
154+
}
155+
func getResourceScope(manifest string, kind string) (bool, error) {
156+
var m map[string]interface{}
157+
158+
err := yaml.Unmarshal([]byte(manifest), &m)
159+
if err != nil {
160+
return false, utils.ErrDecodeYaml(err)
161+
}
162+
163+
paths, ok := m["paths"].(map[string]interface{})
164+
if !ok {
165+
return false, fmt.Errorf("paths not found in manifest")
166+
}
167+
168+
for path := range paths {
169+
if strings.Contains(path, "/namespaces/{namespace}/") && strings.Contains(path, strings.ToLower(kind)) {
170+
return true, nil // Resource is namespaced
171+
}
172+
}
130173

174+
return false, nil // Resource is cluster-scoped
131175
}
132176

133177
func getResolvedManifest(manifest string) (string, error) {

0 commit comments

Comments
 (0)