mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-01-14 08:09:41 -06:00
Implement GetSHA256FromFS function to compute SHA256 hash from a filesystem. Add tests and sample files for validation
This commit is contained in:
44
internal/util/cryptoutil/get_sha256_from_fs.go
Normal file
44
internal/util/cryptoutil/get_sha256_from_fs.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package cryptoutil
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
// GetSHA256FromFS takes a fs.FS and returns a SHA256 hash of the combined contents
|
||||
// of all files in the filesystem.
|
||||
//
|
||||
// If there is an error, it returns an empty string.
|
||||
func GetSHA256FromFS(fsys fs.FS) string {
|
||||
hash := sha256.New()
|
||||
|
||||
err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
file, err := fsys.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return hex.EncodeToString(hash.Sum(nil))
|
||||
}
|
||||
32
internal/util/cryptoutil/get_sha256_from_fs_test.go
Normal file
32
internal/util/cryptoutil/get_sha256_from_fs_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package cryptoutil
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
//go:embed get_sha256_from_fs_test_data/*
|
||||
var testFS embed.FS
|
||||
|
||||
func TestGetSHA256FromFS_ValidFS(t *testing.T) {
|
||||
hash := GetSHA256FromFS(testFS)
|
||||
assert.NotEmpty(t, hash)
|
||||
|
||||
// To generate the expected hash, you must combine the contents of all the
|
||||
// files in the test_data directory and calculate the SHA256 hash of the
|
||||
// resulting string.
|
||||
expectedHash := "d2c58b6783050a95542286a58250d4dc872877a6cf28610669516dcfacf954af"
|
||||
assert.Equal(t, expectedHash, hash)
|
||||
}
|
||||
|
||||
func TestGetSHA256FromFS_EmptyFS(t *testing.T) {
|
||||
var emptyFS embed.FS
|
||||
hash := GetSHA256FromFS(emptyFS)
|
||||
|
||||
expectedHash := sha256.New().Sum(nil)
|
||||
assert.Equal(t, hex.EncodeToString(expectedHash), hash)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
file 1 contents
|
||||
@@ -0,0 +1 @@
|
||||
file 2 contents
|
||||
@@ -0,0 +1 @@
|
||||
file 3 contents
|
||||
Reference in New Issue
Block a user