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

     1  //  Copyright 2019 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 param
    16  
    17  import (
    18  	"strings"
    19  
    20  	daisy "github.com/GoogleCloudPlatform/compute-daisy"
    21  )
    22  
    23  // ParseKeyValues parses a comma-separated list of [key=value] pairs.
    24  func ParseKeyValues(keyValues string) (map[string]string, error) {
    25  	labelsMap := make(map[string]string)
    26  	splits := strings.Split(keyValues, ",")
    27  	for _, split := range splits {
    28  		if len(split) == 0 {
    29  			continue
    30  		}
    31  		key, value, err := parseKeyValue(split)
    32  		if err != nil {
    33  			return nil, err
    34  		}
    35  		labelsMap[key] = value
    36  	}
    37  	return labelsMap, nil
    38  }
    39  
    40  func parseKeyValue(keyValueSplit string) (string, string, daisy.DError) {
    41  	splits := strings.Split(keyValueSplit, "=")
    42  	if len(splits) != 2 {
    43  		return "", "", daisy.Errf("failed to parse key-value pair. key-value should be in the following format: KEY=VALUE, but it's %v", keyValueSplit)
    44  	}
    45  	key := strings.TrimSpace(splits[0])
    46  	value := strings.TrimSpace(splits[1])
    47  	if len(key) == 0 {
    48  		return "", "", daisy.Errf("failed to parse key-value pair. key is empty string: %v", keyValueSplit)
    49  	}
    50  	if len(value) == 0 {
    51  		return "", "", daisy.Errf("failed to parse key-value pair. value is empty string: %v", keyValueSplit)
    52  	}
    53  	return key, value, nil
    54  }