...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/flags/flags.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/flags

     1  // Copyright 2019 Chaos Mesh 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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package flags
    15  
    16  import (
    17  	"fmt"
    18  	"strings"
    19  )
    20  
    21  // MapStringStringFlag is a flag struct for key=value pairs
    22  type MapStringStringFlag struct {
    23  	Values map[string]string
    24  }
    25  
    26  // String implements the flag.Var interface
    27  func (s *MapStringStringFlag) String() string {
    28  	z := []string{}
    29  	for x, y := range s.Values {
    30  		z = append(z, fmt.Sprintf("%s=%s", x, y))
    31  	}
    32  	return strings.Join(z, ",")
    33  }
    34  
    35  // Set implements the flag.Var interface
    36  func (s *MapStringStringFlag) Set(value string) error {
    37  	if s.Values == nil {
    38  		s.Values = map[string]string{}
    39  	}
    40  	for _, p := range strings.Split(value, ",") {
    41  		fields := strings.Split(p, "=")
    42  		if len(fields) != 2 {
    43  			return fmt.Errorf("%s is incorrectly formatted! should be key=value[,key2=value2]", p)
    44  		}
    45  		s.Values[fields[0]] = fields[1]
    46  	}
    47  	return nil
    48  }
    49  
    50  // ToMapStringString returns the underlying representation of the map of key=value pairs
    51  func (s *MapStringStringFlag) ToMapStringString() map[string]string {
    52  	return s.Values
    53  }
    54  
    55  // NewMapStringStringFlag creates a new flag var for storing key=value pairs
    56  func NewMapStringStringFlag() MapStringStringFlag {
    57  	return MapStringStringFlag{Values: map[string]string{}}
    58  }
    59