go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/strpairs.go (about) 1 // Copyright 2018 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package flag 16 17 import ( 18 "flag" 19 "fmt" 20 "strings" 21 22 "go.chromium.org/luci/common/data/strpair" 23 ) 24 25 // strpairsFlag implements the flag.Getter returned by StrPairs. 26 type stringPairsFlag strpair.Map 27 28 // StringPairs returns a flag.Getter for parsing strpair.Map from a 29 // a set of colon-separated strings. 30 // Example: 31 // 32 // "-f a:1" 33 // "-f a:2" 34 // "-f b:3:3" (The value contains a colon ":") 35 // 36 // Panics if m is nil. 37 func StringPairs(m strpair.Map) flag.Getter { 38 if m == nil { 39 panic("m is nil") 40 } 41 return stringPairsFlag(m) 42 } 43 44 // String implements the flag.Value interface. 45 func (f stringPairsFlag) String() string { 46 return strings.Join(strpair.Map(f).Format(), ", ") 47 } 48 49 // Set implements the flag.Value interface. 50 func (f stringPairsFlag) Set(s string) error { 51 // Splits the string into at most two parts by the first colon ":" because 52 // the value part might contain a colon ":". 53 parts := strings.SplitN(s, ":", 2) 54 if len(parts) == 1 { 55 return fmt.Errorf("no colon") 56 } 57 strpair.Map(f).Add(parts[0], parts[1]) 58 return nil 59 } 60 61 // Get retrieves the flag value. 62 func (f stringPairsFlag) Get() any { 63 return strpair.Map(f) 64 }