2024-01-17 14:26:33 +00:00
|
|
|
package yamlsaver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"slices"
|
|
|
|
|
|
|
|
"github.com/databricks/cli/libs/dyn"
|
|
|
|
"github.com/databricks/cli/libs/dyn/convert"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Converts a struct to map. Skips any nil fields.
|
|
|
|
// It uses `skipFields` to skip unnecessary fields.
|
|
|
|
// Uses `order` to define the order of keys in resulting outout
|
|
|
|
func ConvertToMapValue(strct any, order *Order, skipFields []string, dst map[string]dyn.Value) (dyn.Value, error) {
|
|
|
|
ref := dyn.NilValue
|
|
|
|
mv, err := convert.FromTyped(strct, ref)
|
|
|
|
if err != nil {
|
2024-06-21 14:22:42 +00:00
|
|
|
return dyn.InvalidValue, err
|
2024-01-17 14:26:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if mv.Kind() != dyn.KindMap {
|
|
|
|
return dyn.InvalidValue, fmt.Errorf("expected map, got %s", mv.Kind())
|
|
|
|
}
|
|
|
|
|
|
|
|
return skipAndOrder(mv, order, skipFields, dst)
|
|
|
|
}
|
|
|
|
|
|
|
|
func skipAndOrder(mv dyn.Value, order *Order, skipFields []string, dst map[string]dyn.Value) (dyn.Value, error) {
|
2024-03-25 11:01:09 +00:00
|
|
|
for _, pair := range mv.MustMap().Pairs() {
|
|
|
|
k := pair.Key.MustString()
|
|
|
|
v := pair.Value
|
2024-01-17 14:26:33 +00:00
|
|
|
if v.Kind() == dyn.KindNil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if slices.Contains(skipFields, k) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the value is already defined in destination, it means it was
|
|
|
|
// manually set due to custom ordering or other customisation required
|
|
|
|
// So we're skipping processing it again
|
|
|
|
if _, ok := dst[k]; ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-07-16 11:27:27 +00:00
|
|
|
dst[k] = dyn.NewValue(v.Value(), []dyn.Location{{Line: order.Get(k)}})
|
2024-01-17 14:26:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return dyn.V(dst), nil
|
|
|
|
}
|