parse.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package opts
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "github.com/docker/docker/api/types/container"
  7. )
  8. // ReadKVStrings reads a file of line terminated key=value pairs, and overrides any keys
  9. // present in the file with additional pairs specified in the override parameter
  10. func ReadKVStrings(files []string, override []string) ([]string, error) {
  11. envVariables := []string{}
  12. for _, ef := range files {
  13. parsedVars, err := ParseEnvFile(ef)
  14. if err != nil {
  15. return nil, err
  16. }
  17. envVariables = append(envVariables, parsedVars...)
  18. }
  19. // parse the '-e' and '--env' after, to allow override
  20. envVariables = append(envVariables, override...)
  21. return envVariables, nil
  22. }
  23. // ConvertKVStringsToMap converts ["key=value"] to {"key":"value"}
  24. func ConvertKVStringsToMap(values []string) map[string]string {
  25. result := make(map[string]string, len(values))
  26. for _, value := range values {
  27. kv := strings.SplitN(value, "=", 2)
  28. if len(kv) == 1 {
  29. result[kv[0]] = ""
  30. } else {
  31. result[kv[0]] = kv[1]
  32. }
  33. }
  34. return result
  35. }
  36. // ConvertKVStringsToMapWithNil converts ["key=value"] to {"key":"value"}
  37. // but set unset keys to nil - meaning the ones with no "=" in them.
  38. // We use this in cases where we need to distinguish between
  39. // FOO= and FOO
  40. // where the latter case just means FOO was mentioned but not given a value
  41. func ConvertKVStringsToMapWithNil(values []string) map[string]*string {
  42. result := make(map[string]*string, len(values))
  43. for _, value := range values {
  44. kv := strings.SplitN(value, "=", 2)
  45. if len(kv) == 1 {
  46. result[kv[0]] = nil
  47. } else {
  48. result[kv[0]] = &kv[1]
  49. }
  50. }
  51. return result
  52. }
  53. // ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect
  54. func ParseRestartPolicy(policy string) (container.RestartPolicy, error) {
  55. p := container.RestartPolicy{}
  56. if policy == "" {
  57. return p, nil
  58. }
  59. parts := strings.Split(policy, ":")
  60. if len(parts) > 2 {
  61. return p, fmt.Errorf("invalid restart policy format")
  62. }
  63. if len(parts) == 2 {
  64. count, err := strconv.Atoi(parts[1])
  65. if err != nil {
  66. return p, fmt.Errorf("maximum retry count must be an integer")
  67. }
  68. p.MaximumRetryCount = count
  69. }
  70. p.Name = parts[0]
  71. return p, nil
  72. }