[#351] pkg/container: Implement functions to work with native names

Implement `GetNativeNameWithZone` / `SetNativeNameWithZone` function which
gets / sets `__NEOFS_NAME` and `__NEOFS_ZONE` container attributes.

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2021-10-11 12:52:18 +03:00 committed by Alex Vanin
parent 7348dee623
commit 20b863284a
2 changed files with 76 additions and 0 deletions

View file

@ -74,3 +74,57 @@ func (a Attributes) ToV2() []*container.Attribute {
return attrs return attrs
} }
// sets value of the attribute by key.
func setAttribute(c *Container, key, value string) {
var a *Attribute
iterateAttributes(c, func(a_ *Attribute) bool {
if a_.Key() == key {
a = a_
}
return a != nil
})
if a == nil {
a = NewAttribute()
a.SetKey(key)
c.SetAttributes(append(c.Attributes(), a))
}
a.SetValue(value)
}
// iterates over container attributes. Stops at f's true return.
//
// Handler must not be nil.
func iterateAttributes(c *Container, f func(*Attribute) bool) {
for _, a := range c.Attributes() {
if f(a) {
return
}
}
}
// SetNativeNameWithZone sets container native name and its zone.
func SetNativeNameWithZone(c *Container, name, zone string) {
setAttribute(c, container.SysAttributeName, name)
setAttribute(c, container.SysAttributeZone, zone)
}
// GetNativeNameWithZone returns container native name and its zone.
func GetNativeNameWithZone(c *Container) (name string, zone string) {
iterateAttributes(c, func(a *Attribute) bool {
if key := a.Key(); key == container.SysAttributeName {
name = a.Value()
} else if key == container.SysAttributeZone {
zone = a.Value()
}
return name != "" && zone != ""
})
return
}

View file

@ -118,3 +118,25 @@ func TestNewAttributeFromV2(t *testing.T) {
require.Nil(t, container.NewAttributeFromV2(x)) require.Nil(t, container.NewAttributeFromV2(x))
}) })
} }
func TestGetNameWithZone(t *testing.T) {
c := container.New()
for _, item := range [...]struct {
name, zone string
}{
{"name1", ""},
{"name1", "zone1"},
{"name2", "zone1"},
{"name2", "zone2"},
{"", "zone2"},
{"", ""},
} {
container.SetNativeNameWithZone(c, item.name, item.zone)
name, zone := container.GetNativeNameWithZone(c)
require.Equal(t, item.name, name, item.name)
require.Equal(t, item.zone, zone, item.zone)
}
}