diff --git a/internal/formats/formats.go b/internal/formats/formats.go new file mode 100644 index 000000000..0022780bf --- /dev/null +++ b/internal/formats/formats.go @@ -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 +} diff --git a/internal/formats/formats_test.go b/internal/formats/formats_test.go new file mode 100644 index 000000000..e1f082c04 --- /dev/null +++ b/internal/formats/formats_test.go @@ -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) + }) + } +}