convertYAML converts YAML hierarchical notation into a flattened map fulfilling the z.SuperFlag string format so that Viper can correctly set the z.SuperFlag config options for the respective subcommands. If YAML hierarchical notation is not used, convertYAML doesn't change anything and returns the
(old string)
| 348 | // |
| 349 | // Viper then uses the "converted" YAML to set the z.SuperFlag strings in subcommand option structs. |
| 350 | func convertYAML(old string) io.Reader { |
| 351 | isFlat := func(l string) bool { |
| 352 | if len(l) < 1 { |
| 353 | return false |
| 354 | } |
| 355 | if unicode.IsSpace(rune(l[0])) { |
| 356 | return false |
| 357 | } |
| 358 | return true |
| 359 | } |
| 360 | isOption := func(l string) bool { |
| 361 | if len(l) < 3 { |
| 362 | return false |
| 363 | } |
| 364 | if !strings.Contains(l, ":") { |
| 365 | return false |
| 366 | } |
| 367 | if !unicode.IsSpace(rune(l[0])) { |
| 368 | return false |
| 369 | } |
| 370 | return true |
| 371 | } |
| 372 | isSuper := func(l string) bool { |
| 373 | s := strings.TrimSpace(l) |
| 374 | if len(s) < 1 { |
| 375 | return false |
| 376 | } |
| 377 | if s[len(s)-1] != ':' { |
| 378 | return false |
| 379 | } |
| 380 | return true |
| 381 | } |
| 382 | getName := func(l string) string { |
| 383 | s := strings.TrimSpace(l) |
| 384 | return s[:strings.IndexRune(s, rune(':'))] |
| 385 | } |
| 386 | getValue := func(l string) string { |
| 387 | s := strings.TrimSpace(l) |
| 388 | v := s[strings.IndexRune(s, rune(':'))+2:] |
| 389 | return strings.ReplaceAll(v, `"`, ``) |
| 390 | } |
| 391 | super, good, last := make(map[string]string), make([]string, 0), "" |
| 392 | for _, line := range strings.Split(old, "\n") { |
| 393 | if isSuper(line) { |
| 394 | last = getName(line) |
| 395 | continue |
| 396 | } |
| 397 | if isOption(line) { |
| 398 | name, value := getName(line), getValue(line) |
| 399 | super[last] += name + "=" + value + "; " |
| 400 | continue |
| 401 | } |
| 402 | if isFlat(line) { |
| 403 | good = append(good, strings.TrimSpace(line)) |
| 404 | } |
| 405 | } |
| 406 | for k, v := range super { |
| 407 | super[k] = `"` + strings.TrimSpace(v) + `"` |