From 20b863284aff1c2de55fa3105273b437bb7019f0 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Mon, 11 Oct 2021 12:52:18 +0300 Subject: [PATCH] [#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 --- pkg/container/attribute.go | 54 +++++++++++++++++++++++++++++++++ pkg/container/attribute_test.go | 22 ++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/pkg/container/attribute.go b/pkg/container/attribute.go index ec633e8a..0219005e 100644 --- a/pkg/container/attribute.go +++ b/pkg/container/attribute.go @@ -74,3 +74,57 @@ func (a Attributes) ToV2() []*container.Attribute { 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 +} diff --git a/pkg/container/attribute_test.go b/pkg/container/attribute_test.go index acd7bbd0..65967c49 100644 --- a/pkg/container/attribute_test.go +++ b/pkg/container/attribute_test.go @@ -118,3 +118,25 @@ func TestNewAttributeFromV2(t *testing.T) { 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) + } +}