parse.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package filters
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "strings"
  6. )
  7. type Args map[string][]string
  8. // Parse the argument to the filter flag. Like
  9. //
  10. // `docker ps -f 'created=today' -f 'image.name=ubuntu*'`
  11. //
  12. // If prev map is provided, then it is appended to, and returned. By default a new
  13. // map is created.
  14. func ParseFlag(arg string, prev Args) (Args, error) {
  15. var filters Args = prev
  16. if prev == nil {
  17. filters = Args{}
  18. }
  19. if len(arg) == 0 {
  20. return filters, nil
  21. }
  22. if !strings.Contains(arg, "=") {
  23. return filters, ErrorBadFormat
  24. }
  25. f := strings.SplitN(arg, "=", 2)
  26. filters[f[0]] = append(filters[f[0]], f[1])
  27. return filters, nil
  28. }
  29. var ErrorBadFormat = errors.New("bad format of filter (expected name=value)")
  30. // packs the Args into an string for easy transport from client to server
  31. func ToParam(a Args) (string, error) {
  32. // this way we don't URL encode {}, just empty space
  33. if len(a) == 0 {
  34. return "", nil
  35. }
  36. buf, err := json.Marshal(a)
  37. if err != nil {
  38. return "", err
  39. }
  40. return string(buf), nil
  41. }
  42. // unpacks the filter Args
  43. func FromParam(p string) (Args, error) {
  44. args := Args{}
  45. if len(p) == 0 {
  46. return args, nil
  47. }
  48. err := json.Unmarshal([]byte(p), &args)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return args, nil
  53. }