diff --git a/internal/osbuild2/inline_source.go b/internal/osbuild2/inline_source.go new file mode 100644 index 000000000..dc47a9d35 --- /dev/null +++ b/internal/osbuild2/inline_source.go @@ -0,0 +1,41 @@ +package osbuild2 + +import ( + "crypto/sha256" + "encoding/base64" + "fmt" +) + +type InlineSource struct { + Items map[string]InlineSourceItem `json:"items"` +} + +func (InlineSource) isSource() {} + +type InlineSourceItem struct { + Encoding string `json:"encoding"` + Data string `json:"data"` +} + +func NewInlineSource() *InlineSource { + return &InlineSource{ + Items: make(map[string]InlineSourceItem), + } +} + +// AddItem a new item to the source. Well hash and encode that data +// and return the checksum. +func (s *InlineSource) AddItem(data string) string { + + dataBytes := []byte(data) + + encoded := base64.StdEncoding.EncodeToString(dataBytes) + name := fmt.Sprintf("sha256:%x", sha256.Sum256(dataBytes)) + + s.Items[name] = InlineSourceItem{ + Encoding: "base64", + Data: encoded, + } + + return name +} diff --git a/internal/osbuild2/inline_source_test.go b/internal/osbuild2/inline_source_test.go new file mode 100644 index 000000000..ff6192fa7 --- /dev/null +++ b/internal/osbuild2/inline_source_test.go @@ -0,0 +1,32 @@ +package osbuild2 + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInlineSource(t *testing.T) { + + assert := assert.New(t) + + tests := []struct { + data string + hash string + encoded string + }{ + {"42\n", "sha256:084c799cd551dd1d8d5c5f9a5d593b2e931f5e36122ee5c793c1d08a19839cc0", "NDIK"}, + {"Hallo Welt\n", "sha256:f950375066d74787f31cbd8f9f91c71819357cad243fb9d4a0d9ef4fa76709e0", "SGFsbG8gV2VsdAo="}, + } + + ils := NewInlineSource() + + for _, tt := range tests { + hash := ils.AddItem(tt.data) + assert.Equal(tt.hash, hash) + + item := ils.Items[hash] + assert.Equal(item.Data, tt.encoded) + } + +} diff --git a/internal/osbuild2/source.go b/internal/osbuild2/source.go index 61568bf43..5bb48305a 100644 --- a/internal/osbuild2/source.go +++ b/internal/osbuild2/source.go @@ -33,6 +33,8 @@ func (sources *Sources) UnmarshalJSON(data []byte) error { switch name { case "org.osbuild.curl": source = new(CurlSource) + case "org.osbuild.inline": + source = new(InlineSource) case "org.osbuild.ostree": source = new(OSTreeSource) default: