diff --git a/syft/source/directory_resolver.go b/syft/source/directory_resolver.go index ba94a3167..083a54862 100644 --- a/syft/source/directory_resolver.go +++ b/syft/source/directory_resolver.go @@ -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 { diff --git a/syft/source/directory_resolver_test.go b/syft/source/directory_resolver_test.go index 8cfcd5393..6951fdf5e 100644 --- a/syft/source/directory_resolver_test.go +++ b/syft/source/directory_resolver_test.go @@ -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)) + } + }) + } +}