Tizen_4.0 base
[platform/upstream/docker-engine.git] / vendor / github.com / docker / cli / opts / weightdevice.go
1 package opts
2
3 import (
4         "fmt"
5         "strconv"
6         "strings"
7
8         "github.com/docker/docker/api/types/blkiodev"
9 )
10
11 // ValidatorWeightFctType defines a validator function that returns a validated struct and/or an error.
12 type ValidatorWeightFctType func(val string) (*blkiodev.WeightDevice, error)
13
14 // ValidateWeightDevice validates that the specified string has a valid device-weight format.
15 func ValidateWeightDevice(val string) (*blkiodev.WeightDevice, error) {
16         split := strings.SplitN(val, ":", 2)
17         if len(split) != 2 {
18                 return nil, fmt.Errorf("bad format: %s", val)
19         }
20         if !strings.HasPrefix(split[0], "/dev/") {
21                 return nil, fmt.Errorf("bad format for device path: %s", val)
22         }
23         weight, err := strconv.ParseUint(split[1], 10, 0)
24         if err != nil {
25                 return nil, fmt.Errorf("invalid weight for device: %s", val)
26         }
27         if weight > 0 && (weight < 10 || weight > 1000) {
28                 return nil, fmt.Errorf("invalid weight for device: %s", val)
29         }
30
31         return &blkiodev.WeightDevice{
32                 Path:   split[0],
33                 Weight: uint16(weight),
34         }, nil
35 }
36
37 // WeightdeviceOpt defines a map of WeightDevices
38 type WeightdeviceOpt struct {
39         values    []*blkiodev.WeightDevice
40         validator ValidatorWeightFctType
41 }
42
43 // NewWeightdeviceOpt creates a new WeightdeviceOpt
44 func NewWeightdeviceOpt(validator ValidatorWeightFctType) WeightdeviceOpt {
45         values := []*blkiodev.WeightDevice{}
46         return WeightdeviceOpt{
47                 values:    values,
48                 validator: validator,
49         }
50 }
51
52 // Set validates a WeightDevice and sets its name as a key in WeightdeviceOpt
53 func (opt *WeightdeviceOpt) Set(val string) error {
54         var value *blkiodev.WeightDevice
55         if opt.validator != nil {
56                 v, err := opt.validator(val)
57                 if err != nil {
58                         return err
59                 }
60                 value = v
61         }
62         (opt.values) = append((opt.values), value)
63         return nil
64 }
65
66 // String returns WeightdeviceOpt values as a string.
67 func (opt *WeightdeviceOpt) String() string {
68         var out []string
69         for _, v := range opt.values {
70                 out = append(out, v.String())
71         }
72
73         return fmt.Sprintf("%v", out)
74 }
75
76 // GetList returns a slice of pointers to WeightDevices.
77 func (opt *WeightdeviceOpt) GetList() []*blkiodev.WeightDevice {
78         return opt.values
79 }
80
81 // Type returns the option type
82 func (opt *WeightdeviceOpt) Type() string {
83         return "list"
84 }