2019-07-30 18:51:29 +00:00
|
|
|
// Package utils provides some common utility methods
|
2019-07-20 10:26:52 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"runtime"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/drakkan/sftpgo/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
const logSender = "utils"
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// IsStringInSlice searches a string in a slice and returns true if the string is found
|
2019-07-20 10:26:52 +00:00
|
|
|
func IsStringInSlice(obj string, list []string) bool {
|
|
|
|
for _, v := range list {
|
|
|
|
if v == obj {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
|
|
|
|
func GetTimeAsMsSinceEpoch(t time.Time) int64 {
|
|
|
|
return t.UnixNano() / 1000000
|
|
|
|
}
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// ScanDirContents returns the number of files contained in a directory, their size and a slice with the file paths
|
2019-07-27 07:38:09 +00:00
|
|
|
func ScanDirContents(path string) (int, int64, []string, error) {
|
2019-07-20 10:26:52 +00:00
|
|
|
var numFiles int
|
|
|
|
var size int64
|
2019-07-27 07:38:09 +00:00
|
|
|
var fileList []string
|
2019-07-20 10:26:52 +00:00
|
|
|
var err error
|
|
|
|
numFiles = 0
|
|
|
|
size = 0
|
|
|
|
isDir, err := isDirectory(path)
|
|
|
|
if err == nil && isDir {
|
|
|
|
err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if info != nil && info.Mode().IsRegular() {
|
|
|
|
size += info.Size()
|
|
|
|
numFiles++
|
2019-07-27 07:38:09 +00:00
|
|
|
fileList = append(fileList, path)
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-07-27 07:38:09 +00:00
|
|
|
return numFiles, size, fileList, err
|
2019-07-20 10:26:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func isDirectory(path string) (bool, error) {
|
|
|
|
fileInfo, err := os.Stat(path)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return fileInfo.IsDir(), err
|
|
|
|
}
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// SetPathPermissions call os.Chown on unix, it does nothing on windows
|
2019-07-20 10:26:52 +00:00
|
|
|
func SetPathPermissions(path string, uid int, gid int) {
|
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
if err := os.Chown(path, uid, gid); err != nil {
|
|
|
|
logger.Warn(logSender, "error chowning path %v: %v", path, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|