Skip to content

Commit

Permalink
Adds convenience method to generate a file listing & return the hash …
Browse files Browse the repository at this point in the history
…of the listing

Signed-off-by: Daniel Mikusa <[email protected]>
  • Loading branch information
Daniel Mikusa committed Aug 16, 2021
1 parent bd0d6c0 commit 3e8dd64
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
15 changes: 15 additions & 0 deletions sherpa/file_listing.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,21 @@ type result struct {
value FileEntry
}

// NewFileListingHash generates a sha256 hash from the listing of all entries under the roots
func NewFileListingHash(roots ...string) (string, error) {
files, err := NewFileListing(roots...)
if err != nil {
return "", fmt.Errorf("unable to create file listing\n%w", err)
}

hash := sha256.New()
for _, file := range files {
hash.Write([]byte(file.Path + file.Mode + file.SHA256 + "\n"))
}

return hex.EncodeToString(hash.Sum(nil)), nil
}

// NewFileListing generates a listing of all entries under the roots.
func NewFileListing(roots ...string) ([]FileEntry, error) {
entries := make(chan FileEntry)
Expand Down
21 changes: 21 additions & 0 deletions sherpa/file_listing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package sherpa_test

import (
"crypto/sha256"
"encoding/hex"
"io/ioutil"
"os"
"path/filepath"
Expand Down Expand Up @@ -75,4 +77,23 @@ func testFileListing(t *testing.T, context spec.G, it spec.S) {
Expect(e[4].Path).To(HaveSuffix("bravo.txt"))
Expect(e[1].SHA256).To(Equal(e[4].SHA256)) // symlink to file should have hash of target file
})

it("create listing and get SHA256", func() {
Expect(ioutil.WriteFile(filepath.Join(path, "alpha.txt"), []byte{}, 0644)).To(Succeed())
Expect(os.MkdirAll(filepath.Join(path, "test-directory"), 0755)).To(Succeed())
Expect(ioutil.WriteFile(filepath.Join(path, "test-directory", "bravo.txt"), []byte{}, 0644)).To(Succeed())

e, err := sherpa.NewFileListing(path)
Expect(err).NotTo(HaveOccurred())

hash := sha256.New()
for _, file := range e {
hash.Write([]byte(file.Path + file.Mode + file.SHA256 + "\n"))
}

s, err := sherpa.NewFileListingHash(path)
Expect(err).NotTo(HaveOccurred())

Expect(s).To(Equal(hex.EncodeToString(hash.Sum(nil))))
})
}

0 comments on commit 3e8dd64

Please sign in to comment.