util.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package util
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "math"
  10. "math/rand"
  11. "net/netip"
  12. "os"
  13. "regexp"
  14. "slices"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/gabriel-vasile/mimetype"
  20. "golang.org/x/term"
  21. "golang.org/x/time/rate"
  22. )
  23. const (
  24. randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  25. randomStringLowerCaseCharset = "abcdefghijklmnopqrstuvwxyz0123456789"
  26. )
  27. var (
  28. random = rand.New(rand.NewSource(time.Now().UnixNano()))
  29. randomMutex = sync.Mutex{}
  30. sizeStrRegex = regexp.MustCompile(`(?i)^(\d+)([gmkb])?$`)
  31. errInvalidPriority = errors.New("invalid priority")
  32. noQuotesRegex = regexp.MustCompile(`^[-_./:@a-zA-Z0-9]+$`)
  33. )
  34. // Errors for UnmarshalJSON and UnmarshalJSONWithLimit functions
  35. var (
  36. ErrUnmarshalJSON = errors.New("unmarshalling JSON failed")
  37. ErrTooLargeJSON = errors.New("too large JSON")
  38. )
  39. // FileExists checks if a file exists, and returns true if it does
  40. func FileExists(filename string) bool {
  41. stat, _ := os.Stat(filename)
  42. return stat != nil
  43. }
  44. // Contains returns true if needle is contained in haystack
  45. func Contains[T comparable](haystack []T, needle T) bool {
  46. return slices.Contains(haystack, needle)
  47. }
  48. // ContainsIP returns true if any one of the of prefixes contains the ip.
  49. func ContainsIP(haystack []netip.Prefix, needle netip.Addr) bool {
  50. for _, s := range haystack {
  51. if s.Contains(needle) {
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. // ContainsAll returns true if all needles are contained in haystack
  58. func ContainsAll[T comparable](haystack []T, needles []T) bool {
  59. for _, needle := range needles {
  60. if !Contains(haystack, needle) {
  61. return false
  62. }
  63. }
  64. return true
  65. }
  66. // SplitNoEmpty splits a string using strings.Split, but filters out empty strings
  67. func SplitNoEmpty(s string, sep string) []string {
  68. res := make([]string, 0)
  69. for _, r := range strings.Split(s, sep) {
  70. if r != "" {
  71. res = append(res, r)
  72. }
  73. }
  74. return res
  75. }
  76. // SplitKV splits a string into a key/value pair using a separator, and trimming space. If the separator
  77. // is not found, key is empty.
  78. func SplitKV(s string, sep string) (key string, value string) {
  79. kv := strings.SplitN(strings.TrimSpace(s), sep, 2)
  80. if len(kv) == 2 {
  81. return strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
  82. }
  83. return "", strings.TrimSpace(kv[0])
  84. }
  85. // Map applies a function to each element of a slice and returns a new slice with the results
  86. // Example: Map([]int{1, 2, 3}, func(i int) int { return i * 2 }) -> []int{2, 4, 6}
  87. func Map[T any, U any](slice []T, f func(T) U) []U {
  88. result := make([]U, len(slice))
  89. for i, v := range slice {
  90. result[i] = f(v)
  91. }
  92. return result
  93. }
  94. // Filter returns a new slice containing only the elements of the original slice for which the
  95. // given function returns true.
  96. func Filter[T any](slice []T, f func(T) bool) []T {
  97. result := make([]T, 0)
  98. for _, v := range slice {
  99. if f(v) {
  100. result = append(result, v)
  101. }
  102. }
  103. return result
  104. }
  105. // Find returns the first element in the slice that satisfies the given function, and a boolean indicating
  106. // whether such an element was found. If no element is found, it returns the zero value of T and false.
  107. func Find[T any](slice []T, f func(T) bool) (T, bool) {
  108. for _, v := range slice {
  109. if f(v) {
  110. return v, true
  111. }
  112. }
  113. var zero T
  114. return zero, false
  115. }
  116. // RandomString returns a random string with a given length
  117. func RandomString(length int) string {
  118. return RandomStringPrefix("", length)
  119. }
  120. // RandomStringPrefix returns a random string with a given length, with a prefix
  121. func RandomStringPrefix(prefix string, length int) string {
  122. return randomStringPrefixWithCharset(prefix, length, randomStringCharset)
  123. }
  124. // RandomLowerStringPrefix returns a random lowercase-only string with a given length, with a prefix
  125. func RandomLowerStringPrefix(prefix string, length int) string {
  126. return randomStringPrefixWithCharset(prefix, length, randomStringLowerCaseCharset)
  127. }
  128. func randomStringPrefixWithCharset(prefix string, length int, charset string) string {
  129. randomMutex.Lock() // Who would have thought that random.Intn() is not thread-safe?!
  130. defer randomMutex.Unlock()
  131. b := make([]byte, length-len(prefix))
  132. for i := range b {
  133. b[i] = charset[random.Intn(len(charset))]
  134. }
  135. return prefix + string(b)
  136. }
  137. // ValidRandomString returns true if the given string matches the format created by RandomString
  138. func ValidRandomString(s string, length int) bool {
  139. if len(s) != length {
  140. return false
  141. }
  142. for _, c := range strings.Split(s, "") {
  143. if !strings.Contains(randomStringCharset, c) {
  144. return false
  145. }
  146. }
  147. return true
  148. }
  149. // ParsePriority parses a priority string into its equivalent integer value
  150. func ParsePriority(priority string) (int, error) {
  151. p := strings.TrimSpace(strings.ToLower(priority))
  152. switch p {
  153. case "":
  154. return 0, nil
  155. case "1", "min":
  156. return 1, nil
  157. case "2", "low":
  158. return 2, nil
  159. case "3", "default":
  160. return 3, nil
  161. case "4", "high":
  162. return 4, nil
  163. case "5", "max", "urgent":
  164. return 5, nil
  165. default:
  166. return 0, errInvalidPriority
  167. }
  168. }
  169. // PriorityString converts a priority number to a string
  170. func PriorityString(priority int) (string, error) {
  171. switch priority {
  172. case 0:
  173. return "default", nil
  174. case 1:
  175. return "min", nil
  176. case 2:
  177. return "low", nil
  178. case 3:
  179. return "default", nil
  180. case 4:
  181. return "high", nil
  182. case 5:
  183. return "max", nil
  184. default:
  185. return "", errInvalidPriority
  186. }
  187. }
  188. // ShortTopicURL shortens the topic URL to be human-friendly, removing the http:// or https://
  189. func ShortTopicURL(s string) string {
  190. return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
  191. }
  192. // DetectContentType probes the byte array b and returns mime type and file extension.
  193. // The filename is only used to override certain special cases.
  194. func DetectContentType(b []byte, filename string) (mimeType string, ext string) {
  195. if strings.HasSuffix(strings.ToLower(filename), ".apk") {
  196. return "application/vnd.android.package-archive", ".apk"
  197. }
  198. m := mimetype.Detect(b)
  199. mimeType, ext = m.String(), m.Extension()
  200. if ext == "" {
  201. ext = ".bin"
  202. }
  203. return
  204. }
  205. // ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.
  206. func ParseSize(s string) (int64, error) {
  207. matches := sizeStrRegex.FindStringSubmatch(s)
  208. if matches == nil {
  209. return -1, fmt.Errorf("invalid size %s", s)
  210. }
  211. value, err := strconv.Atoi(matches[1])
  212. if err != nil {
  213. return -1, fmt.Errorf("cannot convert number %s", matches[1])
  214. }
  215. switch strings.ToUpper(matches[2]) {
  216. case "T":
  217. return int64(value) * 1024 * 1024 * 1024 * 1024, nil
  218. case "G":
  219. return int64(value) * 1024 * 1024 * 1024, nil
  220. case "M":
  221. return int64(value) * 1024 * 1024, nil
  222. case "K":
  223. return int64(value) * 1024, nil
  224. default:
  225. return int64(value), nil
  226. }
  227. }
  228. // FormatSize formats the size in a way that it can be parsed by ParseSize.
  229. // It does not include decimal places. Uneven sizes are rounded down.
  230. func FormatSize(b int64) string {
  231. const unit = 1024
  232. if b < unit {
  233. return fmt.Sprintf("%d", b)
  234. }
  235. div, exp := int64(unit), 0
  236. for n := b / unit; n >= unit; n /= unit {
  237. div *= unit
  238. exp++
  239. }
  240. return fmt.Sprintf("%d%c", int(math.Floor(float64(b)/float64(div))), "KMGT"[exp])
  241. }
  242. // FormatSizeHuman formats bytes into a human-readable notation, e.g. 2.1 MB
  243. func FormatSizeHuman(b int64) string {
  244. const unit = 1024
  245. if b < unit {
  246. return fmt.Sprintf("%d bytes", b)
  247. }
  248. div, exp := int64(unit), 0
  249. for n := b / unit; n >= unit; n /= unit {
  250. div *= unit
  251. exp++
  252. }
  253. return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGT"[exp])
  254. }
  255. // ReadPassword will read a password from STDIN. If the terminal supports it, it will not print the
  256. // input characters to the screen. If not, it'll just read using normal readline semantics (useful for testing).
  257. func ReadPassword(in io.Reader) ([]byte, error) {
  258. // If in is a file and a character device (a TTY), use term.ReadPassword
  259. if f, ok := in.(*os.File); ok {
  260. stat, err := f.Stat()
  261. if err != nil {
  262. return nil, err
  263. }
  264. if (stat.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
  265. password, err := term.ReadPassword(int(f.Fd())) // This is always going to be 0
  266. if err != nil {
  267. return nil, err
  268. } else if len(password) == 0 {
  269. return nil, errors.New("password cannot be empty")
  270. }
  271. return password, nil
  272. }
  273. }
  274. // Fallback: Manually read util \n if found, see #69 for details why this is so manual
  275. password := make([]byte, 0)
  276. buf := make([]byte, 1)
  277. for {
  278. _, err := in.Read(buf)
  279. if err == io.EOF || buf[0] == '\n' {
  280. break
  281. } else if err != nil {
  282. return nil, err
  283. } else if len(password) > 10240 {
  284. return nil, errors.New("passwords this long are not supported")
  285. }
  286. password = append(password, buf[0])
  287. }
  288. if len(password) == 0 {
  289. return nil, errors.New("password cannot be empty")
  290. }
  291. return password, nil
  292. }
  293. // BasicAuth encodes the Authorization header value for basic auth
  294. func BasicAuth(user, pass string) string {
  295. return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pass))))
  296. }
  297. // BearerAuth encodes the Authorization header value for a bearer/token auth
  298. func BearerAuth(token string) string {
  299. return fmt.Sprintf("Bearer %s", token)
  300. }
  301. // MaybeMarshalJSON returns a JSON string of the given object, or "<cannot serialize>" if serialization failed.
  302. // This is useful for logging purposes where a failure doesn't matter that much.
  303. func MaybeMarshalJSON(v any) string {
  304. jsonBytes, err := json.MarshalIndent(v, "", " ")
  305. if err != nil {
  306. return "<cannot serialize>"
  307. }
  308. if len(jsonBytes) > 5000 {
  309. return string(jsonBytes)[:5000]
  310. }
  311. return string(jsonBytes)
  312. }
  313. // QuoteCommand combines a command array to a string, quoting arguments that need quoting.
  314. // This function is naive, and sometimes wrong. It is only meant for lo pretty-printing a command.
  315. //
  316. // Warning: Never use this function with the intent to run the resulting command.
  317. //
  318. // Example:
  319. //
  320. // []string{"ls", "-al", "Document Folder"} -> ls -al "Document Folder"
  321. func QuoteCommand(command []string) string {
  322. var quoted []string
  323. for _, c := range command {
  324. if noQuotesRegex.MatchString(c) {
  325. quoted = append(quoted, c)
  326. } else {
  327. quoted = append(quoted, fmt.Sprintf(`"%s"`, c))
  328. }
  329. }
  330. return strings.Join(quoted, " ")
  331. }
  332. // UnmarshalJSON reads the given io.ReadCloser into a struct
  333. func UnmarshalJSON[T any](body io.ReadCloser) (*T, error) {
  334. var obj T
  335. if err := json.NewDecoder(body).Decode(&obj); err != nil {
  336. return nil, ErrUnmarshalJSON
  337. }
  338. return &obj, nil
  339. }
  340. // UnmarshalJSONWithLimit reads the given io.ReadCloser into a struct, but only until limit is reached
  341. func UnmarshalJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error) {
  342. defer r.Close()
  343. p, err := Peek(r, limit)
  344. if err != nil {
  345. return nil, err
  346. } else if p.LimitReached {
  347. return nil, ErrTooLargeJSON
  348. }
  349. var obj T
  350. if len(bytes.TrimSpace(p.PeekedBytes)) == 0 && allowEmpty {
  351. return &obj, nil
  352. } else if err := json.NewDecoder(p).Decode(&obj); err != nil {
  353. return nil, ErrUnmarshalJSON
  354. }
  355. return &obj, nil
  356. }
  357. // Retry executes function f until if succeeds, and then returns t. If f fails, it sleeps
  358. // and tries again. The sleep durations are passed as the after params.
  359. func Retry[T any](f func() (*T, error), after ...time.Duration) (t *T, err error) {
  360. for _, delay := range after {
  361. if t, err = f(); err == nil {
  362. return t, nil
  363. }
  364. time.Sleep(delay)
  365. }
  366. return nil, err
  367. }
  368. // MinMax returns value if it is between min and max, or either
  369. // min or max if it is out of range
  370. func MinMax[T int | int64](value, min, max T) T {
  371. if value < min {
  372. return min
  373. } else if value > max {
  374. return max
  375. }
  376. return value
  377. }
  378. // Max returns the maximum value of the two given values
  379. func Max[T int | int64 | rate.Limit](a, b T) T {
  380. if a > b {
  381. return a
  382. }
  383. return b
  384. }
  385. // String turns a string into a pointer of a string
  386. func String(v string) *string {
  387. return &v
  388. }
  389. // Int turns an int into a pointer of an int
  390. func Int(v int) *int {
  391. return &v
  392. }
  393. // Time turns a time.Time into a pointer
  394. func Time(v time.Time) *time.Time {
  395. return &v
  396. }