2020-09-22 10:56:43 +00:00
|
|
|
package attributes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
2021-11-10 07:08:33 +00:00
|
|
|
"github.com/nspcc-dev/neofs-sdk-go/netmap"
|
2020-09-22 10:56:43 +00:00
|
|
|
)
|
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
const keyValueSeparator = ":"
|
2020-09-22 10:56:43 +00:00
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
// ReadNodeAttributes parses node attributes from list of string in "Key:Value" format
|
|
|
|
// and writes them into netmap.NodeInfo instance. Supports escaped symbols
|
|
|
|
// "\:", "\/" and "\\".
|
|
|
|
func ReadNodeAttributes(dst *netmap.NodeInfo, attrs []string) error {
|
|
|
|
cache := make(map[string]struct{}, len(attrs))
|
2020-09-22 10:56:43 +00:00
|
|
|
|
|
|
|
for i := range attrs {
|
2022-06-08 23:18:26 +00:00
|
|
|
line := replaceEscaping(attrs[i], false) // replaced escaped symbols with non-printable symbols
|
2020-09-22 10:56:43 +00:00
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
words := strings.Split(line, keyValueSeparator)
|
|
|
|
if len(words) != 2 {
|
|
|
|
return errors.New("missing attribute key and/or value")
|
|
|
|
}
|
2021-09-01 09:55:09 +00:00
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
_, ok := cache[words[0]]
|
|
|
|
if ok {
|
|
|
|
return fmt.Errorf("duplicated keys %s", words[0])
|
|
|
|
}
|
2021-08-04 09:21:40 +00:00
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
cache[words[0]] = struct{}{}
|
2020-09-22 10:56:43 +00:00
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
// replace non-printable symbols with escaped symbols without escape character
|
|
|
|
words[0] = replaceEscaping(words[0], true)
|
|
|
|
words[1] = replaceEscaping(words[1], true)
|
|
|
|
fmt.Println(words[0], words[1])
|
2020-09-22 10:56:43 +00:00
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
if words[0] == "" {
|
|
|
|
return errors.New("empty key")
|
|
|
|
} else if words[1] == "" {
|
|
|
|
return errors.New("empty value")
|
2020-09-22 10:56:43 +00:00
|
|
|
}
|
2022-06-08 23:18:26 +00:00
|
|
|
|
|
|
|
dst.SetAttribute(words[0], words[1])
|
2020-09-22 10:56:43 +00:00
|
|
|
}
|
|
|
|
|
2022-06-08 23:18:26 +00:00
|
|
|
return nil
|
2020-09-22 10:56:43 +00:00
|
|
|
}
|
2021-08-04 09:21:40 +00:00
|
|
|
|
|
|
|
func replaceEscaping(target string, rollback bool) (s string) {
|
|
|
|
const escChar = `\`
|
|
|
|
|
|
|
|
var (
|
2022-06-08 23:18:26 +00:00
|
|
|
oldKVSep = escChar + keyValueSeparator
|
|
|
|
oldEsc = escChar + escChar
|
|
|
|
newKVSep = string(uint8(2))
|
|
|
|
newEsc = string(uint8(3))
|
2021-08-04 09:21:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
if rollback {
|
2022-06-08 23:18:26 +00:00
|
|
|
oldKVSep, oldEsc = newKVSep, newEsc
|
2021-08-04 09:21:40 +00:00
|
|
|
newKVSep = keyValueSeparator
|
|
|
|
newEsc = escChar
|
|
|
|
}
|
|
|
|
|
|
|
|
s = strings.ReplaceAll(target, oldEsc, newEsc)
|
|
|
|
s = strings.ReplaceAll(s, oldKVSep, newKVSep)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|