~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/github.com/juju/cmd/stringmap.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2016 Canonical Ltd.
 
2
// Licensed under the LGPLv3, see LICENSE file for details.
 
3
 
 
4
package cmd
 
5
 
 
6
import (
 
7
        "errors"
 
8
        "strings"
 
9
)
 
10
 
 
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
 
17
}
 
18
 
 
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{}
 
23
        }
 
24
        // make a copy so the following code is less ugly with dereferencing.
 
25
        mapping := *m.Mapping
 
26
 
 
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)
 
30
        if len(vals) != 2 {
 
31
                return errors.New("expected key=value format")
 
32
        }
 
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")
 
36
        }
 
37
        if _, ok := mapping[key]; ok {
 
38
                return errors.New("duplicate key specified")
 
39
        }
 
40
        mapping[key] = value
 
41
        return nil
 
42
}
 
43
 
 
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)
 
49
        }
 
50
        return strings.Join(pairs, ";")
 
51
}