Skip to content

Commit

Permalink
Ensure packObjects test helper produces deterministic hashes by ite…
Browse files Browse the repository at this point in the history
…rating in sorted order
  • Loading branch information
airhorns committed May 6, 2024
1 parent c9a0294 commit 5ac3942
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
6 changes: 3 additions & 3 deletions internal/files/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func writeObject(rootDir string, cacheObjectsDir string, reader *db.TarReader, h
return err
}
hashHex := hex.EncodeToString(content)
return hardlinkDir(filepath.Join(cacheObjectsDir, hashHex, header.Name), path)
return HardlinkDir(filepath.Join(cacheObjectsDir, hashHex, header.Name), path)

case tar.TypeReg:
dir := filepath.Dir(path)
Expand Down Expand Up @@ -193,7 +193,7 @@ func makeSymlink(oldname, newname string) error {
return nil
}

func hardlinkDir(olddir, newdir string) error {
func HardlinkDir(olddir, newdir string) error {
if fileExists(newdir) {
err := os.RemoveAll(newdir)
if err != nil {
Expand All @@ -203,7 +203,7 @@ func hardlinkDir(olddir, newdir string) error {

return filepath.Walk(olddir, func(oldpath string, info fs.FileInfo, err error) error {
if err != nil {
return err
return fmt.Errorf("failed to walk dir: %v, %w", info, err)
}

newpath := filepath.Join(newdir, strings.TrimPrefix(oldpath, olddir))
Expand Down
14 changes: 12 additions & 2 deletions test/shared_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net"
"os"
"path/filepath"
"sort"
"strings"
"testing"

Expand Down Expand Up @@ -223,13 +224,22 @@ func packObjects(tc util.TestCtx, objects map[string]expectedObject) []byte {
contentWriter := db.NewTarWriter()
defer contentWriter.Close()

for path, info := range objects {
var keys []string
for key := range objects {
keys = append(keys, key)
}

sort.Strings(keys)

// iterate the objects for packing in a deterministic order
for _, key := range keys {
info := objects[key]
mode := info.mode
if mode == 0 {
mode = 0755
}

object := db.NewUncachedTarObject(path, mode, int64(len(info.content)), info.deleted, []byte(info.content))
object := db.NewUncachedTarObject(key, mode, int64(len(info.content)), info.deleted, []byte(info.content))

err := contentWriter.WriteObject(&object)
require.NoError(tc.T(), err, "write content to TAR")
Expand Down

0 comments on commit 5ac3942

Please sign in to comment.