From 682750ff48a85afa43e8890772abc2d57901ca28 Mon Sep 17 00:00:00 2001 From: cyber-dream Date: Mon, 6 Feb 2023 16:19:35 +0300 Subject: [PATCH] Add file stat method --- osutils/files.go | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/osutils/files.go b/osutils/files.go index b366712..239c844 100644 --- a/osutils/files.go +++ b/osutils/files.go @@ -1,6 +1,9 @@ package osutils import ( + "crypto/sha1" + "encoding/hex" + "io" "io/fs" "io/ioutil" "log" @@ -59,3 +62,56 @@ func GetParentDir(filePath string) (string, error) { finalPath := path.Join("/", path.Join(cuttedPath...)) 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 +}