util.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. // RandomString returns a random string with a given length
  72. func RandomString(length int) string {
  73. randomMutex.Lock() // Who would have thought that random.Intn() is not thread-safe?!
  74. defer randomMutex.Unlock()
  75. b := make([]byte, length)
  76. for i := range b {
  77. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  78. }
  79. return string(b)
  80. }
  81. // DurationToHuman converts a duration to a human readable format
  82. func DurationToHuman(d time.Duration) (str string) {
  83. if d == 0 {
  84. return "0"
  85. }
  86. d = d.Round(time.Second)
  87. days := d / time.Hour / 24
  88. if days > 0 {
  89. str += fmt.Sprintf("%dd", days)
  90. }
  91. d -= days * time.Hour * 24
  92. hours := d / time.Hour
  93. if hours > 0 {
  94. str += fmt.Sprintf("%dh", hours)
  95. }
  96. d -= hours * time.Hour
  97. minutes := d / time.Minute
  98. if minutes > 0 {
  99. str += fmt.Sprintf("%dm", minutes)
  100. }
  101. d -= minutes * time.Minute
  102. seconds := d / time.Second
  103. if seconds > 0 {
  104. str += fmt.Sprintf("%ds", seconds)
  105. }
  106. return
  107. }
  108. // ParsePriority parses a priority string into its equivalent integer value
  109. func ParsePriority(priority string) (int, error) {
  110. switch strings.TrimSpace(strings.ToLower(priority)) {
  111. case "":
  112. return 0, nil
  113. case "1", "min":
  114. return 1, nil
  115. case "2", "low":
  116. return 2, nil
  117. case "3", "default":
  118. return 3, nil
  119. case "4", "high":
  120. return 4, nil
  121. case "5", "max", "urgent":
  122. return 5, nil
  123. default:
  124. return 0, errInvalidPriority
  125. }
  126. }
  127. // PriorityString converts a priority number to a string
  128. func PriorityString(priority int) (string, error) {
  129. switch priority {
  130. case 0:
  131. return "default", nil
  132. case 1:
  133. return "min", nil
  134. case 2:
  135. return "low", nil
  136. case 3:
  137. return "default", nil
  138. case 4:
  139. return "high", nil
  140. case 5:
  141. return "max", nil
  142. default:
  143. return "", errInvalidPriority
  144. }
  145. }
  146. // ExpandHome replaces "~" with the user's home directory
  147. func ExpandHome(path string) string {
  148. return os.ExpandEnv(strings.ReplaceAll(path, "~", "$HOME"))
  149. }
  150. // ShortTopicURL shortens the topic URL to be human-friendly, removing the http:// or https://
  151. func ShortTopicURL(s string) string {
  152. return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
  153. }
  154. // DetectContentType probes the byte array b and returns mime type and file extension.
  155. // The filename is only used to override certain special cases.
  156. func DetectContentType(b []byte, filename string) (mimeType string, ext string) {
  157. if strings.HasSuffix(strings.ToLower(filename), ".apk") {
  158. return "application/vnd.android.package-archive", ".apk"
  159. }
  160. m := mimetype.Detect(b)
  161. mimeType, ext = m.String(), m.Extension()
  162. if ext == "" {
  163. ext = ".bin"
  164. }
  165. return
  166. }
  167. // ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.
  168. func ParseSize(s string) (int64, error) {
  169. matches := sizeStrRegex.FindStringSubmatch(s)
  170. if matches == nil {
  171. return -1, fmt.Errorf("invalid size %s", s)
  172. }
  173. value, err := strconv.Atoi(matches[1])
  174. if err != nil {
  175. return -1, fmt.Errorf("cannot convert number %s", matches[1])
  176. }
  177. switch strings.ToUpper(matches[2]) {
  178. case "G":
  179. return int64(value) * 1024 * 1024 * 1024, nil
  180. case "M":
  181. return int64(value) * 1024 * 1024, nil
  182. case "K":
  183. return int64(value) * 1024, nil
  184. default:
  185. return int64(value), nil
  186. }
  187. }
  188. // ReadPassword will read a password from STDIN. If the terminal supports it, it will not print the
  189. // input characters to the screen. If not, it'll just read using normal readline semantics (useful for testing).
  190. func ReadPassword(in io.Reader) ([]byte, error) {
  191. // If in is a file and a character device (a TTY), use term.ReadPassword
  192. if f, ok := in.(*os.File); ok {
  193. stat, err := f.Stat()
  194. if err != nil {
  195. return nil, err
  196. }
  197. if (stat.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
  198. password, err := term.ReadPassword(int(f.Fd())) // This is always going to be 0
  199. if err != nil {
  200. return nil, err
  201. }
  202. return password, nil
  203. }
  204. }
  205. // Fallback: Manually read util \n if found, see #69 for details why this is so manual
  206. password := make([]byte, 0)
  207. buf := make([]byte, 1)
  208. for {
  209. _, err := in.Read(buf)
  210. if err == io.EOF || buf[0] == '\n' {
  211. break
  212. } else if err != nil {
  213. return nil, err
  214. } else if len(password) > 10240 {
  215. return nil, errors.New("passwords this long are not supported")
  216. }
  217. password = append(password, buf[0])
  218. }
  219. return password, nil
  220. }
  221. // BasicAuth encodes the Authorization header value for basic auth
  222. func BasicAuth(user, pass string) string {
  223. return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pass))))
  224. }