util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "os"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. const (
  12. randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  13. )
  14. var (
  15. random = rand.New(rand.NewSource(time.Now().UnixNano()))
  16. randomMutex = sync.Mutex{}
  17. errInvalidPriority = errors.New("unknown priority")
  18. )
  19. // FileExists checks if a file exists, and returns true if it does
  20. func FileExists(filename string) bool {
  21. stat, _ := os.Stat(filename)
  22. return stat != nil
  23. }
  24. // InStringList returns true if needle is contained in haystack
  25. func InStringList(haystack []string, needle string) bool {
  26. for _, s := range haystack {
  27. if s == needle {
  28. return true
  29. }
  30. }
  31. return false
  32. }
  33. // RandomString returns a random string with a given length
  34. func RandomString(length int) string {
  35. randomMutex.Lock() // Who would have thought that random.Intn() is not thread-safe?!
  36. defer randomMutex.Unlock()
  37. b := make([]byte, length)
  38. for i := range b {
  39. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  40. }
  41. return string(b)
  42. }
  43. // DurationToHuman converts a duration to a human readable format
  44. func DurationToHuman(d time.Duration) (str string) {
  45. if d == 0 {
  46. return "0"
  47. }
  48. d = d.Round(time.Second)
  49. days := d / time.Hour / 24
  50. if days > 0 {
  51. str += fmt.Sprintf("%dd", days)
  52. }
  53. d -= days * time.Hour * 24
  54. hours := d / time.Hour
  55. if hours > 0 {
  56. str += fmt.Sprintf("%dh", hours)
  57. }
  58. d -= hours * time.Hour
  59. minutes := d / time.Minute
  60. if minutes > 0 {
  61. str += fmt.Sprintf("%dm", minutes)
  62. }
  63. d -= minutes * time.Minute
  64. seconds := d / time.Second
  65. if seconds > 0 {
  66. str += fmt.Sprintf("%ds", seconds)
  67. }
  68. return
  69. }
  70. // ParsePriority parses a priority string into its equivalent integer value
  71. func ParsePriority(priority string) (int, error) {
  72. switch strings.TrimSpace(strings.ToLower(priority)) {
  73. case "":
  74. return 0, nil
  75. case "1", "min":
  76. return 1, nil
  77. case "2", "low":
  78. return 2, nil
  79. case "3", "default":
  80. return 3, nil
  81. case "4", "high":
  82. return 4, nil
  83. case "5", "max", "urgent":
  84. return 5, nil
  85. default:
  86. return 0, errInvalidPriority
  87. }
  88. }
  89. // ExpandHome replaces "~" with the user's home directory
  90. func ExpandHome(path string) string {
  91. return os.ExpandEnv(strings.ReplaceAll(path, "~", "$HOME"))
  92. }