1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
|
package yamlutils
import (
"fmt"
"iter"
"slices"
"sort"
"strconv"
"github.com/go-openapi/swag/conv"
"github.com/go-openapi/swag/jsonutils"
"github.com/go-openapi/swag/jsonutils/adapters/ifaces"
"github.com/go-openapi/swag/typeutils"
yaml "go.yaml.in/yaml/v3"
)
var (
_ yaml.Marshaler = YAMLMapSlice{}
_ yaml.Unmarshaler = &YAMLMapSlice{}
)
// YAMLMapSlice represents a YAML object, with the order of keys maintained.
//
// It is similar to [jsonutils.JSONMapSlice] and also knows how to marshal and unmarshal YAML.
//
// It behaves like an ordered map, but keys can't be accessed in constant time.
type YAMLMapSlice []YAMLMapItem
// YAMLMapItem represents the value of a key in a YAML object held by [YAMLMapSlice].
//
// It is entirely equivalent to [jsonutils.JSONMapItem], with the same limitation that
// you should not Marshal or Unmarshal directly this type, outside of a [YAMLMapSlice].
type YAMLMapItem = jsonutils.JSONMapItem
func (s YAMLMapSlice) OrderedItems() iter.Seq2[string, any] {
return func(yield func(string, any) bool) {
for _, item := range s {
if !yield(item.Key, item.Value) {
return
}
}
}
}
// SetOrderedItems implements [ifaces.SetOrdered]: it merges keys passed by the iterator argument
// into the [YAMLMapSlice].
func (s *YAMLMapSlice) SetOrderedItems(items iter.Seq2[string, any]) {
if items == nil {
// force receiver to be a nil slice
*s = nil
return
}
m := *s
if len(m) > 0 {
// update mode: short-circuited when unmarshaling fresh data structures
idx := make(map[string]int, len(m))
for i, item := range m {
idx[item.Key] = i
}
for k, v := range items {
idx, ok := idx[k]
if ok {
m[idx].Value = v
continue
}
m = append(m, YAMLMapItem{Key: k, Value: v})
}
*s = m
return
}
for k, v := range items {
m = append(m, YAMLMapItem{Key: k, Value: v})
}
*s = m
}
// MarshalJSON renders this YAML object as JSON bytes.
//
// The difference with standard JSON marshaling is that the order of keys is maintained.
func (s YAMLMapSlice) MarshalJSON() ([]byte, error) {
return jsonutils.JSONMapSlice(s).MarshalJSON()
}
// UnmarshalJSON builds this YAML object from JSON bytes.
//
// The difference with standard JSON marshaling is that the order of keys is maintained.
func (s *YAMLMapSlice) UnmarshalJSON(data []byte) error {
js := jsonutils.JSONMapSlice(*s)
if err := js.UnmarshalJSON(data); err != nil {
return err
}
*s = YAMLMapSlice(js)
return nil
}
// MarshalYAML produces a YAML document as bytes
//
// The difference with standard YAML marshaling is that the order of keys is maintained.
//
// It implements [yaml.Marshaler].
func (s YAMLMapSlice) MarshalYAML() (any, error) {
if typeutils.IsNil(s) {
return []byte("null\n"), nil
}
var n yaml.Node
n.Kind = yaml.DocumentNode
var nodes []*yaml.Node
for _, item := range s {
nn, err := json2yaml(item.Value)
if err != nil {
return nil, err
}
ns := []*yaml.Node{
{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: item.Key,
},
nn,
}
nodes = append(nodes, ns...)
}
n.Content = []*yaml.Node{
{
Kind: yaml.MappingNode,
Content: nodes,
},
}
return yaml.Marshal(&n)
}
// UnmarshalYAML builds a YAMLMapSlice object from a YAML document [yaml.Node].
//
// It implements [yaml.Unmarshaler].
func (s *YAMLMapSlice) UnmarshalYAML(node *yaml.Node) error {
if typeutils.IsNil(*s) {
// allow to unmarshal with a simple var declaration (nil slice)
*s = YAMLMapSlice{}
}
if node == nil {
*s = nil
return nil
}
const sensibleAllocDivider = 2
m := slices.Grow(*s, len(node.Content)/sensibleAllocDivider)
m = m[:0]
for i := 0; i < len(node.Content); i += 2 {
var nmi YAMLMapItem
k, err := yamlStringScalarC(node.Content[i])
if err != nil {
return fmt.Errorf("unable to decode YAML map key: %w: %w", err, ErrYAML)
}
nmi.Key = k
v, err := yamlNode(node.Content[i+1])
if err != nil {
return fmt.Errorf("unable to process YAML map value for key %q: %w: %w", k, err, ErrYAML)
}
nmi.Value = v
m = append(m, nmi)
}
*s = m
return nil
}
func json2yaml(item any) (*yaml.Node, error) {
if typeutils.IsNil(item) {
return &yaml.Node{
Kind: yaml.ScalarNode,
Value: "null",
}, nil
}
switch val := item.(type) {
case ifaces.Ordered:
return orderedYAML(val)
case map[string]any:
var n yaml.Node
n.Kind = yaml.MappingNode
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := val[k]
childNode, err := json2yaml(v)
if err != nil {
return nil, err
}
n.Content = append(n.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: k,
}, childNode)
}
return &n, nil
case []any:
var n yaml.Node
n.Kind = yaml.SequenceNode
for i := range val {
childNode, err := json2yaml(val[i])
if err != nil {
return nil, err
}
n.Content = append(n.Content, childNode)
}
return &n, nil
case string:
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: val,
}, nil
case float32:
return floatNode(val)
case float64:
return floatNode(val)
case int:
return integerNode(val)
case int8:
return integerNode(val)
case int16:
return integerNode(val)
case int32:
return integerNode(val)
case int64:
return integerNode(val)
case uint:
return uintegerNode(val)
case uint8:
return uintegerNode(val)
case uint16:
return uintegerNode(val)
case uint32:
return uintegerNode(val)
case uint64:
return uintegerNode(val)
case bool:
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlBoolScalar,
Value: strconv.FormatBool(val),
}, nil
default:
return nil, fmt.Errorf("unhandled type: %T: %w", val, ErrYAML)
}
}
func floatNode[T conv.Float](val T) (*yaml.Node, error) {
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlFloatScalar,
Value: conv.FormatFloat(val),
}, nil
}
func integerNode[T conv.Signed](val T) (*yaml.Node, error) {
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlIntScalar,
Value: conv.FormatInteger(val),
}, nil
}
func uintegerNode[T conv.Unsigned](val T) (*yaml.Node, error) {
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlIntScalar,
Value: conv.FormatUinteger(val),
}, nil
}
func orderedYAML[T ifaces.Ordered](val T) (*yaml.Node, error) {
var n yaml.Node
n.Kind = yaml.MappingNode
for key, value := range val.OrderedItems() {
childNode, err := json2yaml(value)
if err != nil {
return nil, err
}
n.Content = append(n.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: yamlStringScalar,
Value: key,
}, childNode)
}
return &n, nil
}
|