strings.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // 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. package flags
  15. import (
  16. "flag"
  17. "sort"
  18. "strings"
  19. )
  20. // StringsValue wraps "sort.StringSlice".
  21. type StringsValue sort.StringSlice
  22. // Set parses a command line set of strings, separated by comma.
  23. // Implements "flag.Value" interface.
  24. func (ss *StringsValue) Set(s string) error {
  25. *ss = strings.Split(s, ",")
  26. return nil
  27. }
  28. // String implements "flag.Value" interface.
  29. func (ss *StringsValue) String() string { return strings.Join(*ss, ",") }
  30. // NewStringsValue implements string slice as "flag.Value" interface.
  31. // Given value is to be separated by comma.
  32. func NewStringsValue(s string) (ss *StringsValue) {
  33. if s == "" {
  34. return &StringsValue{}
  35. }
  36. ss = new(StringsValue)
  37. if err := ss.Set(s); err != nil {
  38. plog.Panicf("new StringsValue should never fail: %v", err)
  39. }
  40. return ss
  41. }
  42. // StringsFromFlag returns a string slice from the flag.
  43. func StringsFromFlag(fs *flag.FlagSet, flagName string) []string {
  44. return []string(*fs.Lookup(flagName).Value.(*StringsValue))
  45. }