2014-02-26 17:04:11 -05:00
|
|
|
package filters
|
|
|
|
|
|
|
|
import (
|
2014-05-30 14:59:03 -04:00
|
|
|
"encoding/json"
|
2014-02-26 17:04:11 -05:00
|
|
|
"errors"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2014-05-19 16:31:15 -04:00
|
|
|
type Args map[string][]string
|
|
|
|
|
2014-05-30 15:55:40 -04:00
|
|
|
// Parse the argument to the filter flag. Like
|
|
|
|
//
|
|
|
|
// `docker ps -f 'created=today' -f 'image.name=ubuntu*'`
|
|
|
|
//
|
|
|
|
// If prev map is provided, then it is appended to, and returned. By default a new
|
|
|
|
// map is created.
|
2014-05-19 16:31:15 -04:00
|
|
|
func ParseFlag(arg string, prev Args) (Args, error) {
|
|
|
|
var filters Args = prev
|
|
|
|
if prev == nil {
|
|
|
|
filters = Args{}
|
2014-02-26 17:04:11 -05:00
|
|
|
}
|
2014-03-26 15:14:26 -04:00
|
|
|
if len(arg) == 0 {
|
|
|
|
return filters, nil
|
|
|
|
}
|
2014-02-26 17:04:11 -05:00
|
|
|
|
2014-05-19 16:31:15 -04:00
|
|
|
if !strings.Contains(arg, "=") {
|
|
|
|
return filters, ErrorBadFormat
|
2014-02-26 17:04:11 -05:00
|
|
|
}
|
2014-05-19 16:31:15 -04:00
|
|
|
|
|
|
|
f := strings.SplitN(arg, "=", 2)
|
|
|
|
filters[f[0]] = append(filters[f[0]], f[1])
|
|
|
|
|
2014-02-26 17:04:11 -05:00
|
|
|
return filters, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var ErrorBadFormat = errors.New("bad format of filter (expected name=value)")
|
|
|
|
|
2014-05-30 15:55:40 -04:00
|
|
|
// packs the Args into an string for easy transport from client to server
|
2014-05-30 14:59:03 -04:00
|
|
|
func ToParam(a Args) (string, error) {
|
2014-05-30 15:55:40 -04:00
|
|
|
// this way we don't URL encode {}, just empty space
|
|
|
|
if len(a) == 0 {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
2014-05-30 14:59:03 -04:00
|
|
|
buf, err := json.Marshal(a)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return string(buf), nil
|
2014-05-19 16:31:15 -04:00
|
|
|
}
|
|
|
|
|
2014-05-30 15:55:40 -04:00
|
|
|
// unpacks the filter Args
|
2014-05-19 16:31:15 -04:00
|
|
|
func FromParam(p string) (Args, error) {
|
2014-05-30 14:59:03 -04:00
|
|
|
args := Args{}
|
2014-05-30 15:55:40 -04:00
|
|
|
if len(p) == 0 {
|
|
|
|
return args, nil
|
|
|
|
}
|
2014-05-30 14:59:03 -04:00
|
|
|
err := json.Unmarshal([]byte(p), &args)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return args, nil
|
2014-02-26 17:04:11 -05:00
|
|
|
}
|