Skip to content

Commit 00275cd

Browse files
authored
Add root namespace method to Key (#208)
1 parent 51ad837 commit 00275cd

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

key.go

+13
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,19 @@ func (k Key) BaseNamespace() string {
150150
return n[len(n)-1]
151151
}
152152

153+
// RootNamespace returns the "root" namespace of this key
154+
//
155+
// NewKey("/Comedy/MontyPython/Actor:JohnCleese").RootNamespace()
156+
// "Comedy"
157+
// NewKey("/").RootNamespace()
158+
// ""
159+
// NewKey("/Comedy:MontyPython").RootNamespace()
160+
// "Comedy:MontyPython"
161+
func (k Key) RootNamespace() string {
162+
n := k.Namespaces()
163+
return n[0]
164+
}
165+
153166
// Type returns the "type" of this key (value of last namespace).
154167
//
155168
// NewKey("/Comedy/MontyPython/Actor:JohnCleese").Type()

key_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,23 @@ func TestKeyUnmarshalJSON(t *testing.T) {
204204
}
205205
}
206206
}
207+
208+
func TestKey_RootNamespace(t *testing.T) {
209+
tests := []struct {
210+
name string
211+
key string
212+
want string
213+
}{
214+
{name: "empty path", key: "/", want: ""},
215+
{name: "single namespace", key: "/Comedy", want: "Comedy"},
216+
{name: "long path", key: "/Comedy/MontyPython/Actor:JohnCleese", want: "Comedy"},
217+
{name: "root + type", key: "/Comedy:MontyPython", want: "Comedy:MontyPython"},
218+
}
219+
for _, tt := range tests {
220+
t.Run(tt.name, func(t *testing.T) {
221+
if got := RawKey(tt.key).RootNamespace(); got != tt.want {
222+
t.Errorf("RootNamespace() = %v, want %v", got, tt.want)
223+
}
224+
})
225+
}
226+
}

0 commit comments

Comments
 (0)