github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/flag/map.go (about)

     1  // Copyright (c) 2019 Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package flag
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  )
    11  
    12  // Map is a type used to provide mapped options via command line flags.
    13  // It implements the flag.Value interface.
    14  // If a flag is passed without a value, for example: `-option somebool` it will still be
    15  // initialized, so you can use `_, ok := option["somebool"]` to check if it exists.
    16  type Map map[string]string
    17  
    18  // String is the method to format the flag's value, part of the flag.Value interface.
    19  // The String method's output is used in diagnostics.
    20  func (o Map) String() string {
    21  	return fmt.Sprintf("%#v", o)
    22  }
    23  
    24  // Set is the method to set the flag value, part of the flag.Value interface.
    25  // Set's argument is a string to be parsed to set the flag.
    26  // It still initializes flags that don't explicitly set a string
    27  func (o Map) Set(value string) error {
    28  	var k, v string
    29  	idx := strings.Index(value, "=")
    30  	if idx == -1 {
    31  		k = value
    32  	} else {
    33  		k = value[:idx]
    34  		v = value[idx+1:]
    35  	}
    36  	if _, exists := o[k]; exists {
    37  		return fmt.Errorf("%v is a duplicate option", k)
    38  	}
    39  
    40  	o[k] = v
    41  	return nil
    42  }
    43  
    44  // Type returns the golang type string. This method is required by pflag library.
    45  func (o Map) Type() string {
    46  	return "Map"
    47  }
    48  
    49  // Clone returns a copy of flag options
    50  func (o Map) Clone() Map {
    51  	options := make(Map, len(o))
    52  	for k, v := range o {
    53  		options[k] = v
    54  	}
    55  	return options
    56  }