Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds convenience method to generate a file listing & return the hash of the listing #73

Merged
merged 1 commit into from
Aug 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))))
})
}