forked from docker/cli
-
Notifications
You must be signed in to change notification settings - Fork 8
/
ipnet_slice.go
94 lines (78 loc) · 2.09 KB
/
ipnet_slice.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package swarm
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"net"
"strings"
)
// -- ipNetSlice Value
type ipNetSliceValue struct {
value *[]net.IPNet
changed bool
}
func newIPNetSliceValue(val []net.IPNet, p *[]net.IPNet) *ipNetSliceValue {
ipnsv := new(ipNetSliceValue)
ipnsv.value = p
*ipnsv.value = val
return ipnsv
}
// Set converts, and assigns, the comma-separated IPNet argument string representation as the []net.IPNet value of this flag.
// If Set is called on a flag that already has a []net.IPNet assigned, the newly converted values will be appended.
func (s *ipNetSliceValue) Set(val string) error {
// remove all quote characters
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
// read flag arguments with CSV parser
ipNetStrSlice, err := readAsCSV(rmQuote.Replace(val))
if err != nil && err != io.EOF {
return err
}
// parse ip values into slice
out := make([]net.IPNet, 0, len(ipNetStrSlice))
for _, ipNetStr := range ipNetStrSlice {
_, n, err := net.ParseCIDR(strings.TrimSpace(ipNetStr))
if err != nil {
return fmt.Errorf("invalid string being converted to CIDR: %s", ipNetStr)
}
out = append(out, *n)
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
// Type returns a string that uniquely represents this flag's type.
func (s *ipNetSliceValue) Type() string {
return "ipNetSlice"
}
// String defines a "native" format for this net.IPNet slice flag value.
func (s *ipNetSliceValue) String() string {
ipNetStrSlice := make([]string, len(*s.value))
for i, n := range *s.value {
ipNetStrSlice[i] = n.String()
}
out, _ := writeAsCSV(ipNetStrSlice)
return "[" + out + "]"
}
func readAsCSV(val string) ([]string, error) {
if val == "" {
return []string{}, nil
}
stringReader := strings.NewReader(val)
csvReader := csv.NewReader(stringReader)
return csvReader.Read()
}
func writeAsCSV(vals []string) (string, error) {
b := &bytes.Buffer{}
w := csv.NewWriter(b)
err := w.Write(vals)
if err != nil {
return "", err
}
w.Flush()
return strings.TrimSuffix(b.String(), "\n"), nil
}