driftctl/pkg/resource/deserializer.go

50 lines
1.2 KiB
Go
Raw Permalink Normal View History

2021-05-21 14:09:45 +00:00
package resource
import (
"encoding/json"
"github.com/snyk/driftctl/enumeration/resource"
2021-05-21 14:09:45 +00:00
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
2021-05-21 14:09:45 +00:00
)
type Deserializer struct {
factory resource.ResourceFactory
2021-05-21 14:09:45 +00:00
}
func NewDeserializer(factory resource.ResourceFactory) *Deserializer {
2021-05-21 14:09:45 +00:00
return &Deserializer{factory}
}
func (s *Deserializer) Deserialize(ty string, rawList []cty.Value) ([]*resource.Resource, error) {
resources := make([]*resource.Resource, 0)
2021-05-21 14:09:45 +00:00
for _, rawResource := range rawList {
rawResource := rawResource
2021-06-11 15:10:06 +00:00
res, err := s.DeserializeOne(ty, rawResource)
if err != nil {
return nil, err
}
2021-05-21 14:09:45 +00:00
resources = append(resources, res)
}
return resources, nil
}
2021-06-11 15:10:06 +00:00
func (s *Deserializer) DeserializeOne(ty string, value cty.Value) (*resource.Resource, error) {
2021-07-06 09:14:51 +00:00
if value.IsNull() {
return nil, nil
}
2021-06-11 15:10:06 +00:00
2021-10-01 13:43:59 +00:00
// Marked values cannot be deserialized to JSON.
// For example, this ensures we can deserialize sensitive values too.
unmarkedVal, _ := value.UnmarkDeep()
var attrs resource.Attributes
2021-10-01 13:43:59 +00:00
bytes, _ := ctyjson.Marshal(unmarkedVal, unmarkedVal.Type())
2021-06-11 15:10:06 +00:00
err := json.Unmarshal(bytes, &attrs)
if err != nil {
return nil, err
}
return s.factory.CreateAbstractResource(ty, value.GetAttr("id").AsString(), attrs), nil
}