1
// Copyright 2016 Canonical Ltd.
2
// Licensed under the LGPLv3, see LICENSE file for details.
11
// StringMap is a type that deserializes a CLI string using gnuflag's Value
12
// semantics. It expects a key=value pair, and supports multiple copies of the
13
// flag adding more pairs, though the keys must be unique, and both keys and
14
// values must be non-empty.
15
type StringMap struct {
16
Mapping *map[string]string
19
// Set implements gnuflag.Value's Set method.
20
func (m StringMap) Set(s string) error {
21
if *m.Mapping == nil {
22
*m.Mapping = map[string]string{}
24
// make a copy so the following code is less ugly with dereferencing.
27
// Note that gnuflag will prepend the bad argument to the error message, so
28
// we don't need to restate it here.
29
vals := strings.SplitN(s, "=", 2)
31
return errors.New("expected key=value format")
33
key, value := vals[0], vals[1]
34
if len(key) == 0 || len(value) == 0 {
35
return errors.New("key and value must be non-empty")
37
if _, ok := mapping[key]; ok {
38
return errors.New("duplicate key specified")
44
// String implements gnuflag.Value's String method
45
func (m StringMap) String() string {
46
pairs := make([]string, 0, len(*m.Mapping))
47
for key, value := range *m.Mapping {
48
pairs = append(pairs, key+"="+value)
50
return strings.Join(pairs, ";")