util.go 12 KB

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