fieldoptions.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package mapping
  2. import "fmt"
  3. const notSymbol = '!'
  4. type (
  5. // use context and OptionalDep option to determine the value of Optional
  6. // nothing to do with context.Context
  7. fieldOptionsWithContext struct {
  8. Inherit bool
  9. FromString bool
  10. Optional bool
  11. Options []string
  12. Default string
  13. EnvVar string
  14. Range *numberRange
  15. }
  16. fieldOptions struct {
  17. fieldOptionsWithContext
  18. OptionalDep string
  19. }
  20. numberRange struct {
  21. left float64
  22. leftInclude bool
  23. right float64
  24. rightInclude bool
  25. }
  26. )
  27. func (o *fieldOptionsWithContext) fromString() bool {
  28. return o != nil && o.FromString
  29. }
  30. func (o *fieldOptionsWithContext) getDefault() (string, bool) {
  31. if o == nil {
  32. return "", false
  33. }
  34. return o.Default, len(o.Default) > 0
  35. }
  36. func (o *fieldOptionsWithContext) inherit() bool {
  37. return o != nil && o.Inherit
  38. }
  39. func (o *fieldOptionsWithContext) optional() bool {
  40. return o != nil && o.Optional
  41. }
  42. func (o *fieldOptionsWithContext) options() []string {
  43. if o == nil {
  44. return nil
  45. }
  46. return o.Options
  47. }
  48. func (o *fieldOptions) optionalDep() string {
  49. if o == nil {
  50. return ""
  51. }
  52. return o.OptionalDep
  53. }
  54. func (o *fieldOptions) toOptionsWithContext(key string, m Valuer, fullName string) (
  55. *fieldOptionsWithContext, error) {
  56. var optional bool
  57. if o.optional() {
  58. dep := o.optionalDep()
  59. if len(dep) == 0 {
  60. optional = true
  61. } else if dep[0] == notSymbol {
  62. dep = dep[1:]
  63. if len(dep) == 0 {
  64. return nil, fmt.Errorf("wrong optional value for %q in %q", key, fullName)
  65. }
  66. _, baseOn := m.Value(dep)
  67. _, selfOn := m.Value(key)
  68. if baseOn == selfOn {
  69. return nil, fmt.Errorf("set value for either %q or %q in %q", dep, key, fullName)
  70. }
  71. optional = baseOn
  72. } else {
  73. _, baseOn := m.Value(dep)
  74. _, selfOn := m.Value(key)
  75. if baseOn != selfOn {
  76. return nil, fmt.Errorf("values for %q and %q should be both provided or both not in %q",
  77. dep, key, fullName)
  78. }
  79. optional = !baseOn
  80. }
  81. }
  82. if o.fieldOptionsWithContext.Optional == optional {
  83. return &o.fieldOptionsWithContext, nil
  84. }
  85. return &fieldOptionsWithContext{
  86. FromString: o.FromString,
  87. Optional: optional,
  88. Options: o.Options,
  89. Default: o.Default,
  90. EnvVar: o.EnvVar,
  91. }, nil
  92. }