Add file stat method

This commit is contained in:
cyber-dream 2023-02-06 16:19:35 +03:00
parent 4cf354733c
commit 682750ff48

View File

@ -1,6 +1,9 @@
package osutils package osutils
import ( import (
"crypto/sha1"
"encoding/hex"
"io"
"io/fs" "io/fs"
"io/ioutil" "io/ioutil"
"log" "log"
@ -59,3 +62,56 @@ func GetParentDir(filePath string) (string, error) {
finalPath := path.Join("/", path.Join(cuttedPath...)) finalPath := path.Join("/", path.Join(cuttedPath...))
return finalPath, nil return finalPath, nil
} }
type FileValidationInfo struct {
Path string
fs.FileInfo
SHA1 string
}
func ValidateFile(filePath string) (FileValidationInfo, error) {
info := FileValidationInfo{
Path: filePath,
FileInfo: nil,
SHA1: "",
}
info.Path = filePath
hash, err := GetFileHash(filePath)
if err != nil {
return info, err
}
info.SHA1 = hash
return info, nil
}
func GetFileHash(filePath string) (string, error) {
//Initialize variable returnMD5String now in case an error has to be returned
var returnSHA1String string
//Open the filepath passed by the argument and check for any error
file, err := os.Open(filePath)
if err != nil {
return "", err
}
//Tell the program to call the following function when the current function returns
defer file.Close()
//Open a new SHA1 hash interface to write to
hash := sha1.New()
//Copy the file in the hash interface and check for any error
if _, err := io.Copy(hash, file); err != nil {
return returnSHA1String, err
}
//Get the 20 bytes hash
hashInBytes := hash.Sum(nil)[:20]
//Convert the bytes to a string
returnSHA1String = hex.EncodeToString(hashInBytes)
return returnSHA1String, nil
}