From 1655b7dad8bb4e1cc7c402fac75dddf998dc5621 Mon Sep 17 00:00:00 2001 From: nscuro Date: Mon, 26 Sep 2022 19:51:26 +0200 Subject: [PATCH] feat: set `SpecVersion` when decoding from xml `SpecVersion` as a field is only used in the json format, but when working with `BOM` instances it is useful to know what spec version one is dealing with. Signed-off-by: nscuro --- decode.go | 14 +++++++++++++- decode_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/decode.go b/decode.go index 06dacd4..fdf0529 100644 --- a/decode.go +++ b/decode.go @@ -49,5 +49,17 @@ type xmlBOMDecoder struct { // Decode implements the BOMDecoder interface. func (x xmlBOMDecoder) Decode(bom *BOM) error { - return xml.NewDecoder(x.reader).Decode(bom) + err := xml.NewDecoder(x.reader).Decode(bom) + if err != nil { + return err + } + + for specVersion, xmlNs := range xmlNamespaces { + if xmlNs == bom.XMLNS { + bom.SpecVersion = specVersion + break + } + } + + return nil } diff --git a/decode_test.go b/decode_test.go index 0bd4ae4..9d10c03 100644 --- a/decode_test.go +++ b/decode_test.go @@ -18,12 +18,57 @@ package cyclonedx import ( + "strings" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewBOMDecoder(t *testing.T) { assert.IsType(t, &jsonBOMDecoder{}, NewBOMDecoder(nil, BOMFileFormatJSON)) assert.IsType(t, &xmlBOMDecoder{}, NewBOMDecoder(nil, BOMFileFormatXML)) } + +func TestXmlBOMDecoder_Decode(t *testing.T) { + t.Run("ShouldSetSpecVersion", func(t *testing.T) { + testCases := []struct { + bomContent string + specVersion SpecVersion + }{ + { + bomContent: ``, + specVersion: SpecVersion1_0, + }, + { + bomContent: ``, + specVersion: SpecVersion1_1, + }, + { + bomContent: ``, + specVersion: SpecVersion1_2, + }, + { + bomContent: ``, + specVersion: SpecVersion1_3, + }, + { + bomContent: ``, + specVersion: SpecVersion1_4, + }, + { + bomContent: ``, + specVersion: SpecVersion(0), + }, + } + + for _, tc := range testCases { + t.Run(tc.specVersion.String(), func(t *testing.T) { + var bom BOM + err := NewBOMDecoder(strings.NewReader(tc.bomContent), BOMFileFormatXML).Decode(&bom) + require.NoError(t, err) + require.Equal(t, tc.specVersion, bom.SpecVersion) + }) + } + }) +}