blob: e220ee07a730f0b9794222453e8212f0a2b4eb8a [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001// Copyright 2018 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package flags
16
17import (
18 "flag"
19 "sort"
20 "strings"
21)
22
23// UniqueStringsValue wraps a list of unique strings.
24// The values are set in order.
25type UniqueStringsValue struct {
26 Values map[string]struct{}
27}
28
29// Set parses a command line set of strings, separated by comma.
30// Implements "flag.Value" interface.
31// The values are set in order.
32func (us *UniqueStringsValue) Set(s string) error {
33 us.Values = make(map[string]struct{})
34 for _, v := range strings.Split(s, ",") {
35 us.Values[v] = struct{}{}
36 }
37 return nil
38}
39
40// String implements "flag.Value" interface.
41func (us *UniqueStringsValue) String() string {
42 return strings.Join(us.stringSlice(), ",")
43}
44
45func (us *UniqueStringsValue) stringSlice() []string {
46 ss := make([]string, 0, len(us.Values))
47 for v := range us.Values {
48 ss = append(ss, v)
49 }
50 sort.Strings(ss)
51 return ss
52}
53
54// NewUniqueStringsValue implements string slice as "flag.Value" interface.
55// Given value is to be separated by comma.
56// The values are set in order.
57func NewUniqueStringsValue(s string) (us *UniqueStringsValue) {
58 us = &UniqueStringsValue{Values: make(map[string]struct{})}
59 if s == "" {
60 return us
61 }
62 if err := us.Set(s); err != nil {
63 plog.Panicf("new UniqueStringsValue should never fail: %v", err)
64 }
65 return us
66}
67
68// UniqueStringsFromFlag returns a string slice from the flag.
69func UniqueStringsFromFlag(fs *flag.FlagSet, flagName string) []string {
70 return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).stringSlice()
71}
72
73// UniqueStringsMapFromFlag returns a map of strings from the flag.
74func UniqueStringsMapFromFlag(fs *flag.FlagSet, flagName string) map[string]struct{} {
75 return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).Values
76}