utils.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Package utils provides some common utility methods
  2. package utils
  3. import (
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "time"
  8. "github.com/drakkan/sftpgo/logger"
  9. )
  10. const logSender = "utils"
  11. // IsStringInSlice searches a string in a slice and returns true if the string is found
  12. func IsStringInSlice(obj string, list []string) bool {
  13. for _, v := range list {
  14. if v == obj {
  15. return true
  16. }
  17. }
  18. return false
  19. }
  20. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  21. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  22. return t.UnixNano() / 1000000
  23. }
  24. // ScanDirContents returns the number of files contained in a directory, their size and a slice with the file paths
  25. func ScanDirContents(path string) (int, int64, []string, error) {
  26. var numFiles int
  27. var size int64
  28. var fileList []string
  29. var err error
  30. numFiles = 0
  31. size = 0
  32. isDir, err := isDirectory(path)
  33. if err == nil && isDir {
  34. err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
  35. if err != nil {
  36. return err
  37. }
  38. if info != nil && info.Mode().IsRegular() {
  39. size += info.Size()
  40. numFiles++
  41. fileList = append(fileList, path)
  42. }
  43. return err
  44. })
  45. }
  46. return numFiles, size, fileList, err
  47. }
  48. func isDirectory(path string) (bool, error) {
  49. fileInfo, err := os.Stat(path)
  50. if err != nil {
  51. return false, err
  52. }
  53. return fileInfo.IsDir(), err
  54. }
  55. // SetPathPermissions call os.Chown on unix, it does nothing on windows
  56. func SetPathPermissions(path string, uid int, gid int) {
  57. if runtime.GOOS != "windows" {
  58. if err := os.Chown(path, uid, gid); err != nil {
  59. logger.Warn(logSender, "error chowning path %v: %v", path, err)
  60. }
  61. }
  62. }