...

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

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

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