stringmap.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2017 Google Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package flags
  14. import (
  15. "fmt"
  16. "sort"
  17. "strings"
  18. )
  19. // StringMap is a map[string]string container for command line flags. The
  20. // default initialization will create an empty map. If you need default backing
  21. // map use NewStringMap.
  22. type StringMap map[string]string
  23. func (m *StringMap) String() string {
  24. s := make([]string, len(*m))
  25. i := 0
  26. for k, v := range *m {
  27. s[i] = fmt.Sprintf("%s=%s", k, v)
  28. i++
  29. }
  30. sort.Strings(s)
  31. return strings.Join(s, ",")
  32. }
  33. // Get returns the values of m. The interface will need to be type asserted to
  34. // StringMap for use.
  35. func (m *StringMap) Get() interface{} {
  36. return *m
  37. }
  38. // Set will take a string in the format <key1>=<value1>,<key2>=<value2> and
  39. // parse the resulting value into a map[string]string.
  40. func (m *StringMap) Set(v string) error {
  41. *m = StringMap{}
  42. for _, entry := range strings.Split(v, ",") {
  43. data := strings.SplitN(entry, "=", 2)
  44. if len(data) != 2 {
  45. return fmt.Errorf("invalid key=value pair: %s", entry)
  46. }
  47. k := strings.TrimSpace(data[0])
  48. v := strings.TrimSpace(data[1])
  49. if len(k) == 0 {
  50. return fmt.Errorf("invalid key=value pair: %s", entry)
  51. }
  52. (*m)[k] = v
  53. }
  54. return nil
  55. }
  56. // NewStringMap will wrap the pointer to the map in a StringMap and set the
  57. // underlying map to val.
  58. func NewStringMap(p *map[string]string, val map[string]string) *StringMap {
  59. *p = val
  60. return (*StringMap)(p)
  61. }