pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/options/arguments.go (about)

     1  package options
     2  
     3  // ////////////////////////////////////////////////////////////////////////////////// //
     4  //                                                                                    //
     5  //                         Copyright (c) 2022 ESSENTIAL KAOS                          //
     6  //      Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>     //
     7  //                                                                                    //
     8  // ////////////////////////////////////////////////////////////////////////////////// //
     9  
    10  import (
    11  	"fmt"
    12  	"strconv"
    13  	"strings"
    14  )
    15  
    16  // ////////////////////////////////////////////////////////////////////////////////// //
    17  
    18  type Arguments []string
    19  
    20  // ////////////////////////////////////////////////////////////////////////////////// //
    21  
    22  // Has returns true if arguments contains argument with given index
    23  func (a Arguments) Has(index int) bool {
    24  	return index < len(a) && a[index] != ""
    25  }
    26  
    27  // Get returns argument with given index
    28  func (a Arguments) Get(index int) string {
    29  	if index >= len(a) {
    30  		return ""
    31  	}
    32  
    33  	return a[index]
    34  }
    35  
    36  // GetI returns argument with given index as int
    37  func (a Arguments) GetI(index int) (int, error) {
    38  	v := a.Get(index)
    39  	return strconv.Atoi(v)
    40  }
    41  
    42  // GetF returns argument with given index as float
    43  func (a Arguments) GetF(index int) (float64, error) {
    44  	v := a.Get(index)
    45  	return strconv.ParseFloat(v, 64)
    46  }
    47  
    48  // GetB returns argument with given index as bool
    49  func (a Arguments) GetB(index int) (bool, error) {
    50  	v := a.Get(index)
    51  	switch strings.ToLower(v) {
    52  	case "true", "yes", "y", "1":
    53  		return true, nil
    54  	case "false", "no", "n", "0", "":
    55  		return false, nil
    56  	default:
    57  		return false, fmt.Errorf("Unsupported boolean value \"%s\"", v)
    58  	}
    59  }