diff --git a/key.go b/key.go index 24bfccb..345d943 100644 --- a/key.go +++ b/key.go @@ -150,6 +150,19 @@ func (k Key) BaseNamespace() string { return n[len(n)-1] } +// RootNamespace returns the "root" namespace of this key +// +// NewKey("/Comedy/MontyPython/Actor:JohnCleese").RootNamespace() +// "Comedy" +// NewKey("/").RootNamespace() +// "" +// NewKey("/Comedy:MontyPython").RootNamespace() +// "Comedy:MontyPython" +func (k Key) RootNamespace() string { + n := k.Namespaces() + return n[0] +} + // Type returns the "type" of this key (value of last namespace). // // NewKey("/Comedy/MontyPython/Actor:JohnCleese").Type() diff --git a/key_test.go b/key_test.go index 7272af0..c24415e 100644 --- a/key_test.go +++ b/key_test.go @@ -204,3 +204,23 @@ func TestKeyUnmarshalJSON(t *testing.T) { } } } + +func TestKey_RootNamespace(t *testing.T) { + tests := []struct { + name string + key string + want string + }{ + {name: "empty path", key: "/", want: ""}, + {name: "single namespace", key: "/Comedy", want: "Comedy"}, + {name: "long path", key: "/Comedy/MontyPython/Actor:JohnCleese", want: "Comedy"}, + {name: "root + type", key: "/Comedy:MontyPython", want: "Comedy:MontyPython"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := RawKey(tt.key).RootNamespace(); got != tt.want { + t.Errorf("RootNamespace() = %v, want %v", got, tt.want) + } + }) + } +}