github.com/openebs/api@v1.12.0/pkg/util/util.go (about)

     1  /*
     2  Copyright 2020 The OpenEBS Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"os"
    23  	"strconv"
    24  	"strings"
    25  
    26  	"k8s.io/klog"
    27  )
    28  
    29  var (
    30  	// ErrMAPIADDRNotSet is the new error to display this error if MAPI_ADDR is not set.
    31  	ErrMAPIADDRNotSet = errors.New("MAPI_ADDR environment variable not set")
    32  	// ErrInternalServerError is the new error to raise if an error occurs while rendering the service
    33  	ErrInternalServerError = errors.New("Internal Server Error")
    34  	// ErrServerUnavailable is the new error to raise if the server is not available
    35  	ErrServerUnavailable = errors.New("Server Unavailable")
    36  	// ErrServerNotReachable is the new error to raise if the server is not reachable
    37  	ErrServerNotReachable = errors.New("Server Not Reachable")
    38  	// ErrPageNotFound is the new error to raise if the page is not found
    39  	ErrPageNotFound = errors.New("Page Not Found")
    40  )
    41  
    42  // truthyValues maps a set of values which are considered as true
    43  var truthyValues = map[string]bool{
    44  	"1":       true,
    45  	"YES":     true,
    46  	"TRUE":    true,
    47  	"OK":      true,
    48  	"ENABLED": true,
    49  	"ON":      true,
    50  }
    51  
    52  // CheckTruthy checks for truthiness of the passed argument.
    53  func CheckTruthy(truth string) bool {
    54  	return truthyValues[strings.ToUpper(truth)]
    55  }
    56  
    57  // falsyValues maps a set of values which are considered as false
    58  var falsyValues = map[string]bool{
    59  	"0":        true,
    60  	"NO":       true,
    61  	"FALSE":    true,
    62  	"BLANK":    true,
    63  	"DISABLED": true,
    64  	"OFF":      true,
    65  }
    66  
    67  // CheckFalsy checks for non-truthiness of the passed argument.
    68  func CheckFalsy(falsy string) bool {
    69  	if len(falsy) == 0 {
    70  		falsy = "blank"
    71  	}
    72  	return falsyValues[strings.ToUpper(falsy)]
    73  }
    74  
    75  // CheckErr to handle command errors
    76  func CheckErr(err error, handleErr func(string)) {
    77  	if err == nil {
    78  		return
    79  	}
    80  	handleErr(err.Error())
    81  }
    82  
    83  // Fatal prints the message (if provided) and then exits. If V(2) or greater,
    84  // klog.Fatal is invoked for extended information.
    85  func Fatal(msg string) {
    86  	if klog.V(2) {
    87  		klog.FatalDepth(2, msg)
    88  	}
    89  	if len(msg) > 0 {
    90  		// add newline if needed
    91  		if !strings.HasSuffix(msg, "\n") {
    92  			msg += "\n"
    93  		}
    94  		fmt.Fprint(os.Stderr, msg)
    95  	}
    96  	os.Exit(1)
    97  }
    98  
    99  // StringToInt32 converts a string type to corresponding
   100  // *int32 type
   101  func StringToInt32(val string) (*int32, error) {
   102  	if len(val) == 0 {
   103  		return nil, fmt.Errorf("Nil value to convert")
   104  	}
   105  
   106  	n, err := strconv.ParseInt(val, 10, 32)
   107  	if err != nil {
   108  		return nil, err
   109  	}
   110  	n32 := int32(n)
   111  	return &n32, nil
   112  }
   113  
   114  // StrToInt32 converts a string type to corresponding
   115  // *int32 type
   116  //
   117  // NOTE:
   118  //  This swallows the error if any
   119  func StrToInt32(val string) *int32 {
   120  	n32, _ := StringToInt32(val)
   121  	return n32
   122  }
   123  
   124  // ContainsString returns true if the provided element is present in the
   125  // provided array
   126  func ContainsString(stringarr []string, element string) bool {
   127  	for _, elem := range stringarr {
   128  		if elem == element {
   129  			return true
   130  		}
   131  	}
   132  	return false
   133  }
   134  
   135  //TODO: Make better enhancement
   136  
   137  // ListDiff returns list of string which are in listA but not in listB
   138  func ListDiff(listA []string, listB []string) []string {
   139  	outputList := []string{}
   140  	mapListB := map[string]bool{}
   141  	for _, str := range listB {
   142  		mapListB[str] = true
   143  	}
   144  	for _, str := range listA {
   145  		if !mapListB[str] {
   146  			outputList = append(outputList, str)
   147  		}
   148  	}
   149  	return outputList
   150  }
   151  
   152  // ListIntersection returns list of string which are in listA and listB
   153  func ListIntersection(listA []string, listB []string) []string {
   154  	outputList := []string{}
   155  	mapListB := map[string]bool{}
   156  	for _, str := range listB {
   157  		mapListB[str] = true
   158  	}
   159  	for _, str := range listA {
   160  		if mapListB[str] {
   161  			outputList = append(outputList, str)
   162  		}
   163  	}
   164  	return outputList
   165  }
   166  
   167  // ContainsKey returns true if the provided key is present in the provided map
   168  func ContainsKey(mapOfObjs map[string]interface{}, key string) bool {
   169  	for k := range mapOfObjs {
   170  		if k == key {
   171  			return true
   172  		}
   173  	}
   174  	return false
   175  }
   176  
   177  // ContainKeys returns true if all the provided keys are present in the
   178  // provided map
   179  func ContainKeys(mapOfObjs map[string]interface{}, keys []string) bool {
   180  	if len(keys) == 0 || len(mapOfObjs) == 0 {
   181  		return false
   182  	}
   183  
   184  	allKeys := []string{}
   185  	for k := range mapOfObjs {
   186  		allKeys = append(allKeys, k)
   187  	}
   188  
   189  	for _, expectedKey := range keys {
   190  		if !ContainsString(allKeys, expectedKey) {
   191  			return false
   192  		}
   193  	}
   194  
   195  	return true
   196  }
   197  
   198  // MergeMaps merges maps and returns the resulting map.
   199  // map priority increases with order i.e. MergeMaps(m1,m2)
   200  // will result in a map with overriding values from m2
   201  func MergeMaps(maps ...map[string]interface{}) map[string]interface{} {
   202  	result := make(map[string]interface{})
   203  	for _, m := range maps {
   204  		for k, v := range m {
   205  			result[k] = v
   206  		}
   207  	}
   208  	return result
   209  }
   210  
   211  // RemoveString removes all occurrences of a string from slice
   212  // and returns a new updated slice
   213  func RemoveString(slice []string, s string) (result []string) {
   214  	for _, item := range slice {
   215  		if item != s {
   216  			result = append(result, item)
   217  		}
   218  	}
   219  	return result
   220  }
   221  
   222  // IsChangeInLists returns true if there is any difference in listA and listB
   223  func IsChangeInLists(listA, listB []string) bool {
   224  	listAMap := map[string]bool{}
   225  	listBMap := map[string]bool{}
   226  	for _, name := range listA {
   227  		listAMap[name] = true
   228  	}
   229  	for _, name := range listB {
   230  		listBMap[name] = true
   231  	}
   232  	for _, name := range listA {
   233  		if !listBMap[name] {
   234  			return true
   235  		}
   236  	}
   237  	for _, name := range listB {
   238  		if !listAMap[name] {
   239  			return true
   240  		}
   241  	}
   242  	return false
   243  }