util.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. package util
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "fmt"
  6. "github.com/gabriel-vasile/mimetype"
  7. "golang.org/x/term"
  8. "io"
  9. "math/rand"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. const (
  18. randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  19. )
  20. var (
  21. random = rand.New(rand.NewSource(time.Now().UnixNano()))
  22. randomMutex = sync.Mutex{}
  23. sizeStrRegex = regexp.MustCompile(`(?i)^(\d+)([gmkb])?$`)
  24. errInvalidPriority = errors.New("invalid priority")
  25. )
  26. // FileExists checks if a file exists, and returns true if it does
  27. func FileExists(filename string) bool {
  28. stat, _ := os.Stat(filename)
  29. return stat != nil
  30. }
  31. // InStringList returns true if needle is contained in haystack
  32. func InStringList(haystack []string, needle string) bool {
  33. for _, s := range haystack {
  34. if s == needle {
  35. return true
  36. }
  37. }
  38. return false
  39. }
  40. // InStringListAll returns true if all needles are contained in haystack
  41. func InStringListAll(haystack []string, needles []string) bool {
  42. matches := 0
  43. for _, s := range haystack {
  44. for _, needle := range needles {
  45. if s == needle {
  46. matches++
  47. }
  48. }
  49. }
  50. return matches == len(needles)
  51. }
  52. // InIntList returns true if needle is contained in haystack
  53. func InIntList(haystack []int, needle int) bool {
  54. for _, s := range haystack {
  55. if s == needle {
  56. return true
  57. }
  58. }
  59. return false
  60. }
  61. // SplitNoEmpty splits a string using strings.Split, but filters out empty strings
  62. func SplitNoEmpty(s string, sep string) []string {
  63. res := make([]string, 0)
  64. for _, r := range strings.Split(s, sep) {
  65. if r != "" {
  66. res = append(res, r)
  67. }
  68. }
  69. return res
  70. }
  71. // SplitKV splits a string into a key/value pair using a separator, and trimming space. If the separator
  72. // is not found, key is empty.
  73. func SplitKV(s string, sep string) (key string, value string) {
  74. kv := strings.SplitN(strings.TrimSpace(s), sep, 2)
  75. if len(kv) == 2 {
  76. return strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
  77. }
  78. return "", strings.TrimSpace(kv[0])
  79. }
  80. // RandomString returns a random string with a given length
  81. func RandomString(length int) string {
  82. randomMutex.Lock() // Who would have thought that random.Intn() is not thread-safe?!
  83. defer randomMutex.Unlock()
  84. b := make([]byte, length)
  85. for i := range b {
  86. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  87. }
  88. return string(b)
  89. }
  90. // ValidRandomString returns true if the given string matches the format created by RandomString
  91. func ValidRandomString(s string, length int) bool {
  92. if len(s) != length {
  93. return false
  94. }
  95. for _, c := range strings.Split(s, "") {
  96. if !strings.Contains(randomStringCharset, c) {
  97. return false
  98. }
  99. }
  100. return true
  101. }
  102. // DurationToHuman converts a duration to a human-readable format
  103. func DurationToHuman(d time.Duration) (str string) {
  104. if d == 0 {
  105. return "0"
  106. }
  107. d = d.Round(time.Second)
  108. days := d / time.Hour / 24
  109. if days > 0 {
  110. str += fmt.Sprintf("%dd", days)
  111. }
  112. d -= days * time.Hour * 24
  113. hours := d / time.Hour
  114. if hours > 0 {
  115. str += fmt.Sprintf("%dh", hours)
  116. }
  117. d -= hours * time.Hour
  118. minutes := d / time.Minute
  119. if minutes > 0 {
  120. str += fmt.Sprintf("%dm", minutes)
  121. }
  122. d -= minutes * time.Minute
  123. seconds := d / time.Second
  124. if seconds > 0 {
  125. str += fmt.Sprintf("%ds", seconds)
  126. }
  127. return
  128. }
  129. // ParsePriority parses a priority string into its equivalent integer value
  130. func ParsePriority(priority string) (int, error) {
  131. switch strings.TrimSpace(strings.ToLower(priority)) {
  132. case "":
  133. return 0, nil
  134. case "1", "min":
  135. return 1, nil
  136. case "2", "low":
  137. return 2, nil
  138. case "3", "default":
  139. return 3, nil
  140. case "4", "high":
  141. return 4, nil
  142. case "5", "max", "urgent":
  143. return 5, nil
  144. default:
  145. return 0, errInvalidPriority
  146. }
  147. }
  148. // PriorityString converts a priority number to a string
  149. func PriorityString(priority int) (string, error) {
  150. switch priority {
  151. case 0:
  152. return "default", nil
  153. case 1:
  154. return "min", nil
  155. case 2:
  156. return "low", nil
  157. case 3:
  158. return "default", nil
  159. case 4:
  160. return "high", nil
  161. case 5:
  162. return "max", nil
  163. default:
  164. return "", errInvalidPriority
  165. }
  166. }
  167. // ShortTopicURL shortens the topic URL to be human-friendly, removing the http:// or https://
  168. func ShortTopicURL(s string) string {
  169. return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
  170. }
  171. // DetectContentType probes the byte array b and returns mime type and file extension.
  172. // The filename is only used to override certain special cases.
  173. func DetectContentType(b []byte, filename string) (mimeType string, ext string) {
  174. if strings.HasSuffix(strings.ToLower(filename), ".apk") {
  175. return "application/vnd.android.package-archive", ".apk"
  176. }
  177. m := mimetype.Detect(b)
  178. mimeType, ext = m.String(), m.Extension()
  179. if ext == "" {
  180. ext = ".bin"
  181. }
  182. return
  183. }
  184. // ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.
  185. func ParseSize(s string) (int64, error) {
  186. matches := sizeStrRegex.FindStringSubmatch(s)
  187. if matches == nil {
  188. return -1, fmt.Errorf("invalid size %s", s)
  189. }
  190. value, err := strconv.Atoi(matches[1])
  191. if err != nil {
  192. return -1, fmt.Errorf("cannot convert number %s", matches[1])
  193. }
  194. switch strings.ToUpper(matches[2]) {
  195. case "G":
  196. return int64(value) * 1024 * 1024 * 1024, nil
  197. case "M":
  198. return int64(value) * 1024 * 1024, nil
  199. case "K":
  200. return int64(value) * 1024, nil
  201. default:
  202. return int64(value), nil
  203. }
  204. }
  205. // ReadPassword will read a password from STDIN. If the terminal supports it, it will not print the
  206. // input characters to the screen. If not, it'll just read using normal readline semantics (useful for testing).
  207. func ReadPassword(in io.Reader) ([]byte, error) {
  208. // If in is a file and a character device (a TTY), use term.ReadPassword
  209. if f, ok := in.(*os.File); ok {
  210. stat, err := f.Stat()
  211. if err != nil {
  212. return nil, err
  213. }
  214. if (stat.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
  215. password, err := term.ReadPassword(int(f.Fd())) // This is always going to be 0
  216. if err != nil {
  217. return nil, err
  218. }
  219. return password, nil
  220. }
  221. }
  222. // Fallback: Manually read util \n if found, see #69 for details why this is so manual
  223. password := make([]byte, 0)
  224. buf := make([]byte, 1)
  225. for {
  226. _, err := in.Read(buf)
  227. if err == io.EOF || buf[0] == '\n' {
  228. break
  229. } else if err != nil {
  230. return nil, err
  231. } else if len(password) > 10240 {
  232. return nil, errors.New("passwords this long are not supported")
  233. }
  234. password = append(password, buf[0])
  235. }
  236. return password, nil
  237. }
  238. // BasicAuth encodes the Authorization header value for basic auth
  239. func BasicAuth(user, pass string) string {
  240. return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pass))))
  241. }