util.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package util
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/klauspost/compress/zstd"
  13. "github.com/minio/minio-go/v7"
  14. )
  15. func ExpandShellString(s string) (string, error) {
  16. if strings.Contains(s, "$") {
  17. // Start a shell to expand the environment variables
  18. cmd := exec.Command("sh", "-c", "echo "+s)
  19. out, err := cmd.Output()
  20. if err != nil {
  21. return "", err
  22. }
  23. s = strings.TrimSpace(string(out))
  24. }
  25. return s, nil
  26. }
  27. func ExpandShellStringInfallible(s string) string {
  28. expanded, err := ExpandShellString(s)
  29. if err != nil {
  30. return s
  31. }
  32. return expanded
  33. }
  34. func DecompressZstdBuffer(input []byte) ([]byte, error) {
  35. decoder, err := zstd.NewReader(nil)
  36. if err != nil {
  37. return nil, err
  38. }
  39. defer decoder.Close()
  40. return decoder.DecodeAll(input, nil)
  41. }
  42. func FmtMyTime(t time.Time) string {
  43. return t.Format("2006-01-02 15:04:05.000")
  44. }
  45. func FmtMyDate(t time.Time) string {
  46. return t.Format("2006-01-02")
  47. }
  48. func LastElem[T any](s []T) T {
  49. return s[len(s)-1]
  50. }
  51. func MinioUploadFolder(minioClient *minio.Client, bucketName string, objPath string, localPath string) error {
  52. // Walk the local folder
  53. err := filepath.WalkDir(localPath, func(path string, d os.DirEntry, err error) error {
  54. if err != nil {
  55. return fmt.Errorf("walk dir failed: %w", err)
  56. }
  57. if d.IsDir() {
  58. return nil
  59. }
  60. relPath, err := filepath.Rel(localPath, path)
  61. if err != nil {
  62. return fmt.Errorf("get relative path failed: %w", err)
  63. }
  64. targetPath := filepath.Join(objPath, relPath)
  65. _, err = minioClient.FPutObject(context.Background(), bucketName, targetPath, path,
  66. minio.PutObjectOptions{ContentType: "application/octet-stream"})
  67. if err != nil {
  68. return fmt.Errorf("fput object failed: %w", err)
  69. }
  70. return nil
  71. })
  72. return err
  73. }
  74. func GetCurrentNanoTimestampUTC() int64 {
  75. return time.Now().UnixNano()
  76. }
  77. func ExtractNumberFromString(filename string) (int64, error) {
  78. re := regexp.MustCompile(`(\d+)`)
  79. match := re.FindStringSubmatch(filename)
  80. if len(match) < 2 {
  81. return 0, fmt.Errorf("number not found in filename `%s`", filename)
  82. }
  83. return strconv.ParseInt(match[1], 10, 64)
  84. }