flag.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2017 The Bazel Authors. All rights reserved.
  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 flag provides some general-purpose types which satisfy the
  15. // flag.Value interface.
  16. package flag
  17. import (
  18. stdflag "flag"
  19. "fmt"
  20. "strings"
  21. )
  22. // MultiFlag collects repeated string flags into a slice.
  23. type MultiFlag struct {
  24. IsSet *bool
  25. Values *[]string
  26. }
  27. var _ stdflag.Value = (*MultiFlag)(nil)
  28. func (m *MultiFlag) Set(v string) error {
  29. if m.IsSet != nil && !*m.IsSet {
  30. *m.IsSet = true
  31. *m.Values = nil // clear any default values
  32. }
  33. *m.Values = append(*m.Values, v)
  34. return nil
  35. }
  36. func (m *MultiFlag) String() string {
  37. if m == nil || m.Values == nil {
  38. return ""
  39. }
  40. return strings.Join(*m.Values, ",")
  41. }
  42. // ExplicitFlag is a string flag that tracks whether it was set.
  43. type ExplicitFlag struct {
  44. IsSet *bool
  45. Value *string
  46. }
  47. var _ stdflag.Value = (*ExplicitFlag)(nil)
  48. func (f *ExplicitFlag) Set(value string) error {
  49. *f.IsSet = true
  50. *f.Value = value
  51. return nil
  52. }
  53. func (f *ExplicitFlag) String() string {
  54. if f == nil || f.Value == nil {
  55. return ""
  56. }
  57. return *f.Value
  58. }
  59. var _ stdflag.Value = (*AllowedStringFlag)(nil)
  60. type AllowedStringFlag struct {
  61. Allowed []string
  62. Value *string
  63. }
  64. func (f *AllowedStringFlag) Set(v string) error {
  65. for _, a := range f.Allowed {
  66. if v == a {
  67. *f.Value = v
  68. return nil
  69. }
  70. }
  71. return fmt.Errorf("Invalid argument %q. Possible values are: %s", v, strings.Join(f.Allowed, ", "))
  72. }
  73. func (f *AllowedStringFlag) String() string {
  74. if f == nil || f.Value == nil {
  75. return ""
  76. }
  77. return *f.Value
  78. }