1
// Copyright 2016 Canonical Ltd.
2
// Licensed under the AGPLv3, see LICENCE file for details.
12
"github.com/juju/errors"
13
"github.com/juju/utils"
17
// ConfigFlag records k=v attributes from command arguments
18
// and/or specified files containing key values.
19
type ConfigFlag struct {
21
attrs map[string]interface{}
24
// Set implements gnuflag.Value.Set.
25
func (f *ConfigFlag) Set(s string) error {
27
return errors.NotValidf("empty string")
29
fields := strings.SplitN(s, "=", 2)
31
f.files = append(f.files, fields[0])
35
if err := yaml.Unmarshal([]byte(fields[1]), &value); err != nil {
36
return errors.Trace(err)
39
f.attrs = make(map[string]interface{})
41
f.attrs[fields[0]] = value
45
// ReadAttrs reads attributes from the specified files, and then overlays
46
// the results with the k=v attributes.
47
func (f *ConfigFlag) ReadAttrs(ctx *cmd.Context) (map[string]interface{}, error) {
48
attrs := make(map[string]interface{})
49
for _, f := range f.files {
50
path, err := utils.NormalizePath(f)
52
return nil, errors.Trace(err)
54
data, err := ioutil.ReadFile(ctx.AbsPath(path))
56
return nil, errors.Trace(err)
58
if err := yaml.Unmarshal(data, &attrs); err != nil {
62
for k, v := range f.attrs {
68
// String implements gnuflag.Value.String.
69
func (f *ConfigFlag) String() string {
70
strs := make([]string, 0, len(f.attrs)+len(f.files))
71
for _, f := range f.files {
72
strs = append(strs, f)
74
for k, v := range f.attrs {
75
strs = append(strs, fmt.Sprintf("%s=%v", k, v))
77
return strings.Join(strs, " ")