github.com/jaypipes/ghw@v0.21.1/pkg/util/util.go (about)

     1  //
     2  // Use and distribution licensed under the Apache license version 2.
     3  //
     4  // See the COPYING file in the root project directory for full text.
     5  //
     6  
     7  package util
     8  
     9  import (
    10  	"fmt"
    11  	"os"
    12  	"strconv"
    13  	"strings"
    14  
    15  	"github.com/jaypipes/ghw/pkg/context"
    16  )
    17  
    18  const (
    19  	UNKNOWN = "unknown"
    20  )
    21  
    22  type closer interface {
    23  	Close() error
    24  }
    25  
    26  func SafeClose(c closer) {
    27  	err := c.Close()
    28  	if err != nil {
    29  		_, _ = fmt.Fprintf(os.Stderr, "failed to close: %s", err)
    30  	}
    31  }
    32  
    33  // Reads a supplied filepath and converts the contents to an integer. Returns
    34  // -1 if there were file permissions or existence errors or if the contents
    35  // could not be successfully converted to an integer. In any error, a warning
    36  // message is printed to STDERR and -1 is returned.
    37  func SafeIntFromFile(ctx *context.Context, path string) int {
    38  	msg := "failed to read int from file: %s\n"
    39  	buf, err := os.ReadFile(path)
    40  	if err != nil {
    41  		ctx.Warn(msg, err)
    42  		return -1
    43  	}
    44  	contents := strings.TrimSpace(string(buf))
    45  	res, err := strconv.Atoi(contents)
    46  	if err != nil {
    47  		ctx.Warn(msg, err)
    48  		return -1
    49  	}
    50  	return res
    51  }
    52  
    53  // ConcatStrings concatenate strings in a larger one. This function
    54  // addresses a very specific ghw use case. For a more general approach,
    55  // just use strings.Join()
    56  func ConcatStrings(items ...string) string {
    57  	return strings.Join(items, "")
    58  }
    59  
    60  // Convert strings to bool using strconv.ParseBool() when recognized, otherwise
    61  // use map lookup to convert strings like "Yes" "No" "On" "Off" to bool
    62  // `ethtool` uses on, off, yes, no (upper and lower case) rather than true and
    63  // false.
    64  func ParseBool(str string) (bool, error) {
    65  	if b, err := strconv.ParseBool(str); err == nil {
    66  		return b, err
    67  	} else {
    68  		ExtraBools := map[string]bool{
    69  			"on":  true,
    70  			"off": false,
    71  			"yes": true,
    72  			"no":  false,
    73  			// Return false instead of an error on empty strings
    74  			// For example from empty files in SysClassNet/Device
    75  			"": false,
    76  		}
    77  		if b, ok := ExtraBools[strings.ToLower(str)]; ok {
    78  			return b, nil
    79  		} else {
    80  			// Return strconv.ParseBool's error here
    81  			return b, err
    82  		}
    83  	}
    84  }