github.com/haraldrudell/parl@v0.4.176/pflags/string-slice-value.go (about)

     1  /*
     2  © 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pflags
     7  
     8  import (
     9  	"flag"
    10  	"strings"
    11  )
    12  
    13  /*
    14  type Value interface {
    15  	String() string
    16  	Set(string) error
    17  }
    18  */
    19  
    20  // StringSliceValue manages a string-slice value for [flag.Var]
    21  type StringSliceValue struct {
    22  	providedStringsp *[]string
    23  	// didUpdate allows to erase the default value on first Set invocation
    24  	//	- on first provided option, any default strings should be discarded
    25  	didUpdate bool
    26  }
    27  
    28  // NewStringSliceValue initializes a slice option
    29  //   - the option’s value is stored in a slice at slicePointer
    30  //   - defaultValue may be nil
    31  //   - [flag.Value] is an interface of the flag package storing non-standard value types
    32  func NewStringSliceValue(slicePointer *[]string, defaultValue []string) (v flag.Value) {
    33  	*slicePointer = append([]string{}, defaultValue...)
    34  	v = &StringSliceValue{providedStringsp: slicePointer}
    35  	return
    36  }
    37  
    38  // Set updates the string slice
    39  //   - Set is invoked once for each option-occurrence in the command line
    40  //   - Set appends each such option value to its list of strings
    41  func (v *StringSliceValue) Set(optionValue string) (err error) {
    42  	if !v.didUpdate {
    43  		v.didUpdate = true
    44  		*v.providedStringsp = nil // clear the slice
    45  	}
    46  	*v.providedStringsp = append(*v.providedStringsp, optionValue)
    47  
    48  	return
    49  }
    50  
    51  // StringSliceValue implements flag.Value
    52  //   - type Value interface { String() string; Set(string) error }
    53  var _ flag.Value = &StringSliceValue{}
    54  
    55  // flag package invoke String to render default value
    56  func (v StringSliceValue) String() (s string) {
    57  	if stringSlicep := v.providedStringsp; stringSlicep != nil {
    58  		s = strings.Join(*stringSlicep, "\x20")
    59  	}
    60  	return
    61  }