github.com/searKing/golang/go@v1.2.117/flag/string_slice.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package flag
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  	"sync"
    11  )
    12  
    13  // StringSliceVarWithFlagSet defines a []string flag with specified name, default value, and usage string.
    14  // The argument p points to a []string variable in which to store the value of the flag.
    15  func StringSliceVarWithFlagSet(f *flag.FlagSet, p *[]string, name string, value []string, usage string) {
    16  	f.Var(newStringSliceValue(value, p), name, usage)
    17  }
    18  
    19  // StringSliceWithFlagSet defines an []string flag with specified name, default value, and usage string.
    20  // The return value is the address of a []string variable that stores the value of the flag.
    21  func StringSliceWithFlagSet(f *flag.FlagSet, name string, value []string, usage string) *[]string {
    22  	p := new([]string)
    23  	StringSliceVarWithFlagSet(f, p, name, value, usage)
    24  	return p
    25  }
    26  
    27  // StringSliceVar defines a []string flag with specified name, default value, and usage string.
    28  // The argument p points to a []string variable in which to store the value of the flag.
    29  func StringSliceVar(p *[]string, name string, value []string, usage string) {
    30  	flag.CommandLine.Var(newStringSliceValue(value, p), name, usage)
    31  }
    32  
    33  // StringSlice defines an []string flag with specified name, default value, and usage string.
    34  // The return value is the address of a []string variable that stores the value of the flag.
    35  func StringSlice(name string, value []string, usage string) *[]string {
    36  	return StringSliceWithFlagSet(flag.CommandLine, name, value, usage)
    37  }
    38  
    39  // stringSliceValue is a flag.Value that accumulates strings.
    40  // e.g. --flag=one --flag=two would produce []string{"one", "two"}.
    41  type stringSliceValue struct {
    42  	vars *[]string
    43  	once sync.Once
    44  }
    45  
    46  func newStringSliceValue(val []string, p *[]string) *stringSliceValue {
    47  	*p = val
    48  	return &stringSliceValue{vars: p}
    49  }
    50  
    51  func (ss *stringSliceValue) Get() any { return *(ss.vars) }
    52  
    53  func (ss *stringSliceValue) String() string {
    54  	if ss.vars == nil {
    55  		return "[]"
    56  	}
    57  	return fmt.Sprintf("%q", *(ss.vars))
    58  }
    59  
    60  func (ss *stringSliceValue) Set(s string) error {
    61  	ss.once.Do(func() {
    62  		*(ss.vars) = (*(ss.vars))[0:0]
    63  	})
    64  	*(ss.vars) = append(*(ss.vars), s)
    65  	return nil
    66  }