2021-05-21 14:09:45 +00:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
2021-06-02 10:01:55 +00:00
|
|
|
"encoding/json"
|
|
|
|
|
2022-06-28 07:23:29 +00:00
|
|
|
"github.com/snyk/driftctl/enumeration/resource"
|
2021-05-21 14:09:45 +00:00
|
|
|
"github.com/zclconf/go-cty/cty"
|
2021-06-02 10:01:55 +00:00
|
|
|
ctyjson "github.com/zclconf/go-cty/cty/json"
|
2021-05-21 14:09:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Deserializer struct {
|
2022-06-28 07:23:29 +00:00
|
|
|
factory resource.ResourceFactory
|
2021-05-21 14:09:45 +00:00
|
|
|
}
|
|
|
|
|
2022-06-28 07:23:29 +00:00
|
|
|
func NewDeserializer(factory resource.ResourceFactory) *Deserializer {
|
2021-05-21 14:09:45 +00:00
|
|
|
return &Deserializer{factory}
|
|
|
|
}
|
|
|
|
|
2022-06-28 07:23:29 +00:00
|
|
|
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)
|
2021-06-02 10:01:55 +00:00
|
|
|
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
|
|
|
|
2022-06-28 07:23:29 +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()
|
|
|
|
|
2022-06-28 07:23:29 +00:00
|
|
|
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
|
|
|
|
}
|