github.com/puellanivis/breton@v0.2.16/lib/gnuflag/slices.go (about)

     1  package gnuflag
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"strings"
     7  )
     8  
     9  type sliceValue struct {
    10  	value interface{} // this must be a pointer to the slice!
    11  	fn    func(s string) error
    12  }
    13  
    14  func newSlice(value interface{}, fn func(s string) error) sliceValue {
    15  	v := reflect.ValueOf(value)
    16  
    17  	if v.Kind() != reflect.Ptr {
    18  		panic(fmt.Sprintf("newSlice on non-pointer: %v", v.Kind()))
    19  	}
    20  
    21  	v = v.Elem()
    22  
    23  	if v.Kind() != reflect.Slice {
    24  		panic(fmt.Sprintf("newSlice on non-slice: %v", v.Kind()))
    25  	}
    26  
    27  	return sliceValue{
    28  		value: value,
    29  		fn:    fn,
    30  	}
    31  }
    32  
    33  func (a sliceValue) Set(s string) error {
    34  	for _, v := range strings.Split(s, ",") {
    35  		if err := a.fn(v); err != nil {
    36  			return err
    37  		}
    38  	}
    39  
    40  	return nil
    41  }
    42  
    43  func (a sliceValue) Get() interface{} {
    44  	v := reflect.ValueOf(a.value)
    45  
    46  	return v.Elem().Interface()
    47  }
    48  
    49  func (a sliceValue) String() string {
    50  	var elems []string
    51  
    52  	if a.value == nil {
    53  		// zero value
    54  		return ""
    55  	}
    56  
    57  	val := reflect.ValueOf(a.value).Elem()
    58  
    59  	for i := 0; i < val.Len(); i++ {
    60  		v := val.Index(i)
    61  		elems = append(elems, fmt.Sprint(v))
    62  	}
    63  
    64  	return strings.Join(elems, ",")
    65  }