File: yaml.go

package info (click to toggle)
golang-github-coreos-pkg 2-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 304 kB
  • ctags: 244
  • sloc: sh: 30; makefile: 3
file content (55 lines) | stat: -rw-r--r-- 1,187 bytes parent folder | download | duplicates (4)
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
package yamlutil

import (
	"flag"
	"fmt"
	"strings"

	"gopkg.in/yaml.v2"
)

// SetFlagsFromYaml goes through all registered flags in the given flagset,
// and if they are not already set it attempts to set their values from
// the YAML config. It will use the key REPLACE(UPPERCASE(flagname), '-', '_')
func SetFlagsFromYaml(fs *flag.FlagSet, rawYaml []byte) (err error) {
	conf := make(map[string]string)
	if err = yaml.Unmarshal(rawYaml, conf); err != nil {
		return
	}
	alreadySet := map[string]struct{}{}
	fs.Visit(func(f *flag.Flag) {
		alreadySet[f.Name] = struct{}{}
	})

	errs := make([]error, 0)
	fs.VisitAll(func(f *flag.Flag) {
		if f.Name == "" {
			return
		}
		if _, ok := alreadySet[f.Name]; ok {
			return
		}
		tag := strings.Replace(strings.ToUpper(f.Name), "-", "_", -1)
		val, ok := conf[tag]
		if !ok {
			return
		}
		if serr := fs.Set(f.Name, val); serr != nil {
			errs = append(errs, fmt.Errorf("invalid value %q for %s: %v", val, tag, serr))
		}
	})
	if len(errs) != 0 {
		err = ErrorSlice(errs)
	}
	return
}

type ErrorSlice []error

func (e ErrorSlice) Error() string {
	s := ""
	for _, err := range e {
		s += ", " + err.Error()
	}
	return "Errors: " + s
}