github.com/GoogleCloudPlatform/compute-image-tools/cli_tools@v0.0.0-20240516224744-de2dabc4ed1b/common/utils/flags/key_value_flag.go (about)

     1  //  Copyright 2020 Google Inc. All Rights Reserved.
     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 flags
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  
    21  	"github.com/GoogleCloudPlatform/compute-image-tools/cli_tools/common/utils/param"
    22  )
    23  
    24  // KeyValueString is an implementation of flag.Value that creates a map
    25  // from the user's argument prior to storing it.
    26  type KeyValueString map[string]string
    27  
    28  // String returns string representation of KeyValueString.
    29  // The format of the return value is "KEY1=AB,KEY2=CD"
    30  func (s KeyValueString) String() string {
    31  	var parts []string
    32  	for k, v := range s {
    33  		parts = append(parts, fmt.Sprintf("%s=%s", k, v))
    34  	}
    35  	return strings.Join(parts, ",")
    36  }
    37  
    38  // Set creates a key-value map of the input string.
    39  // The input string must be in the format of KEY1=AB,KEY2=CD
    40  func (s *KeyValueString) Set(input string) error {
    41  	if *s != nil {
    42  		return fmt.Errorf("only one instance of this flag is allowed")
    43  	}
    44  
    45  	*s = make(map[string]string)
    46  	if input != "" {
    47  		var err error
    48  		*s, err = param.ParseKeyValues(input)
    49  		if err != nil {
    50  			return err
    51  		}
    52  	}
    53  	return nil
    54  }