go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/strmap.go (about)

     1  // Copyright 2016 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  	"sort"
    21  	"strings"
    22  
    23  	"go.chromium.org/luci/common/errors"
    24  )
    25  
    26  type strMapFlag map[string]string
    27  
    28  // StringMap returns a flag.Getter for parsing map[string]string from a
    29  // a set of colon-separated strings.
    30  // Example:
    31  //
    32  //	-f a:1 -f b:3
    33  //
    34  // The flag.Getter.Set implementation returns an error if the key is already
    35  // in the map.
    36  // Panics if m is nil.
    37  func StringMap(m map[string]string) flag.Getter {
    38  	if m == nil {
    39  		panic("m is nil")
    40  	}
    41  	return strMapFlag(m)
    42  }
    43  
    44  func (f strMapFlag) String() string {
    45  	// This encoding is lossy. It is optimized for readability.
    46  	pairs := make([]string, 0, len(f))
    47  	for k, v := range f {
    48  		pairs = append(pairs, fmt.Sprintf("%s:%s", k, v))
    49  	}
    50  	sort.Strings(pairs)
    51  	return strings.Join(pairs, " ")
    52  }
    53  
    54  func (f strMapFlag) Set(s string) error {
    55  	parts := strings.SplitN(s, ":", 2)
    56  	if len(parts) == 1 {
    57  		return fmt.Errorf("no colon")
    58  	}
    59  	key := parts[0]
    60  	value := parts[1]
    61  	if _, ok := f[key]; ok {
    62  		return errors.Reason("key %q is already specified", key).Err()
    63  	}
    64  	f[key] = value
    65  	return nil
    66  }
    67  
    68  func (f strMapFlag) Get() any {
    69  	return map[string]string(f)
    70  }