explicitflags.go raw

   1  package cfgutil
   2  
   3  // ExplicitString is a string value implementing the flags.Marshaler and flags.Unmarshaler interfaces so it may be used
   4  // as a config struct field. It records whether the value was explicitly set by the flags package.
   5  //
   6  // This is useful when behavior must be modified depending on whether a flag was set by the user or left as a default.
   7  //
   8  // Without recording this, it would be impossible to determine whether flag with a default value was unmodified or
   9  // explicitly set to the default.
  10  type ExplicitString struct {
  11  	Value         string
  12  	explicitlySet bool
  13  }
  14  
  15  // NewExplicitString creates a string flag with the provided default value.
  16  func NewExplicitString(defaultValue string) *ExplicitString {
  17  	return &ExplicitString{Value: defaultValue, explicitlySet: false}
  18  }
  19  
  20  // ExplicitlySet returns whether the flag was explicitly set through the flags.Unmarshaler interface.
  21  func (es *ExplicitString) ExplicitlySet() bool { return es.explicitlySet }
  22  
  23  // MarshalFlag implements the flags.Marshaler interface.
  24  func (es *ExplicitString) MarshalFlag() (string, error) {
  25  	return es.Value, nil
  26  }
  27  
  28  // UnmarshalFlag implements the flags.Unmarshaler interface.
  29  func (es *ExplicitString) UnmarshalFlag(value string) (e error) {
  30  	es.Value = value
  31  	es.explicitlySet = true
  32  	return nil
  33  }
  34