-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathkv.go
60 lines (52 loc) · 1.42 KB
/
kv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
"strings"
)
// FIXME: This is a temporary solution until dagger supports map types as public types. Remove when
// issue: https://github.com/dagger/dagger/issues/6138 is fixed.
// KV is representing a key=value pair to be used in a list of key=value strings.
type KV struct {
Key string
Value string
}
// NewKV returns a new KV instance.
func NewKV(key, value string) KV {
return KV{Key: key, Value: value}
}
// ConvertMapToKVSlice converts a map to a list of key=value strings.
func ConvertMapToKVSlice(m map[string]string) []KV {
kv := make([]KV, 0, len(m))
for k, v := range m {
kv = append(kv, NewKV(k, v))
}
return kv
}
// ConvertKVSliceToMap converts a list of KV to a map.
func ConvertKVSliceToMap(kv []KV) map[string]string {
m := make(map[string]string, len(kv))
for _, v := range kv {
m[v.Key] = v.Value
}
return m
}
// ParseKeyValuePairs converts a list of key=value strings to a list of KV.
func ParseKeyValuePairs(s []string) ([]KV, error) {
slice := make([]KV, 0, len(s))
for _, v := range s {
kv, err := DecodeKeyValue(v)
if err != nil {
return nil, err
}
slice = append(slice, kv)
}
return slice, nil
}
// DecodeKeyValue converts a key=value string to a KV.
func DecodeKeyValue(str string) (KV, error) {
parts := strings.SplitN(str, "=", 2)
if len(parts) != 2 {
return KV{}, fmt.Errorf("invalid key=value pair: %s", str)
}
return NewKV(parts[0], parts[1]), nil
}