fix directory content fetching (#651)

Signed-off-by: Alex Goodman <alex.goodman@anchore.com>
This commit is contained in:
Alex Goodman 2021-12-02 09:02:54 -05:00 committed by GitHub
parent ed84e43d67
commit 21d1738b27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 1 deletions

View File

@ -326,7 +326,10 @@ func (r *directoryResolver) RelativeFileByPath(_ Location, path string) *Locatio
// FileContentsByLocation fetches file contents for a single file reference relative to a directory.
// If the path does not exist an error is returned.
func (r directoryResolver) FileContentsByLocation(location Location) (io.ReadCloser, error) {
return file.NewLazyReadCloser(location.RealPath), nil
if location.ref.RealPath == "" {
return nil, errors.New("empty path given")
}
return file.NewLazyReadCloser(string(location.ref.RealPath)), nil
}
func (r *directoryResolver) AllLocations() <-chan Location {

View File

@ -536,3 +536,45 @@ func Test_ignoreIrregularFiles(t *testing.T) {
rp := resolver.fileTree.AllFiles()[0].RealPath
assert.True(t, strings.Contains(string(rp), filepath.Join(dir, "readme")))
}
func Test_directoryResolver_FileContentsByLocation(t *testing.T) {
tests := []struct {
name string
location Location
expects string
err bool
}{
{
name: "use file reference for content requests",
location: NewLocationFromDirectory("some/place", file.Reference{
RealPath: "test-fixtures/image-simple/file-1.txt",
}),
expects: "this file has contents",
},
{
name: "error on empty file reference",
location: NewLocationFromDirectory("doesn't matter", file.Reference{}),
err: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
r, err := newDirectoryResolver(".")
require.NoError(t, err)
actual, err := r.FileContentsByLocation(test.location)
if test.err {
require.Error(t, err)
return
} else {
require.NoError(t, err)
}
if test.expects != "" {
b, err := ioutil.ReadAll(actual)
require.NoError(t, err)
assert.Equal(t, test.expects, string(b))
}
})
}
}