Skip to content

Commit

Permalink
Add hex encoding to HashTruncateName util (#996)
Browse files Browse the repository at this point in the history
  • Loading branch information
justinkaseman authored Jan 13, 2025
1 parent d266596 commit 42c3764
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
12 changes: 7 additions & 5 deletions pkg/workflows/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,15 @@ func GenerateWorkflowID(owner []byte, name string, workflow []byte, config []byt
}

// HashTruncateName returns the SHA-256 hash of the workflow name truncated to the first 10 bytes.
func HashTruncateName(name string) [10]byte {
func HashTruncateName(name string) string {
// Compute SHA-256 hash of the input string
hash := sha256.Sum256([]byte(name))

// Truncate the hash to 10 bytes
var result [10]byte
copy(result[:], hash[:10])
// Encode as hex to ensure UTF8
var hashBytes []byte = hash[:]
resultHex := hex.EncodeToString(hashBytes)

return result
// Truncate to 10 bytes
truncated := []byte(resultHex)[:10]
return string(truncated)
}
19 changes: 14 additions & 5 deletions pkg/workflows/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/hex"
"testing"
"unicode/utf8"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -70,32 +71,40 @@ func Test_GenerateWorkflowIDFromStrings(t *testing.T) {
func TestNormalizeWorkflowName(t *testing.T) {
tt := []struct {
input string
expected [10]byte
expected string
}{
{
input: "Hello, world!",
expected: [10]byte{0x31, 0x5f, 0x5b, 0xdb, 0x76, 0xd0, 0x78, 0xc4, 0x3b, 0x8a},
expected: "315f5bdb76",
},
{
input: "My Incredible Workflow Name",
expected: [10]byte{0x84, 0x00, 0x2e, 0xb9, 0xe2, 0xa0, 0x6b, 0x09, 0x97, 0x7c},
expected: "84002eb9e2",
},
{
input: "You either die a hero, or live long enough to see yourself become the villain.",
expected: [10]byte{0x6b, 0xa1, 0xf7, 0xa6, 0xa0, 0x91, 0x95, 0x1a, 0x2d, 0xd2},
expected: "6ba1f7a6a0",
},
{
input: "�����ï¿ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿",
expected: "68f19173b3",
},
}

for _, tc := range tt {
t.Run(tc.input, func(t *testing.T) {
// Call the function with the test input
result := HashTruncateName(tc.input)
var resultBytes = []byte(result)

// Assert that the result is exactly the expected output
require.Equal(t, tc.expected, result)

// Assert that the result is 10 bytes long
require.Len(t, result, 10)
require.Len(t, resultBytes, 10)

// Assert that the result is UTF8 encoded
require.True(t, utf8.Valid(resultBytes))
})
}
}

0 comments on commit 42c3764

Please sign in to comment.