tristate.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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 flag
  14. import (
  15. "fmt"
  16. "strconv"
  17. )
  18. // Tristate is a flag compatible with flags and pflags that
  19. // keeps track of whether it had a value supplied or not.
  20. type Tristate int
  21. const (
  22. Unset Tristate = iota // 0
  23. True
  24. False
  25. )
  26. func (f *Tristate) Default(value bool) {
  27. *f = triFromBool(value)
  28. }
  29. func (f Tristate) String() string {
  30. b := boolFromTri(f)
  31. return fmt.Sprintf("%t", b)
  32. }
  33. func (f Tristate) Value() bool {
  34. b := boolFromTri(f)
  35. return b
  36. }
  37. func (f *Tristate) Set(value string) error {
  38. boolVal, err := strconv.ParseBool(value)
  39. if err != nil {
  40. return err
  41. }
  42. *f = triFromBool(boolVal)
  43. return nil
  44. }
  45. func (f Tristate) Provided() bool {
  46. if f != Unset {
  47. return true
  48. }
  49. return false
  50. }
  51. func (f *Tristate) Type() string {
  52. return "tristate"
  53. }
  54. func boolFromTri(t Tristate) bool {
  55. if t == True {
  56. return true
  57. } else {
  58. return false
  59. }
  60. }
  61. func triFromBool(b bool) Tristate {
  62. if b {
  63. return True
  64. } else {
  65. return False
  66. }
  67. }