convertJSON converts JSON hierarchical config objects into a flattened map fulfilling the z.SuperFlag string format so that Viper can correctly set z.SuperFlag config options for the respective subcommands. If JSON hierarchical config objects are not used, convertJSON doesn't change anything and ret
(old string)
| 287 | // |
| 288 | // Viper then uses the "converted" JSON to set the z.SuperFlag strings in subcommand option structs. |
| 289 | func convertJSON(old string) io.Reader { |
| 290 | dec := json.NewDecoder(strings.NewReader(old)) |
| 291 | config := make(map[string]interface{}) |
| 292 | x.Panic(dec.Decode(&config)) |
| 293 | |
| 294 | // super holds superflags to later be condensed into 'good' |
| 295 | super, good := make(map[string]map[string]interface{}), make(map[string]string) |
| 296 | for k, v := range config { |
| 297 | switch t := v.(type) { |
| 298 | case map[string]interface{}: |
| 299 | super[k] = t |
| 300 | default: |
| 301 | good[k] = fmt.Sprintf("%v", v) |
| 302 | } |
| 303 | } |
| 304 | // condense superflags |
| 305 | for f, options := range super { |
| 306 | for k, v := range options { |
| 307 | // JSON does not have distinct types for integers and floats. |
| 308 | // Go will always give us a float64 value. So, an exceptionally |
| 309 | // large integer like 1_000_000 will be printed as 1e06 unless |
| 310 | // we format it carefully. |
| 311 | if vFloat, ok := v.(float64); ok { |
| 312 | v = strconv.FormatFloat(vFloat, 'f', -1, 64) |
| 313 | } |
| 314 | good[f] += fmt.Sprintf("%s=%v; ", k, v) |
| 315 | } |
| 316 | good[f] = good[f][:len(good[f])-1] |
| 317 | } |
| 318 | // generate good json string |
| 319 | buf := &bytes.Buffer{} |
| 320 | enc := json.NewEncoder(buf) |
| 321 | enc.SetIndent("", " ") |
| 322 | x.Panic(enc.Encode(&good)) |
| 323 | |
| 324 | return buf |
| 325 | } |
| 326 | |
| 327 | // convertYAML converts YAML hierarchical notation into a flattened map fulfilling the z.SuperFlag |
| 328 | // string format so that Viper can correctly set the z.SuperFlag config options for the respective |