add internal.formats helper functions + identify tests

Signed-off-by: Alex Goodman <alex.goodman@anchore.com>
This commit is contained in:
Alex Goodman 2021-10-10 18:32:02 -07:00
parent f6cc0c8628
commit bcdebcadaf
No known key found for this signature in database
GPG Key ID: 5CB45AE22BAB7EA7
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package formats
import (
"github.com/anchore/syft/internal/formats/spdx22json"
"github.com/anchore/syft/internal/formats/syftjson"
"github.com/anchore/syft/syft/format"
)
// TODO: eventually this is the source of truth for all formatters
func All() []format.Format {
return []format.Format{
spdx22json.Format(),
syftjson.Format(),
}
}
func Identify(by []byte) (*format.Format, error) {
for _, f := range All() {
if f.Detect(by) {
return &f, nil
}
}
return nil, nil
}
func ByOption(option format.Option) *format.Format {
for _, f := range All() {
if f.Option == option {
return &f
}
}
return nil
}

View File

@ -0,0 +1,39 @@
package formats
import (
"io"
"os"
"testing"
"github.com/anchore/syft/syft/format"
"github.com/stretchr/testify/assert"
)
func TestIdentify(t *testing.T) {
tests := []struct {
fixture string
expected format.Option
}{
{
fixture: "test-fixtures/alpine-syft.json",
expected: format.JSONOption,
},
{
fixture: "test-fixtures/alpine-syft-spdx.json",
expected: format.SPDXJSONOption,
},
}
for _, test := range tests {
t.Run(test.fixture, func(t *testing.T) {
f, err := os.Open(test.fixture)
assert.NoError(t, err)
by, err := io.ReadAll(f)
assert.NoError(t, err)
frmt, err := Identify(by)
assert.NoError(t, err)
assert.NotNil(t, frmt)
assert.Equal(t, test.expected, frmt.Option)
})
}
}