ronantakizawa/codereview-bench huggingface dataset:
Repository: etcd-io/etcd
File: cache/store_test.go (Go)

Code before:
//
// 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 cache

import (
	"errors"
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"

	mvccpb "go.etcd.io/etcd/api/v3/mvccpb"
	clientv3 "go.etcd.io/etcd/client/v3"
)

func TestStoreGet(t *testing.T) {
	tests := []struct {
		name       string
		initialKVs []*mvccpb.KeyValue
		initialRev int64

		start []byte
		end   []byte

		expectedKVs []*mvccpb.KeyValue
		expectedRev int64
		expectedErr error
	}{
		{
			name:        "empty_store_returns_ErrNotReady",
			initialKVs:  nil,
			start:       []byte("a"),
			expectedErr: ErrNotReady,
		},
		{
			name:        "Get_single_key_hit",
			initialKVs:  []*mvccpb.KeyValue{makeKV("/b", "2", 5), makeKV("/a", "1", 5), makeKV("/c", "3", 5)},
			initialRev:  5,

Review comment (suggestion):
Thanks for extensive tests, however I would recommend to send them in separate PR that we merge first. This way we know that both previous and the current implementation passes them.

Code after:
//
// 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 cache

import (
	"errors"
	"testing"

	"github.com/google/go-cmp/cmp"

	mvccpb "go.etcd.io/etcd/api/v3/mvccpb"
	clientv3 "go.etcd.io/etcd/client/v3"
)

func TestStoreGet(t *testing.T) {
	tests := []struct {
		name       string
		initialKVs []*mvccpb.KeyValue
		initialRev int64

		start []byte
		end   []byte

		expectedKVs []*mvccpb.KeyValue
		expectedRev int64
		expectedErr error
	}{
		{
			name:        "empty_store_returns_ErrNotReady",
			initialKVs:  nil,
			start:       []byte("a"),
			expectedErr: ErrNotReady,
		},
		{
			name:        "Get_single_key_hit",
			initialKVs:  []*mvccpb.KeyValue{makeKV("/b", "2", 5), makeKV("/a", "1", 5), makeKV("/c", "3", 5)},
			initialRev:  5,
			start:       []byte("/b"),
			expectedKVs: []*mvccpb.KeyValue{makeKV("/b", "2", 5)},
			expectedRev: 5,
Repository: etcd-io/etcd
File: tests/robustness/coverage/coverage_test.go (Go)

Code before:
}

func printableCallTable(callsByOperationName map[string]int) string {
	buf := new(bytes.Buffer)
	cfgBuilder := tablewriter.NewConfigBuilder().WithRowAlignment(tw.AlignRight)
	table := tablewriter.NewTable(buf, tablewriter.WithConfig(cfgBuilder.Build()))
	table.Header("method", "calls", "percent")

	totalCalls := 0
	for _, c := range callsByOperationName {
		totalCalls += c
	}

	for opName, callCount := range callsByOperationName {
		table.Append(opName, callCount, fmt.Sprintf("%.2f%%", float64(callCount*100)/float64(totalCalls)))
	}
	table.Footer("total", totalCalls, "100.00%")

	table.Render()
	return buf.String()
}

func printableMatcherTable(cols []column, res map[row]int) string {
	keys := slices.Collect(maps.Keys(res))
	slices.SortFunc(keys, func(a, b row) int {
		if ca, cb := strings.Count(a.pattern, "/"), strings.Count(b.pattern, "/"); ca != cb {
			return ca - cb
		}
		if a.pattern != b.pattern {
			return strings.Compare(a.pattern, b.pattern)
		}
		if a.method != b.method {
			return strings.Compare(a.method, b.method)
		}
		return strings.Compare(a.args, b.args)
	})

	buf := new(bytes.Buffer)
	width := 2 + len(cols) + 2
	alignment := make([]tw.Align, width)
	alignment[1] = tw.AlignLeft
	cfgBuilder := tablewriter.NewConfigBuilder().
		WithRowAlignment(tw.AlignRight).
		Row().Alignment().WithPerColumn(alignment).Build()
	table := tablewriter.NewTable(buf, tablewriter.WithConfig(cfgBuilder.Build()))

	hdr := make([]string, width)
	hdr[0] = "method"
	hdr[1] = "pattern"
	for i, col := range cols {
		hdr[i+2] = col.name

Review comment (suggestion):
Nit, `/registry/{resource}/{namespace}/{name}/` should be before `/registry/{api-group}/{resource}/{namespace}/{name}`, but it's not because it has same number of "/" and `{api-group}` < `{resource}`.

Code after:

	table.Render()
	return buf.String()
}

func printableMatcherTable(cols []column, res map[row]int) string {
	keys := slices.Collect(maps.Keys(res))
	slices.SortFunc(keys, func(a, b row) int {
		if a.pattern != b.pattern {
			return strings.Compare(a.pattern, b.pattern)
		}
		if a.method != b.method {
			return strings.Compare(a.method, b.method)
		}
		return strings.Compare(a.args, b.args)
	})

	buf := new(bytes.Buffer)
	width := 2 + len(cols) + 2
	alignment := make([]tw.Align, width)
	alignment[1] = tw.AlignLeft
	cfgBuilder := tablewriter.NewConfigBuilder().
		WithRowAlignment(tw.AlignRight).
		Row().Alignment().WithPerColumn(alignment).Build()
	table := tablewriter.NewTable(buf, tablewriter.WithConfig(cfgBuilder.Build()))

	hdr := make([]string, width)
	hdr[0] = "method"
	hdr[1] = "pattern"
	for i, col := range cols {
		hdr[i+2] = col.name
	}
	hdr[len(hdr)-2] = "calls"
	hdr[len(hdr)-1] = "percent"
	table.Header(hdr)

	totalCalls := 0
	for _, c := range res {
		totalCalls += c
	}

	footer := make([]int, len(cols))
	for _, r := range keys {
		callCount := res[r]
		rowPrefix := make([]string, len(cols))
		for i := range cols {
			rowPrefix[i] = string(r.args[i])
			if r.args[i] != notMatched {
				footer[i] += callCount
			}
		}
Repository: etcd-io/etcd
File: tests/robustness/coverage/coverage_test.go (Go)

Code before:

	resource := "{resource}"
	if strings.HasPrefix(k, "/registry/events") {
		resource = "events"
	}

	switch strings.Count(k, "/") {
	case 1:
		return "/registry" + suffix, true
	case 2:
		return "/registry/" + resource + suffix, true
	case 3:
		return "/registry/" + resource + "/{namespace}" + suffix, true
	case 4:
		return "/registry/" + resource + "/{namespace}/{name}" + suffix, true
	case 5:
		return "/registry/{api-group}/{resource}/{namespace}/{name}" + suffix, true
	}
	return k, false
}

func columnsToArgs(span *tracev1.Span, cols []column) string {
	acc := make([]byte, len(cols))
	for i, col := range cols {
		if col.matcher(span) {
			acc[i] = 'X'
		} else {
			acc[i] = notMatched
		}
	}
	return string(acc)
}

func argsToDescription(matched string, cols []column) string {
	ret := make([]string, len(cols))
	for i, col := range cols {
		ret[i] = fmt.Sprintf("%s=%v", col.name, matched[i] != notMatched)
	}
	return strings.Join(ret, ",")
}

func extractMethod(methodToMatched []method, span *tracev1.Span) (string, bool) {
	for _, mm := range methodToMatched {
		if mm.matcher(span) {
			return mm.name, true
		}
	}
	return "", false
}

type Traces struct {

Review comment (performance):
Can you leave a comment that `events` are special as that's the only resource that has watch cache disabled by default?

Code after:
	}
	return k, false
}

func columnsToArgs(span *tracev1.Span, cols []column) string {
	acc := make([]byte, len(cols))
	for i, col := range cols {
		if col.matcher(span) {
			acc[i] = 'X'
		} else {
			acc[i] = notMatched
		}
	}
	return string(acc)
}

func argsToDescription(matched string, cols []column) string {
	ret := make([]string, len(cols))
	for i, col := range cols {
		ret[i] = fmt.Sprintf("%s=%v", col.name, matched[i] != notMatched)
	}
	return strings.Join(ret, ",")
}

func extractMethod(methodToMatched []method, span *tracev1.Span) (string, bool) {
	for _, mm := range methodToMatched {
		if mm.matcher(span) {
			return mm.name, true
		}
	}
	return "", false
}

type Traces struct {
	traceservice.ExportTraceServiceRequest
}

func (t *Traces) UnmarshalJSON(b []byte) error {
	return protojson.Unmarshal(b, &t.ExportTraceServiceRequest)
}

type Dump struct {
	Result *Traces `json:"result"`
}

func printableCallTable(callsByOperationName map[string]int) string {
	buf := new(bytes.Buffer)
	cfgBuilder := tablewriter.NewConfigBuilder().WithRowAlignment(tw.AlignRight)
	table := tablewriter.NewTable(buf, tablewriter.WithConfig(cfgBuilder.Build()))
	table.Header("method", "calls", "percent")
Repository: etcd-io/etcd
File: tests/robustness/coverage/key_pattern_test.go (Go)

Code before:
			want: "compact_rev_key",
		},
		{
			name: "special_healthcheck",
			key:  "/registry/health",
			want: "/registry/health",
		},
		{
			name: "core_namespace_get",
			key:  "/registry/controllerrevisions/kube-system/kube-proxy-5884f58745",
			want: "/registry/{resource}/{namespace}/{name}",
		},
		{
			name: "core_namespace_list",
			key:  "/registry/controllerrevisions/kube-system/",
			want: "/registry/{resource}/{namespace}/",
		},
		{
			name: "core_subresource_namespace_get",
			key:  "/registry/services/specs/default/kubernetes",
			want: "/registry/{resource}/{namespace}/{name}",
		},
		{
			name: "core_subresource_rev",
			key:  "/registry/services/endpoints",
			want: "/registry/{resource}",
		},
		{
			name: "core_subresource_namespace_list",
			key:  "/registry/services/specs/default/",
			want: "/registry/{resource}/{namespace}/",
		},
		{
			name: "core_no_namespace_get",
			key:  "/registry/priorityclasses/system-node-critical",
			want: "/registry/{resource}/{name}",
		},
		{
			name: "core_no_namespace_rev",
			key:  "/registry/priorityclasses",
			want: "/registry/{resource}",
		},
		{
			name: "core_no_namespace_list",
			key:  "/registry/priorityclasses/",
			want: "/registry/{resource}/",
		},
		{
			name: "crd_namespace_get",
			key:  "/registry/cilium.io/ciliumendpoints/kube-system/kube-dns",
			want: "/registry/{api-group}/{resource}/{namespace}/{name}",

Review comment (suggestion):
```suggestion
			want: "/registry/{resource}/{subresource}",
```

Code after:
		key  string
		want string
	}{
		{
			key:  "compact_rev_key",
			want: "compact_rev_key",
		},
		{
			key:  "/registry/health",
			want: "/registry/health",
		},
		{
			key:  "/registry/resource/namespace/object",
			want: "/registry/{resource}/{namespace}/{name}",
		},
		{
			key:  "/registry/resource/namespace_list/",
			want: "/registry/{resource}/{namespace}/",
		},
		{
			key:  "/registry/services/specs/namespace/object",
			want: "/registry/services/{subresource}/{namespace}/{name}",
		},
		{
			key:  "/registry/services/endpoints",
			want: "/registry/services/{subresource}",
		},
		{
			key:  "/registry/services/specs/namespace_list/",
			want: "/registry/services/{subresource}/{namespace}/",
		},
		{
			key:  "/registry/resource/object_get",
			want: "/registry/{resource}/{name}",
		},
		{
			key:  "/registry/resource_rev",
			want: "/registry/{resource}",
		},
		{
			key:  "/registry/resource_list/",
			want: "/registry/{resource}/",
		},
		{
			key:  "/registry/crd.io/resource/namespace/object_get",
			want: "/registry/{api-group}/{resource}/{namespace}/{name}",
		},
		{
			key:  "/registry/crd.io/resource/namespace_list/",
			want: "/registry/{api-group}/{resource}/{namespace}/",
		},
Repository: etcd-io/etcd
File: tests/robustness/coverage/key_pattern_test.go (Go)

Code before:
			want: "/registry/health",
		},
		{
			name: "core_namespace_get",
			key:  "/registry/controllerrevisions/kube-system/kube-proxy-5884f58745",
			want: "/registry/{resource}/{namespace}/{name}",
		},
		{
			name: "core_namespace_list",
			key:  "/registry/controllerrevisions/kube-system/",
			want: "/registry/{resource}/{namespace}/",
		},
		{
			name: "core_subresource_namespace_get",
			key:  "/registry/services/specs/default/kubernetes",
			want: "/registry/{resource}/{namespace}/{name}",
		},
		{
			name: "core_subresource_rev",
			key:  "/registry/services/endpoints",
			want: "/registry/{resource}",
		},
		{
			name: "core_subresource_namespace_list",
			key:  "/registry/services/specs/default/",
			want: "/registry/{resource}/{namespace}/",
		},
		{
			name: "core_no_namespace_get",
			key:  "/registry/priorityclasses/system-node-critical",
			want: "/registry/{resource}/{name}",
		},
		{
			name: "core_no_namespace_rev",
			key:  "/registry/priorityclasses",
			want: "/registry/{resource}",
		},
		{
			name: "core_no_namespace_list",
			key:  "/registry/priorityclasses/",
			want: "/registry/{resource}/",
		},
		{
			name: "crd_namespace_get",
			key:  "/registry/cilium.io/ciliumendpoints/kube-system/kube-dns",
			want: "/registry/{api-group}/{resource}/{namespace}/{name}",
		},
		{
			name: "crd_namespace_list",
			key:  "/registry/cilium.io/ciliumendpoints/kube-system/",
			want: "/registry/{api-group}/{resource}/{namespace}/",

Review comment (suggestion):
```suggestion
			want: "/registry/{resource}/{subresource}/{namespace}/",
```

Code after:
			want: "compact_rev_key",
		},
		{
			key:  "/registry/health",
			want: "/registry/health",
		},
		{
			key:  "/registry/resource/namespace/object",
			want: "/registry/{resource}/{namespace}/{name}",
		},
		{
			key:  "/registry/resource/namespace_list/",
			want: "/registry/{resource}/{namespace}/",
		},
		{
			key:  "/registry/services/specs/namespace/object",
			want: "/registry/services/{subresource}/{namespace}/{name}",
		},
		{
			key:  "/registry/services/endpoints",
			want: "/registry/services/{subresource}",
		},
		{
			key:  "/registry/services/specs/namespace_list/",
			want: "/registry/services/{subresource}/{namespace}/",
		},
		{
			key:  "/registry/resource/object_get",
			want: "/registry/{resource}/{name}",
		},
		{
			key:  "/registry/resource_rev",
			want: "/registry/{resource}",
		},
		{
			key:  "/registry/resource_list/",
			want: "/registry/{resource}/",
		},
		{
			key:  "/registry/crd.io/resource/namespace/object_get",
			want: "/registry/{api-group}/{resource}/{namespace}/{name}",
		},
		{
			key:  "/registry/crd.io/resource/namespace_list/",
			want: "/registry/{api-group}/{resource}/{namespace}/",
		},
		{
			key:  "/registry/crd.io/resource/object_get",
			want: "/registry/{api-group}/{resource}/{name}",
		},
		{
Repository: etcd-io/etcd
File: tests/robustness/coverage/key_pattern_test.go (Go)

Code before:
			name: "core_subresource_rev",
			key:  "/registry/services/endpoints",
			want: "/registry/services/{subresource}",
		},
		{
			name: "core_subresource_namespace_list",
			key:  "/registry/services/specs/default/",
			want: "/registry/services/{subresource}/{namespace}/",
		},
		{
			name: "core_no_namespace_get",
			key:  "/registry/priorityclasses/system-node-critical",
			want: "/registry/{resource}/{name}",
		},
		{
			name: "core_no_namespace_rev",
			key:  "/registry/priorityclasses",
			want: "/registry/{resource}",
		},
		{
			name: "core_no_namespace_list",
			key:  "/registry/priorityclasses/",
			want: "/registry/{resource}/",
		},
		{
			name: "crd_namespace_get",
			key:  "/registry/cilium.io/ciliumendpoints/kube-system/kube-dns",
			want: "/registry/{api-group}/{resource}/{namespace}/{name}",
		},
		{
			name: "crd_namespace_list",
			key:  "/registry/cilium.io/ciliumendpoints/kube-system/",
			want: "/registry/{api-group}/{resource}/{namespace}/",
		},
		{
			name: "crd_no_namespace_get",
			key:  "/registry/apiregistration.k8s.io/apiservices/v1alpha1.storage.k8s.io",
			want: "/registry/{api-group}/{resource}/{name}",
		},
		{
			name: "crd_no_namespace_rev",
			key:  "/registry/apiregistration.k8s.io/apiservices",
			want: "/registry/{api-group}/{resource}",
		},
		{
			name: "crd_no_namespace_list",
			key:  "/registry/apiregistration.k8s.io/apiservices/",
			want: "/registry/{api-group}/{resource}/",
		},
	} {
		t.Run(tc.name, func(t *testing.T) {

Review comment (suggestion):
There are non-core API that follow this pattern and are not CRDs. Like `apps` with `Deployment` resource.

Code after:
		{
			key:  "/registry/services/endpoints",
			want: "/registry/services/{subresource}",
		},
		{
			key:  "/registry/services/specs/namespace_list/",
			want: "/registry/services/{subresource}/{namespace}/",
		},
		{
			key:  "/registry/resource/object_get",
			want: "/registry/{resource}/{name}",
		},
		{
			key:  "/registry/resource_rev",
			want: "/registry/{resource}",
		},
		{
			key:  "/registry/resource_list/",
			want: "/registry/{resource}/",
		},
		{
			key:  "/registry/crd.io/resource/namespace/object_get",
			want: "/registry/{api-group}/{resource}/{namespace}/{name}",
		},
		{
			key:  "/registry/crd.io/resource/namespace_list/",
			want: "/registry/{api-group}/{resource}/{namespace}/",
		},
		{
			key:  "/registry/crd.io/resource/object_get",
			want: "/registry/{api-group}/{resource}/{name}",
		},
		{
			key:  "/registry/crd.io/resource_rev",
			want: "/registry/{api-group}/{resource}",
		},
		{
			key:  "/registry/crd.io/resource_list/",
			want: "/registry/{api-group}/{resource}/",
		},
	} {
		name := strings.Trim(strings.ReplaceAll(tc.key, "/", "_"), "_")
		t.Run(name, func(t *testing.T) {
			got, valid := pattern(tc.key)
			if !valid {
				t.Fatalf("key=%q, want=valid, got=invalid", tc.key)
			}
			if got != tc.want {
				t.Fatalf("key=%q, want=%s, got=%s", tc.key, tc.want, got)
			}
		})
Repository: etcd-io/etcd
File: tests/robustness/coverage/key_pattern_test.go (Go)

Code before:
		return k, false
	}
	slash := ""
	if strings.HasSuffix(k, "/") {
		slash = "/"
	}
	s := strings.Split(strings.Trim(k, "/"), "/")
	if len(s[0]) == 0 {
		return k, false
	}

	resource, shift := resourceOrCRD(s[0])
	s = s[shift:]

	if len(s) == 0 {
		// Listing all resources.
		return "/registry/" + resource + slash, true
	}
	if len(s) == 1 && slash == "" {
		// Get on a non-namespaced resource.
		return "/registry/" + resource + "/{name}", true
	}
	if len(s) == 1 {
		// Listing all resources in a namespace.
		return "/registry/" + resource + "/{namespace}" + slash, true
	}
	if len(s) == 2 && slash == "" {
		// Get on a namespaced resource.
		return "/registry/" + resource + "/{namespace}/{name}", true
	}

	return k, false
}

func resourceOrCRD(s string) (string, int) {
	if strings.Contains(s, ".") {
		// CRD
		return "{api-group}/{resource}", 2
	}
	switch s {
	case "services":
		// services have subresources specs and endpoints.
		return "services/{subresource}", 2
	case "masterleases":
		// masterleases are a special case as they are not a regular (namespaced) resource.
		return "masterleases", 1
	case "events":
		// events are a special case as they have watch cache disabled by default.
		return "events", 1
	}
	return "{resource}", 1

Review comment (suggestion):
```suggestion
	if len(s) == 1 {
		if slash == "" {
			// Get on a non-namespaced resource.
			return "/registry/" + resource + "/{name}", true
		}
		// Listing all resources in a namespace.
		return "/registry/" + resource + "/{namespace}" + slash, true
	}
```

Code after:
		return key, false
	}
	slash := ""
	if strings.HasSuffix(key, "/") {
		slash = "/"
	}
	parts := strings.Split(strings.Trim(key, "/"), "/")
	if len(parts[0]) == 0 {
		return key, false
	}

	apiResource, shift := resourceOrCRD(parts[0])
	parts = parts[shift:]

	switch len(parts) {
	case 0:
		// Listing all resources.
		return "/registry/" + apiResource + slash, true
	case 1:
		if slash == "" {
			// Get on a non-namespaced resource.
			return "/registry/" + apiResource + "/{name}", true
		}
		// Listing all resources in a namespace.
		return "/registry/" + apiResource + "/{namespace}" + slash, true
	case 2:
		if slash == "" {
			// Get on a namespaced resource.
			return "/registry/" + apiResource + "/{namespace}/{name}", true
		}
	}

	return key, false
}

func resourceOrCRD(s string) (string, int) {
	if strings.Contains(s, ".") {
		// Group name from the Custom Resource Definition.
		// Names without dots are technically valid DNS name, but against best practices:
		// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names
		// https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.33/#customresourcedefinitionspec-v1-apiextensions-k8s-io
		return "{api-group}/{resource}", 2
	}
	switch s {
	case "services":
		// services have subresources specs and endpoints.
		return "services/{subresource}", 2
	case "masterleases":
		// masterleases are not a regular resource.
		return "masterleases", 1
	case "events":
Repository: etcd-io/etcd
File: tests/robustness/coverage/key_pattern_test.go (Go)

Code before:
import (
	"strings"
	"testing"
)

func pattern(k string) (string, bool) {
	if k == "/registry/health" || k == "compact_rev_key" {
		return k, true
	}
	k, valid := strings.CutPrefix(k, "/registry")
	if !valid {
		return k, false
	}
	slash := ""
	if strings.HasSuffix(k, "/") {
		slash = "/"
	}
	s := strings.Split(strings.Trim(k, "/"), "/")
	if len(s[0]) == 0 {
		return k, false
	}

	resource, shift := resourceOrCRD(s[0])
	s = s[shift:]

	if len(s) == 0 {
		// Listing all resources.
		return "/registry/" + resource + slash, true
	}
	if len(s) == 1 && slash == "" {
		// Get on a non-namespaced resource.
		return "/registry/" + resource + "/{name}", true
	}
	if len(s) == 1 {
		// Listing all resources in a namespace.
		return "/registry/" + resource + "/{namespace}" + slash, true
	}
	if len(s) == 2 && slash == "" {
		// Get on a namespaced resource.
		return "/registry/" + resource + "/{namespace}/{name}", true
	}

	return k, false
}

func resourceOrCRD(s string) (string, int) {
	if strings.Contains(s, ".") {
		// CRD
		return "{api-group}/{resource}", 2
	}
	switch s {

Review comment (suggestion):
I think it would be better to go back to switch statement on `len(s)`

Code after:
import (
	"strings"
	"testing"
)

func pattern(key string) (string, bool) {
	if key == "/registry/health" || key == "compact_rev_key" {
		return key, true
	}
	key, valid := strings.CutPrefix(key, "/registry")
	if !valid {
		return key, false
	}
	slash := ""
	if strings.HasSuffix(key, "/") {
		slash = "/"
	}
	parts := strings.Split(strings.Trim(key, "/"), "/")
	if len(parts[0]) == 0 {
		return key, false
	}

	apiResource, shift := resourceOrCRD(parts[0])
	parts = parts[shift:]

	switch len(parts) {
	case 0:
		// Listing all resources.
		return "/registry/" + apiResource + slash, true
	case 1:
		if slash == "" {
			// Get on a non-namespaced resource.
			return "/registry/" + apiResource + "/{name}", true
		}
		// Listing all resources in a namespace.
		return "/registry/" + apiResource + "/{namespace}" + slash, true
	case 2:
		if slash == "" {
			// Get on a namespaced resource.
			return "/registry/" + apiResource + "/{namespace}/{name}", true
		}
	}

	return key, false
}

func resourceOrCRD(s string) (string, int) {
	if strings.Contains(s, ".") {
		// Group name from the Custom Resource Definition.
		// Names without dots are technically valid DNS name, but against best practices:
		// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names