utils.go 2.0 KB

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