Skip to content

Commit

Permalink
check file hash before mv
Browse files Browse the repository at this point in the history
  • Loading branch information
zachcheung committed Jul 20, 2024
1 parent a43f04d commit 9057c74
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
9 changes: 9 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
41 changes: 41 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"archive/tar"
"archive/zip"
"compress/gzip"
"crypto/sha256"
"fmt"
"io"
"log"
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}

0 comments on commit 9057c74

Please sign in to comment.