package osutils import ( "crypto/sha1" "encoding/hex" "io" "io/fs" "io/ioutil" "log" "os" "path" "path/filepath" "strings" ) func IsDirectory(path string) (bool, error) { fileInfo, err := os.Stat(path) if err != nil { return false, err } return fileInfo.IsDir(), err } func RecursiceWalk(pathToWalk string) ([]string, error) { paths := []string{} err := filepath.Walk(pathToWalk, func(path string, info os.FileInfo, err error) error { if err != nil { println(err) return err } // fmt.Println(path[len(path)-4:]) libBool, err := IsDirectory(path) if err != nil { println("error in checking lib or dir") } if !libBool { // println(path) paths = append(paths, path) } return nil }) if err != nil { log.Println(err) } return paths, nil } func ListDir(path string) ([]fs.FileInfo, error) { files, err := ioutil.ReadDir(path) if err != nil { return []fs.FileInfo{}, err } return files, nil } func GetParentDir(filePath string) (string, error) { cuttedPath := strings.Split(filePath, "/") cuttedPath = cuttedPath[:len(cuttedPath)-1] 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 stat, err := os.Stat(filePath) if err != nil { return &info, err } info.FileInfo = stat 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 }