github.com/kat-co/cmd@v0.0.0-20140616103059-5da365f9d57e/args.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package cmd
     5  
     6  import (
     7  	"strings"
     8  
     9  	"launchpad.net/gnuflag"
    10  )
    11  
    12  // StringsValue implements gnuflag.Value for a comma separated list of
    13  // strings.  This allows flags to be created where the target is []string, and
    14  // the caller is after comma separated values.
    15  type StringsValue []string
    16  
    17  var _ gnuflag.Value = (*StringsValue)(nil)
    18  
    19  // NewStringsValue is used to create the type passed into the gnuflag.FlagSet Var function.
    20  // f.Var(cmd.NewStringsValue(defaultValue, &someMember), "name", "help")
    21  func NewStringsValue(defaultValue []string, target *[]string) *StringsValue {
    22  	value := (*StringsValue)(target)
    23  	*value = defaultValue
    24  	return value
    25  }
    26  
    27  // Implements gnuflag.Value Set.
    28  func (v *StringsValue) Set(s string) error {
    29  	*v = strings.Split(s, ",")
    30  	return nil
    31  }
    32  
    33  // Implements gnuflag.Value String.
    34  func (v *StringsValue) String() string {
    35  	return strings.Join(*v, ",")
    36  }
    37  
    38  // AppendStringsValue implements gnuflag.Value for a value that can be set
    39  // multiple times, and it appends each value to the slice.
    40  type AppendStringsValue []string
    41  
    42  var _ gnuflag.Value = (*AppendStringsValue)(nil)
    43  
    44  // NewAppendStringsValue is used to create the type passed into the gnuflag.FlagSet Var function.
    45  // f.Var(cmd.NewAppendStringsValue(&someMember), "name", "help")
    46  func NewAppendStringsValue(target *[]string) *AppendStringsValue {
    47  	return (*AppendStringsValue)(target)
    48  }
    49  
    50  // Implements gnuflag.Value Set.
    51  func (v *AppendStringsValue) Set(s string) error {
    52  	*v = append(*v, s)
    53  	return nil
    54  }
    55  
    56  // Implements gnuflag.Value String.
    57  func (v *AppendStringsValue) String() string {
    58  	return strings.Join(*v, ",")
    59  }