command.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package yaml
  2. import "fmt"
  3. // StringandSlice stores either a string or slice depending on original type
  4. // Differs from libcompose Stringorslice by being able to determine original type
  5. type StringandSlice struct {
  6. StringValue string
  7. SliceValue []string
  8. }
  9. // UnmarshalYAML implements the Unmarshaller interface.
  10. // TODO: this needs to be ported to go-yaml
  11. func (s *StringandSlice) UnmarshalYAML(tag string, value interface{}) error {
  12. switch value := value.(type) {
  13. case []interface{}:
  14. parts, err := toStrings(value)
  15. if err != nil {
  16. return err
  17. }
  18. s.SliceValue = parts
  19. case string:
  20. s.StringValue = value
  21. default:
  22. return fmt.Errorf("Failed to unmarshal StringandSlice: %#v", value)
  23. }
  24. return nil
  25. }
  26. // TODO: use this function from libcompose
  27. func toStrings(s []interface{}) ([]string, error) {
  28. if len(s) == 0 {
  29. return nil, nil
  30. }
  31. r := make([]string, len(s))
  32. for k, v := range s {
  33. if sv, ok := v.(string); ok {
  34. r[k] = sv
  35. } else {
  36. return nil, fmt.Errorf("Cannot unmarshal '%v' of type %T into a string value", v, v)
  37. }
  38. }
  39. return r, nil
  40. }