util.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "mime"
  7. "os"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. const (
  15. randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  16. )
  17. var (
  18. random = rand.New(rand.NewSource(time.Now().UnixNano()))
  19. randomMutex = sync.Mutex{}
  20. sizeStrRegex = regexp.MustCompile(`(?i)^(\d+)([gmkb])?$`)
  21. extRegex = regexp.MustCompile(`^\.[-_A-Za-z0-9]+$`)
  22. errInvalidPriority = errors.New("invalid priority")
  23. )
  24. // FileExists checks if a file exists, and returns true if it does
  25. func FileExists(filename string) bool {
  26. stat, _ := os.Stat(filename)
  27. return stat != nil
  28. }
  29. // InStringList returns true if needle is contained in haystack
  30. func InStringList(haystack []string, needle string) bool {
  31. for _, s := range haystack {
  32. if s == needle {
  33. return true
  34. }
  35. }
  36. return false
  37. }
  38. // InStringListAll returns true if all needles are contained in haystack
  39. func InStringListAll(haystack []string, needles []string) bool {
  40. matches := 0
  41. for _, s := range haystack {
  42. for _, needle := range needles {
  43. if s == needle {
  44. matches++
  45. }
  46. }
  47. }
  48. return matches == len(needles)
  49. }
  50. // InIntList returns true if needle is contained in haystack
  51. func InIntList(haystack []int, needle int) bool {
  52. for _, s := range haystack {
  53. if s == needle {
  54. return true
  55. }
  56. }
  57. return false
  58. }
  59. // SplitNoEmpty splits a string using strings.Split, but filters out empty strings
  60. func SplitNoEmpty(s string, sep string) []string {
  61. res := make([]string, 0)
  62. for _, r := range strings.Split(s, sep) {
  63. if r != "" {
  64. res = append(res, r)
  65. }
  66. }
  67. return res
  68. }
  69. // RandomString returns a random string with a given length
  70. func RandomString(length int) string {
  71. randomMutex.Lock() // Who would have thought that random.Intn() is not thread-safe?!
  72. defer randomMutex.Unlock()
  73. b := make([]byte, length)
  74. for i := range b {
  75. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  76. }
  77. return string(b)
  78. }
  79. // DurationToHuman converts a duration to a human readable format
  80. func DurationToHuman(d time.Duration) (str string) {
  81. if d == 0 {
  82. return "0"
  83. }
  84. d = d.Round(time.Second)
  85. days := d / time.Hour / 24
  86. if days > 0 {
  87. str += fmt.Sprintf("%dd", days)
  88. }
  89. d -= days * time.Hour * 24
  90. hours := d / time.Hour
  91. if hours > 0 {
  92. str += fmt.Sprintf("%dh", hours)
  93. }
  94. d -= hours * time.Hour
  95. minutes := d / time.Minute
  96. if minutes > 0 {
  97. str += fmt.Sprintf("%dm", minutes)
  98. }
  99. d -= minutes * time.Minute
  100. seconds := d / time.Second
  101. if seconds > 0 {
  102. str += fmt.Sprintf("%ds", seconds)
  103. }
  104. return
  105. }
  106. // ParsePriority parses a priority string into its equivalent integer value
  107. func ParsePriority(priority string) (int, error) {
  108. switch strings.TrimSpace(strings.ToLower(priority)) {
  109. case "":
  110. return 0, nil
  111. case "1", "min":
  112. return 1, nil
  113. case "2", "low":
  114. return 2, nil
  115. case "3", "default":
  116. return 3, nil
  117. case "4", "high":
  118. return 4, nil
  119. case "5", "max", "urgent":
  120. return 5, nil
  121. default:
  122. return 0, errInvalidPriority
  123. }
  124. }
  125. // PriorityString converts a priority number to a string
  126. func PriorityString(priority int) (string, error) {
  127. switch priority {
  128. case 0:
  129. return "default", nil
  130. case 1:
  131. return "min", nil
  132. case 2:
  133. return "low", nil
  134. case 3:
  135. return "default", nil
  136. case 4:
  137. return "high", nil
  138. case 5:
  139. return "max", nil
  140. default:
  141. return "", errInvalidPriority
  142. }
  143. }
  144. // ExpandHome replaces "~" with the user's home directory
  145. func ExpandHome(path string) string {
  146. return os.ExpandEnv(strings.ReplaceAll(path, "~", "$HOME"))
  147. }
  148. // ShortTopicURL shortens the topic URL to be human-friendly, removing the http:// or https://
  149. func ShortTopicURL(s string) string {
  150. return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
  151. }
  152. // ExtensionByType is a wrapper around mime.ExtensionByType with a few sensible corrections
  153. func ExtensionByType(contentType string) string {
  154. switch contentType {
  155. case "image/jpeg":
  156. return ".jpg"
  157. default:
  158. exts, err := mime.ExtensionsByType(contentType)
  159. if err == nil && len(exts) > 0 && extRegex.MatchString(exts[0]) {
  160. return exts[0]
  161. }
  162. return ".bin"
  163. }
  164. }
  165. // ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.
  166. func ParseSize(s string) (int64, error) {
  167. matches := sizeStrRegex.FindStringSubmatch(s)
  168. if matches == nil {
  169. return -1, fmt.Errorf("invalid size %s", s)
  170. }
  171. value, err := strconv.Atoi(matches[1])
  172. if err != nil {
  173. return -1, fmt.Errorf("cannot convert number %s", matches[1])
  174. }
  175. switch strings.ToUpper(matches[2]) {
  176. case "G":
  177. return int64(value) * 1024 * 1024 * 1024, nil
  178. case "M":
  179. return int64(value) * 1024 * 1024, nil
  180. case "K":
  181. return int64(value) * 1024, nil
  182. default:
  183. return int64(value), nil
  184. }
  185. }