github.com/greenpau/go-authcrunch@v1.1.4/pkg/util/cfg/encoder.go (about)

     1  // Copyright 2022 Paul Greenberg greenpau@outlook.com
     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 cfg
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/csv"
    20  	"fmt"
    21  	"strings"
    22  )
    23  
    24  // ParseBoolArg converts string to boolean.
    25  func ParseBoolArg(s string) (bool, error) {
    26  	switch strings.ToLower(s) {
    27  	case "":
    28  		return false, fmt.Errorf("empty switch")
    29  	case "yes", "true", "on", "1":
    30  		return true, nil
    31  	case "no", "false", "off", "0":
    32  		return false, nil
    33  	}
    34  	return false, fmt.Errorf("invalid switch: %s", s)
    35  }
    36  
    37  // EncodeArgs encodes passed arguments.
    38  func EncodeArgs(args []string) string {
    39  	var b []byte
    40  	bb := bytes.NewBuffer(b)
    41  	w := csv.NewWriter(bb)
    42  	w.Comma = ' '
    43  	w.Write(args)
    44  	w.Flush()
    45  	s := string(bb.Bytes())
    46  	s = strings.TrimSpace(s)
    47  	return s
    48  }
    49  
    50  // DecodeArgs decode arguments from string.
    51  func DecodeArgs(s string) ([]string, error) {
    52  	s = strings.TrimSpace(s)
    53  	r := csv.NewReader(strings.NewReader(s))
    54  	r.Comma = ' '
    55  	args, err := r.Read()
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  	if len(args) == 0 {
    60  		return nil, fmt.Errorf("empty")
    61  	}
    62  	return args, err
    63  }
    64  
    65  // Contains returns true if a value is in a slice.
    66  func Contains(arr []string, s string) bool {
    67  	for _, entry := range arr {
    68  		if entry == s {
    69  			return true
    70  		}
    71  	}
    72  	return false
    73  }