...

Source file src/k8s.io/component-base/cli/flag/string_slice_flag.go

Documentation: k8s.io/component-base/cli/flag

     1  /*
     2  Copyright 2021 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package flag
    18  
    19  import (
    20  	goflag "flag"
    21  	"fmt"
    22  	"strings"
    23  
    24  	"github.com/spf13/pflag"
    25  )
    26  
    27  // StringSlice implements goflag.Value and plfag.Value,
    28  // and allows set to be invoked repeatedly to accumulate values.
    29  type StringSlice struct {
    30  	value   *[]string
    31  	changed bool
    32  }
    33  
    34  func NewStringSlice(s *[]string) *StringSlice {
    35  	return &StringSlice{value: s}
    36  }
    37  
    38  var _ goflag.Value = &StringSlice{}
    39  var _ pflag.Value = &StringSlice{}
    40  
    41  func (s *StringSlice) String() string {
    42  	if s == nil || s.value == nil {
    43  		return ""
    44  	}
    45  	return strings.Join(*s.value, " ")
    46  }
    47  
    48  func (s *StringSlice) Set(val string) error {
    49  	if s.value == nil {
    50  		return fmt.Errorf("no target (nil pointer to []string)")
    51  	}
    52  	if !s.changed {
    53  		*s.value = make([]string, 0)
    54  	}
    55  	*s.value = append(*s.value, val)
    56  	s.changed = true
    57  	return nil
    58  }
    59  
    60  func (StringSlice) Type() string {
    61  	return "sliceString"
    62  }
    63  

View as plain text