github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/flagutil/strings.go (about) 1 /* 2 Copyright 2018 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 flagutil 18 19 import ( 20 "strings" 21 22 "k8s.io/apimachinery/pkg/util/sets" 23 ) 24 25 // Strings represents the value of a flag that accept multiple strings. 26 type Strings struct { 27 vals []string 28 beenSet bool 29 } 30 31 // NewStrings returns a Strings struct that defaults to the value of def if left unset. 32 func NewStrings(def ...string) Strings { 33 return Strings{ 34 vals: def, 35 beenSet: false, 36 } 37 } 38 39 // NewStringsBeenSet returns a Strings struct with beenSet: true 40 func NewStringsBeenSet(def ...string) Strings { 41 return Strings{ 42 vals: def, 43 beenSet: true, 44 } 45 } 46 47 // Strings returns the slice of strings set for this value instance. 48 func (s *Strings) Strings() []string { 49 return s.vals 50 } 51 52 // StringSet returns a sets.Set[string] of strings set for this value instance. 53 func (s *Strings) StringSet() sets.Set[string] { 54 return sets.New[string](s.Strings()...) 55 } 56 57 // String returns a concatenated string of all the values joined by commas. 58 func (s *Strings) String() string { 59 return strings.Join(s.vals, ",") 60 } 61 62 // Set records the value passed, overwriting the defaults (if any) 63 func (s *Strings) Set(value string) error { 64 if !s.beenSet { 65 s.beenSet = true 66 // Value is being set, don't use default. 67 s.vals = nil 68 } 69 s.vals = append(s.vals, value) 70 return nil 71 } 72 73 // Add records the value passes, adding to the defaults (if any) 74 func (s *Strings) Add(value string) { 75 s.vals = append(s.vals, value) 76 }