Implement GetSHA256FromFS function to compute SHA256 hash from a filesystem. Add tests and sample files for validation

This commit is contained in:
Luis Eduardo Jeréz Girón
2024-09-04 23:59:55 -06:00
parent 89e01336da
commit babc4c6f78
5 changed files with 79 additions and 0 deletions

View 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))
}

View 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)
}

View File

@@ -0,0 +1 @@
file 1 contents

View File

@@ -0,0 +1 @@
file 2 contents

View File

@@ -0,0 +1 @@
file 3 contents