data_funcs.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package config
  2. import (
  3. log "github.com/Sirupsen/logrus"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. )
  8. func getOrSetVal(args string, data map[interface{}]interface{}, value interface{}) interface{} {
  9. parts := strings.Split(args, ".")
  10. for i, part := range parts {
  11. val, ok := data[part]
  12. last := i+1 == len(parts)
  13. // Reached end, set the value
  14. if last && value != nil {
  15. if s, ok := value.(string); ok {
  16. value = DummyMarshall(s)
  17. }
  18. data[part] = value
  19. return value
  20. }
  21. // Missing intermediate key, create key
  22. if !last && value != nil && !ok {
  23. newData := map[interface{}]interface{}{}
  24. data[part] = newData
  25. data = newData
  26. continue
  27. }
  28. if !ok {
  29. break
  30. }
  31. if last {
  32. return val
  33. }
  34. newData, ok := val.(map[interface{}]interface{})
  35. if !ok {
  36. break
  37. }
  38. data = newData
  39. }
  40. return ""
  41. }
  42. func DummyMarshall(value string) interface{} {
  43. if strings.HasPrefix(value, "[") && strings.HasSuffix(value, "]") {
  44. result := []string{}
  45. for _, i := range strings.Split(value[1:len(value)-1], ",") {
  46. result = append(result, strings.TrimSpace(i))
  47. }
  48. return result
  49. }
  50. if value == "true" {
  51. return true
  52. } else if value == "false" {
  53. return false
  54. } else if ok, _ := regexp.MatchString("^[0-9]+$", value); ok {
  55. i, err := strconv.Atoi(value)
  56. if err != nil {
  57. panic(err)
  58. }
  59. return i
  60. }
  61. return value
  62. }
  63. func parseCmdline(cmdLine string) map[interface{}]interface{} {
  64. result := make(map[interface{}]interface{})
  65. outer:
  66. for _, part := range strings.Split(cmdLine, " ") {
  67. if !strings.HasPrefix(part, "rancher.") {
  68. continue
  69. }
  70. var value string
  71. kv := strings.SplitN(part, "=", 2)
  72. if len(kv) == 1 {
  73. value = "true"
  74. } else {
  75. value = kv[1]
  76. }
  77. current := result
  78. keys := strings.Split(kv[0], ".")[1:]
  79. for i, key := range keys {
  80. if i == len(keys)-1 {
  81. current[key] = DummyMarshall(value)
  82. } else {
  83. if obj, ok := current[key]; ok {
  84. if newCurrent, ok := obj.(map[interface{}]interface{}); ok {
  85. current = newCurrent
  86. } else {
  87. continue outer
  88. }
  89. } else {
  90. newCurrent := make(map[interface{}]interface{})
  91. current[key] = newCurrent
  92. current = newCurrent
  93. }
  94. }
  95. }
  96. }
  97. log.Debugf("Input obj %v", result)
  98. return result
  99. }