util.go 2.0 KB

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