...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package flags
16
17 import (
18 "flag"
19 "fmt"
20 "net/url"
21 "sort"
22 "strings"
23
24 "go.etcd.io/etcd/client/pkg/v3/types"
25 )
26
27
28
29 type UniqueURLs struct {
30 Values map[string]struct{}
31 uss []url.URL
32 Allowed map[string]struct{}
33 }
34
35
36
37
38 func (us *UniqueURLs) Set(s string) error {
39 if _, ok := us.Values[s]; ok {
40 return nil
41 }
42 if _, ok := us.Allowed[s]; ok {
43 us.Values[s] = struct{}{}
44 return nil
45 }
46 ss, err := types.NewURLs(strings.Split(s, ","))
47 if err != nil {
48 return err
49 }
50 us.Values = make(map[string]struct{})
51 us.uss = make([]url.URL, 0)
52 for _, v := range ss {
53 x := v.String()
54 if _, exists := us.Values[x]; exists {
55 continue
56 }
57 us.Values[x] = struct{}{}
58 us.uss = append(us.uss, v)
59 }
60 return nil
61 }
62
63
64 func (us *UniqueURLs) String() string {
65 all := make([]string, 0, len(us.Values))
66 for u := range us.Values {
67 all = append(all, u)
68 }
69 sort.Strings(all)
70 return strings.Join(all, ",")
71 }
72
73
74
75 func NewUniqueURLsWithExceptions(s string, exceptions ...string) *UniqueURLs {
76 us := &UniqueURLs{Values: make(map[string]struct{}), Allowed: make(map[string]struct{})}
77 for _, v := range exceptions {
78 us.Allowed[v] = struct{}{}
79 }
80 if s == "" {
81 return us
82 }
83 if err := us.Set(s); err != nil {
84 panic(fmt.Sprintf("new UniqueURLs should never fail: %v", err))
85 }
86 return us
87 }
88
89
90 func UniqueURLsFromFlag(fs *flag.FlagSet, urlsFlagName string) []url.URL {
91 return (*fs.Lookup(urlsFlagName).Value.(*UniqueURLs)).uss
92 }
93
94
95 func UniqueURLsMapFromFlag(fs *flag.FlagSet, urlsFlagName string) map[string]struct{} {
96 return (*fs.Lookup(urlsFlagName).Value.(*UniqueURLs)).Values
97 }
98
View as plain text