Skip to content

Commit

Permalink
blueprint: extract unmarshalTOMLviaJSON() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
mvo5 authored and achilleas-k committed Nov 22, 2024
1 parent 192b5b0 commit c839c44
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
21 changes: 4 additions & 17 deletions pkg/blueprint/filesystem_customizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,6 @@ type filesystemCustomizationMarshaling struct {
MinSize datasizes.Size `json:"minsize,omitempty" toml:"minsize,omitempty"`
}

func (fsc *FilesystemCustomization) UnmarshalTOML(data any) error {
// This is the most efficient way to reuse code when unmarshaling
// structs in toml, it leaks json errors which is a bit sad but
// because the toml unmarshaler gives us not "[]byte" but an
// already pre-processed "any" we cannot just unmarshal into our
// "fooMarshaling" struct and reuse the result so we resort to
// this workaround (but toml will go away long term anyway).
dataJSON, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("error unmarshaling TOML data %v: %w", data, err)
}
if err := fsc.UnmarshalJSON(dataJSON); err != nil {
return fmt.Errorf("error decoding TOML %v: %w", data, err)
}
return nil
}

func (fsc *FilesystemCustomization) UnmarshalJSON(data []byte) error {
var fc filesystemCustomizationMarshaling
if err := json.Unmarshal(data, &fc); err != nil {
Expand All @@ -50,6 +33,10 @@ func (fsc *FilesystemCustomization) UnmarshalJSON(data []byte) error {
return nil
}

func (fsc *FilesystemCustomization) UnmarshalTOML(data any) error {
return unmarshalTOMLviaJSON(fsc, data)
}

// CheckMountpointsPolicy checks if the mountpoints are allowed by the policy
func CheckMountpointsPolicy(mountpoints []FilesystemCustomization, mountpointAllowList *pathpolicy.PathPolicies) error {
var errs []error
Expand Down
24 changes: 24 additions & 0 deletions pkg/blueprint/toml_json_bridge.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package blueprint

import (
"encoding/json"
"fmt"
)

// XXX: move to interal/common ?
func unmarshalTOMLviaJSON(u json.Unmarshaler, data any) error {
// This is the most efficient way to reuse code when unmarshaling
// structs in toml, it leaks json errors which is a bit sad but
// because the toml unmarshaler gives us not "[]byte" but an
// already pre-processed "any" we cannot just unmarshal into our
// "fooMarshaling" struct and reuse the result so we resort to
// this workaround (but toml will go away long term anyway).
dataJSON, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("error unmarshaling TOML data %v: %w", data, err)
}
if err := u.UnmarshalJSON(dataJSON); err != nil {
return fmt.Errorf("error decoding TOML %v: %w", data, err)
}
return nil
}

0 comments on commit c839c44

Please sign in to comment.