Skip to content

Commit

Permalink
refactor: use the RestMapper for the gvr lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
gitolicious committed Apr 22, 2024
1 parent c51e67f commit 1c1a9a6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 26 deletions.
2 changes: 1 addition & 1 deletion internal/dao/generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func (g *Generic) GetOwners(path string) ([]OwnerInfo, error) {
var owners []OwnerInfo

for _, ownerRef := range u.GetOwnerReferences() {
gvr, namespaced, err := GVRForKind(ownerRef.APIVersion, ownerRef.Kind)
gvr, namespaced, err := GVRForKind(g.Client(), ownerRef.APIVersion, ownerRef.Kind)
if err != nil {
return nil, err
}
Expand Down
52 changes: 27 additions & 25 deletions internal/dao/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ package dao

import (
"fmt"
"k8s.io/apimachinery/pkg/runtime/schema"
"path"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -101,37 +103,37 @@ func AccessorFor(f Factory, gvr client.GVR) (Accessor, error) {
return r, nil
}

type gvrInfo struct {
gvr client.GVR
namespaced bool
}
// GVRForKind returns the client.GVR corresponding to a kind.
func GVRForKind(c client.Connection, apiVersion string, kind string) (client.GVR, bool, error) {
mapper := RestMapper{Connection: c}

var gvrs = map[string]map[string]gvrInfo{
"apps/v1": {
"ReplicaSet": {client.NewGVR("apps/v1/replicasets"), true},
"DaemonSet": {client.NewGVR("apps/v1/daemonsets"), true},
"StatefulSet": {client.NewGVR("apps/v1/statefulsets"), true},
"Deployment": {client.NewGVR("apps/v1/deployments"), true},
"Jobs": {client.NewGVR("apps/v1/jobs"), true},
"CronJobs": {client.NewGVR("apps/v1/cronjobs"), true},
},
"v1": {
"Node": {client.NewGVR("v1/nodes"), false},
},
}
m, err := mapper.ToRESTMapper()
if err != nil {
return client.GVR{}, false, err
}

var g, v string

func GVRForKind(apiVersion string, kind string) (client.GVR, bool, error) {
_, found := gvrs[apiVersion]
if !found {
return client.GVR{}, false, fmt.Errorf("unsupported ownerReference API version: %s", apiVersion)
if strings.Contains(apiVersion, "/") {
parts := strings.Split(apiVersion, "/")
g, v = parts[0], parts[1]
} else {
v = apiVersion
}

gvr, found := gvrs[apiVersion][kind]
if !found {
return client.GVR{}, false, fmt.Errorf("unsupported ownerReference kind: %s", kind)
rm, err := m.RESTMapping(schema.GroupKind{Group: g, Kind: kind}, v)
if err != nil {
return client.GVR{}, false, err
}

gvr := client.NewGVR(path.Join(rm.Resource.Group, rm.Resource.Version, rm.Resource.Resource))

meta, err := MetaAccess.MetaFor(gvr)
if err != nil {
return client.GVR{}, false, err
}

return gvr.gvr, gvr.namespaced, nil
return gvr, meta.Namespaced, nil
}

// RegisterMeta registers a new resource meta object.
Expand Down

0 comments on commit 1c1a9a6

Please sign in to comment.