From 9057c742e36d827540481838c172b6bd542b8461 Mon Sep 17 00:00:00 2001 From: Zach Cheung Date: Sat, 20 Jul 2024 19:39:07 +0800 Subject: [PATCH] check file hash before mv --- main.go | 9 +++++++++ utils.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/main.go b/main.go index 152d62c..d90a3f9 100644 --- a/main.go +++ b/main.go @@ -131,6 +131,15 @@ func main() { // use repo base as filename name := filepath.Base(repo) destPath := filepath.Join(installDir, name) + isSameFile, err := isIdenticalFile(fpath, destPath) + if err != nil { + log.Fatal(err) + } + if isSameFile { + log.Printf("%s is identical, no need to install", destPath) + return + } + if err := addExecutePermission(fpath); err != nil { log.Fatalf("Error adding execute permission: %v", err) } diff --git a/utils.go b/utils.go index ac2698e..949517e 100644 --- a/utils.go +++ b/utils.go @@ -4,6 +4,7 @@ import ( "archive/tar" "archive/zip" "compress/gzip" + "crypto/sha256" "fmt" "io" "log" @@ -49,6 +50,15 @@ func extractAndInstallExecutables(archivePath, destDir string) error { } defer outFile.Close() + isSameFile, err := isIdenticalFile(oldpath, newpath) + if err != nil { + return err + } + if isSameFile { + log.Printf("%s is identical, no need to install", newpath) + return nil + } + if err := outFile.Chmod(mode); err != nil { return err } @@ -275,3 +285,34 @@ func boolToInt(b bool) int { } return 0 } + +func isIdenticalFile(src, dst string) (bool, error) { + srcHash, err := calculateSHA256(src) + if err != nil { + return false, err + } + dstHash, err := calculateSHA256(dst) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, err + } + + return string(srcHash) == string(dstHash), nil +} + +func calculateSHA256(filePath string) ([]byte, error) { + file, err := os.Open(filePath) + if err != nil { + return nil, err + } + defer file.Close() + + hash := sha256.New() + if _, err := io.Copy(hash, file); err != nil { + return nil, err + } + + return hash.Sum(nil), nil +}