utils.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Package utils provides some common utility methods
  2. package utils
  3. import (
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "strconv"
  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. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  22. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  23. return t.UnixNano() / 1000000
  24. }
  25. // ScanDirContents returns the number of files contained in a directory, their size and a slice with the file paths
  26. func ScanDirContents(path string) (int, int64, []string, error) {
  27. var numFiles int
  28. var size int64
  29. var fileList []string
  30. var err error
  31. numFiles = 0
  32. size = 0
  33. isDir, err := isDirectory(path)
  34. if err == nil && isDir {
  35. err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
  36. if err != nil {
  37. return err
  38. }
  39. if info != nil && info.Mode().IsRegular() {
  40. size += info.Size()
  41. numFiles++
  42. fileList = append(fileList, path)
  43. }
  44. return err
  45. })
  46. }
  47. return numFiles, size, fileList, err
  48. }
  49. func isDirectory(path string) (bool, error) {
  50. fileInfo, err := os.Stat(path)
  51. if err != nil {
  52. return false, err
  53. }
  54. return fileInfo.IsDir(), err
  55. }
  56. // SetPathPermissions call os.Chown on unix, it does nothing on windows
  57. func SetPathPermissions(path string, uid int, gid int) {
  58. if runtime.GOOS != "windows" {
  59. if err := os.Chown(path, uid, gid); err != nil {
  60. logger.Warn(logSender, "error chowning path %v: %v", path, err)
  61. }
  62. }
  63. }
  64. // GetEnvVar retrieves the value of the environment variable named
  65. // by the key. If the variable is present in the environment the it
  66. // returns the fallback value
  67. func GetEnvVar(key, fallback string) string {
  68. if value, ok := os.LookupEnv(key); ok {
  69. return value
  70. }
  71. return fallback
  72. }
  73. // GetEnvVarAsInt retrieves the value of the environment variable named
  74. // by the key and returns its value or fallback
  75. func GetEnvVarAsInt(key string, fallback int) int {
  76. stringValue := GetEnvVar(key, strconv.Itoa(fallback))
  77. if value, err := strconv.Atoi(stringValue); err == nil {
  78. return value
  79. }
  80. return fallback
  81. }