|
|
| package utils
|
|
|
| import (
|
| "fmt"
|
| "io"
|
| "math"
|
| "os"
|
| "os/exec"
|
| "path/filepath"
|
| "runtime"
|
| "strconv"
|
| "strings"
|
| )
|
|
|
|
|
| func GetEnv(key string) (value string, exists bool) {
|
| if value, exists = os.LookupEnv("BESZEL_AGENT_" + key); exists {
|
| return value, exists
|
| }
|
| return os.LookupEnv(key)
|
| }
|
|
|
|
|
| func BytesToMegabytes(b float64) float64 {
|
| return TwoDecimals(b / 1048576)
|
| }
|
|
|
|
|
| func BytesToGigabytes(b uint64) float64 {
|
| return TwoDecimals(float64(b) / 1073741824)
|
| }
|
|
|
|
|
| func TwoDecimals(value float64) float64 {
|
| return math.Round(value*100) / 100
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| func ReadStringFile(path string) string {
|
| content, _ := ReadStringFileOK(path)
|
| return content
|
| }
|
|
|
|
|
| func ReadStringFileOK(path string) (string, bool) {
|
| b, err := os.ReadFile(path)
|
| if err != nil {
|
| return "", false
|
| }
|
| return strings.TrimSpace(string(b)), true
|
| }
|
|
|
|
|
|
|
| func ReadStringFileLimited(path string, maxSize int) (string, error) {
|
| f, err := os.Open(path)
|
| if err != nil {
|
| return "", err
|
| }
|
| defer f.Close()
|
|
|
| buf := make([]byte, maxSize)
|
| n, err := f.Read(buf)
|
| if err != nil && err != io.EOF {
|
| return "", err
|
| }
|
| if n < 0 {
|
| return "", fmt.Errorf("%s returned negative bytes: %d", path, n)
|
| }
|
| return strings.TrimSpace(string(buf[:n])), nil
|
| }
|
|
|
|
|
| func FileExists(path string) bool {
|
| _, err := os.Stat(path)
|
| return err == nil
|
| }
|
|
|
|
|
| func ReadUintFile(path string) (uint64, bool) {
|
| raw, ok := ReadStringFileOK(path)
|
| if !ok {
|
| return 0, false
|
| }
|
| parsed, err := strconv.ParseUint(raw, 10, 64)
|
| if err != nil {
|
| return 0, false
|
| }
|
| return parsed, true
|
| }
|
|
|
|
|
| func LookPathHomebrew(file string) (string, error) {
|
| foundPath, lookPathErr := exec.LookPath(file)
|
| if lookPathErr == nil {
|
| return foundPath, nil
|
| }
|
| var homebrewPath string
|
| switch runtime.GOOS {
|
| case "darwin":
|
| homebrewPath = filepath.Join("/opt", "homebrew", "bin", file)
|
| case "linux":
|
| homebrewPath = filepath.Join("/home", "linuxbrew", ".linuxbrew", "bin", file)
|
| }
|
| if homebrewPath != "" {
|
| if _, err := os.Stat(homebrewPath); err == nil {
|
| return homebrewPath, nil
|
| }
|
| }
|
| return "", lookPathErr
|
| }
|
|
|