github.com/tommi2day/gomodules@v1.13.2-0.20240423190010-b7d55d252a27/common/common.go (about)

     1  // Package common collection of small utils
     2  package common
     3  
     4  import (
     5  	"bytes"
     6  	"io"
     7  	"os"
     8  	"os/exec"
     9  	"reflect"
    10  	"regexp"
    11  	"time"
    12  	"unicode"
    13  
    14  	log "github.com/sirupsen/logrus"
    15  )
    16  
    17  const osWin = "windows"
    18  
    19  func init() {
    20  	// use text formatter
    21  	// log.SetFormatter(&log.TextFormatter{})
    22  
    23  	// Output to stdout instead of the default stderr
    24  	// Can be any io.Writer, see below for File example
    25  	log.SetOutput(os.Stdout)
    26  
    27  	// Only log the warning severity or above.
    28  	log.SetLevel(log.WarnLevel)
    29  }
    30  
    31  // GetEnv read an OS Env variable
    32  func GetEnv(key, fallback string) string {
    33  	if value, ok := os.LookupEnv(key); ok {
    34  		return value
    35  	}
    36  	return fallback
    37  }
    38  
    39  // GetStringEnv read an OS Env variable
    40  func GetStringEnv(key string, fallback string) string {
    41  	return GetEnv(key, fallback)
    42  }
    43  
    44  // GetBoolEnv read an OS Env variable and convert to bool
    45  func GetBoolEnv(key string, fallback bool) bool {
    46  	if value, ok := os.LookupEnv(key); ok {
    47  		if b, err := GetBoolVal(value); err == nil {
    48  			return b
    49  		}
    50  	}
    51  	return fallback
    52  }
    53  
    54  // GetIntEnv read an OS Env variable and convert to int
    55  func GetIntEnv(key string, fallback int) int {
    56  	if value, ok := os.LookupEnv(key); ok {
    57  		if i, err := GetIntVal(value); err == nil {
    58  			return i
    59  		}
    60  	}
    61  	return fallback
    62  }
    63  
    64  // GetFloatEnv read an OS Env variable and convert to float64
    65  func GetFloatEnv(key string, fallback float64) float64 {
    66  	if value, ok := os.LookupEnv(key); ok {
    67  		if i, err := GetFloatVal(value); err == nil {
    68  			return i
    69  		}
    70  	}
    71  	return fallback
    72  }
    73  
    74  // CheckSkip checks if a line can be skipped
    75  func CheckSkip(line string) (skip bool) {
    76  	skip = true
    77  	found := false
    78  	reEmpty := regexp.MustCompile(`\S`)
    79  	reComment := regexp.MustCompile(`^#`)
    80  	found = reEmpty.MatchString(line)
    81  	if !found {
    82  		return
    83  	}
    84  	found = reComment.MatchString(line)
    85  	if found {
    86  		return
    87  	}
    88  	skip = false
    89  	return
    90  }
    91  
    92  // RemoveSpace deletes all spaces and newlines from string
    93  func RemoveSpace(s string) string {
    94  	rr := make([]rune, 0, len(s))
    95  	for _, r := range s {
    96  		if !unicode.IsSpace(r) {
    97  			rr = append(rr, r)
    98  		}
    99  	}
   100  	return string(rr)
   101  }
   102  
   103  // CommandExists checks if a command exists in PATH
   104  func CommandExists(command string) bool {
   105  	log.Debugf("checking if command %s exists", command)
   106  	p, err := exec.LookPath(command)
   107  	if err != nil {
   108  		log.Debugf("%s not found in PATH: %v", command, err)
   109  		return false
   110  	}
   111  	log.Debugf("command %s found as: %s", command, p)
   112  	return true
   113  }
   114  
   115  // ExecuteOsCommand runs an OS command and returns output
   116  func ExecuteOsCommand(cmdArgs []string, stdIn io.Reader) (stdOut string, stdErr string, err error) {
   117  	var cmdOut bytes.Buffer
   118  	var cmdErr bytes.Buffer
   119  	//nolint gosec
   120  	cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
   121  	cmdOut.Reset()
   122  	cmdErr.Reset()
   123  	cmd.Stdout = &cmdOut
   124  	cmd.Stderr = &cmdErr
   125  	cmd.Stdin = stdIn
   126  	err = cmd.Run()
   127  	stdOut = cmdOut.String()
   128  	stdErr = cmdErr.String()
   129  	return
   130  }
   131  
   132  // InArray will search element inside array with any type.
   133  // Will return boolean and index for matched element.
   134  // True and index more than 0 if element is exist.
   135  // needle is element to search, haystack is slice of value to be search.
   136  // Taken from https://github.com/SimonWaldherr/golang-examples/blob/master/advanced/in_array.go
   137  func InArray(needle interface{}, haystack interface{}) (exists bool, index int) {
   138  	exists = false
   139  	index = -1
   140  	if reflect.TypeOf(haystack).Kind() == reflect.Slice {
   141  		s := reflect.ValueOf(haystack)
   142  		for i := 0; i < s.Len(); i++ {
   143  			if reflect.DeepEqual(needle, s.Index(i).Interface()) {
   144  				index = i
   145  				exists = true
   146  				return
   147  			}
   148  		}
   149  	}
   150  	return
   151  }
   152  
   153  // FormatUnixtsString converts a unix timestamp string to a human readable
   154  func FormatUnixtsString(ts string, layout string) string {
   155  	if !IsNumeric(ts) {
   156  		return ts
   157  	}
   158  	timestamp, err := GetInt64Val(ts)
   159  	if err != nil {
   160  		return ts
   161  	}
   162  	return time.Unix(timestamp, 0).Format(layout)
   163  }