2018-08-13 22:44:46 +00:00
|
|
|
package mcfg
|
|
|
|
|
2018-08-14 00:05:22 +00:00
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
)
|
2018-08-13 22:44:46 +00:00
|
|
|
|
|
|
|
// ParamValue describes a value for a parameter which has been parsed by a
|
2019-01-08 19:21:55 +00:00
|
|
|
// Source.
|
2018-08-13 22:44:46 +00:00
|
|
|
type ParamValue struct {
|
|
|
|
Param
|
|
|
|
Value json.RawMessage
|
|
|
|
}
|
|
|
|
|
2019-01-08 19:21:55 +00:00
|
|
|
// Source parses ParamValues out of a particular configuration source, given a
|
|
|
|
// sorted set of possible Params to parse. The returned []ParamValue may contain
|
|
|
|
// duplicates of the same Param's value. in which case the later value takes
|
|
|
|
// precedence.
|
2018-08-13 22:44:46 +00:00
|
|
|
type Source interface {
|
2019-01-08 19:21:55 +00:00
|
|
|
Parse([]Param) ([]ParamValue, error)
|
2018-08-13 22:44:46 +00:00
|
|
|
}
|
2018-08-14 00:15:54 +00:00
|
|
|
|
|
|
|
// Sources combines together multiple Source instances into one. It will call
|
2019-01-08 19:21:55 +00:00
|
|
|
// Parse on each element individually. Values from later Sources take precedence
|
|
|
|
// over previous ones.
|
2018-08-14 00:15:54 +00:00
|
|
|
type Sources []Source
|
|
|
|
|
|
|
|
// Parse implements the method for the Source interface.
|
2019-01-08 19:21:55 +00:00
|
|
|
func (ss Sources) Parse(params []Param) ([]ParamValue, error) {
|
2018-08-14 00:15:54 +00:00
|
|
|
var pvs []ParamValue
|
|
|
|
for _, s := range ss {
|
2019-01-08 19:21:55 +00:00
|
|
|
innerPVs, err := s.Parse(params)
|
2018-08-14 00:15:54 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
pvs = append(pvs, innerPVs...)
|
|
|
|
}
|
|
|
|
return pvs, nil
|
|
|
|
}
|
2018-08-14 00:44:03 +00:00
|
|
|
|
|
|
|
// SourceMap implements the Source interface by mapping parameter names to
|
|
|
|
// values for them. The names are comprised of the path and name of a Param
|
2019-01-08 19:21:55 +00:00
|
|
|
// joined by "-" characters, i.e. `strings.Join(append(param.Path, param.Name),
|
|
|
|
// "-")`. Values will be parsed in the same way that SourceEnv parses its
|
|
|
|
// variables.
|
2018-08-14 00:44:03 +00:00
|
|
|
type SourceMap map[string]string
|
|
|
|
|
2019-01-08 19:21:55 +00:00
|
|
|
func (m SourceMap) Parse(params []Param) ([]ParamValue, error) {
|
2018-08-14 00:44:03 +00:00
|
|
|
pvs := make([]ParamValue, 0, len(m))
|
2019-01-08 19:21:55 +00:00
|
|
|
for _, p := range params {
|
2018-08-14 01:02:06 +00:00
|
|
|
if v, ok := m[p.fullName()]; ok {
|
|
|
|
pvs = append(pvs, ParamValue{
|
|
|
|
Param: p,
|
|
|
|
Value: p.fuzzyParse(v),
|
|
|
|
})
|
2018-08-14 00:44:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return pvs, nil
|
|
|
|
}
|