Debian Codegraph @

cmd/go-yaml/node.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // YAML node formatting utilities for the go-yaml tool.
5
6 package main
7
8 import (
9 "fmt"
10
11 "go.yaml.in/yaml/v4"
12 )
13
14 // TagDirectiveInfo represents a YAML %TAG directive
15 type TagDirectiveInfo struct {
16 Handle string `yaml:"handle"`
17 Prefix string `yaml:"prefix"`
18 }
19
20 // MapItem is a single item in a MapSlice.
21 type MapItem struct {
22 Key string
23 Value any
24 }
25
26 // MapSlice is a slice of MapItems that preserves order when marshaled to YAML.
27 type MapSlice []MapItem
28
29 // MarshalYAML implements yaml.Marshaler for MapSlice to preserve key order.
30 func (ms MapSlice) MarshalYAML() (any, error) {
31 // Convert MapSlice to yaml.Node with MappingNode kind to preserve order
32 node := &yaml.Node{
33 Kind: yaml.MappingNode,
34 }
35 for _, item := range ms {
36 // Add key node
37 keyNode := &yaml.Node{
38 Kind: yaml.ScalarNode,
39 Value: item.Key,
40 }
41 // Add value node - let yaml dumper handle the value
42 // Dump item.Value directly into a yaml.Node
43 valueNode := &yaml.Node{}
44 if err := valueNode.Dump(item.Value); err != nil {
45 return nil, err
46 }
47 node.Content = append(node.Content, keyNode, valueNode)
48 }
49 return node, nil
50 }
51
52 // NodeInfo represents the information about a YAML node
53 type NodeInfo struct {
54 Kind string `yaml:"kind"`
55 Style string `yaml:"style,omitempty"`
56 Anchor string `yaml:"anchor,omitempty"`
57 Tag string `yaml:"tag,omitempty"`
58 Head string `yaml:"head,omitempty"`
59 Line string `yaml:"line,omitempty"`
60 Foot string `yaml:"foot,omitempty"`
61 Text string `yaml:"text,omitempty"`
62 Content []*NodeInfo `yaml:"content,omitempty"`
63 Encoding string `yaml:"encoding,omitempty"`
64 Version string `yaml:"version,omitempty"`
65 TagDirectives []TagDirectiveInfo `yaml:"tag-directives,omitempty"`
66 }
67
68 // FormatNode converts a YAML node into a NodeInfo structure
69 func FormatNode(n yaml.Node, profuse bool) *NodeInfo {
70 info := &NodeInfo{
71 Kind: formatKind(n.Kind),
72 }
73
74 // Don't set style for Document or Stream nodes
75 if n.Kind != yaml.DocumentNode && n.Kind != yaml.StreamNode {
76 if style := formatStyle(n.Style, profuse); style != "" {
77 info.Style = style
78 }
79 }
80 if n.Anchor != "" {
81 info.Anchor = n.Anchor
82 }
83 if tag := formatTag(n.Tag, n.Style, profuse); tag != "" {
84 info.Tag = tag
85 }
86 if n.HeadComment != "" {
87 info.Head = n.HeadComment
88 }
89 if n.LineComment != "" {
90 info.Line = n.LineComment
91 }
92 if n.FootComment != "" {
93 info.Foot = n.FootComment
94 }
95
96 if info.Kind == "Scalar" {
97 info.Text = n.Value
98 } else if n.Content != nil {
99 info.Content = make([]*NodeInfo, len(n.Content))
100 for i, node := range n.Content {
101 info.Content[i] = FormatNode(*node, profuse)
102 }
103 }
104
105 // Handle StreamNode-specific fields
106 if info.Kind == "Stream" && n.Stream != nil {
107 if n.Stream.Encoding != 0 {
108 info.Encoding = formatEncoding(n.Stream.Encoding)
109 }
110 if n.Stream.Version != nil {
111 info.Version = formatVersion(n.Stream.Version)
112 }
113 if len(n.Stream.TagDirectives) > 0 {
114 info.TagDirectives = make([]TagDirectiveInfo, len(n.Stream.TagDirectives))
115 for i, td := range n.Stream.TagDirectives {
116 info.TagDirectives[i] = TagDirectiveInfo{
117 Handle: td.Handle,
118 Prefix: td.Prefix,
119 }
120 }
121 }
122 }
123
124 return info
125 }
126
127 // formatEncoding converts an encoding constant to its string representation.
128 func formatEncoding(e yaml.Encoding) string {
129 switch e {
130 case yaml.EncodingAny:
131 return "Any"
132 case yaml.EncodingUTF8:
133 return "UTF-8"
134 case yaml.EncodingUTF16LE:
135 return "UTF-16LE"
136 case yaml.EncodingUTF16BE:
137 return "UTF-16BE"
138 default:
139 return "Unknown"
140 }
141 }
142
143 // formatVersion converts a VersionDirective to its string representation.
144 func formatVersion(v *yaml.VersionDirective) string {
145 if v == nil {
146 return ""
147 }
148 return fmt.Sprintf("%d.%d", v.Major, v.Minor)
149 }
150
151 // formatKind converts a YAML node kind into its string representation.
152 func formatKind(k yaml.Kind) string {
153 switch k {
154 case yaml.DocumentNode:
155 return "Document"
156 case yaml.SequenceNode:
157 return "Sequence"
158 case yaml.MappingNode:
159 return "Mapping"
160 case yaml.ScalarNode:
161 return "Scalar"
162 case yaml.AliasNode:
163 return "Alias"
164 case yaml.StreamNode:
165 return "Stream"
166 default:
167 return "Unknown"
168 }
169 }
170
171 // formatStyle converts a YAML node style into its string representation.
172 func formatStyle(s yaml.Style, profuse bool) string {
173 // Remove tagged style bit for checking base style
174 baseStyle := s &^ yaml.TaggedStyle
175
176 switch baseStyle {
177 case yaml.DoubleQuotedStyle:
178 return "Double"
179 case yaml.SingleQuotedStyle:
180 return "Single"
181 case yaml.LiteralStyle:
182 return "Literal"
183 case yaml.FoldedStyle:
184 return "Folded"
185 case yaml.FlowStyle:
186 return "Flow"
187 case 0:
188 // Plain style - only show if profuse
189 if profuse {
190 return "Plain"
191 }
192 }
193 return ""
194 }
195
196 // formatStyleName converts a YAML node style into a lowercase style name.
197 // Always returns a style name (defaults to "plain" for style 0).
198 func formatStyleName(s yaml.Style) string {
199 // Remove tagged style bit for checking base style
200 baseStyle := s &^ yaml.TaggedStyle
201
202 switch baseStyle {
203 case yaml.DoubleQuotedStyle:
204 return "double"
205 case yaml.SingleQuotedStyle:
206 return "single"
207 case yaml.LiteralStyle:
208 return "literal"
209 case yaml.FoldedStyle:
210 return "folded"
211 case yaml.FlowStyle:
212 return "flow"
213 case 0:
214 return "plain"
215 default:
216 return "unknown"
217 }
218 }
219
220 // formatTag converts a YAML tag string to its string representation.
221 func formatTag(tag string, style yaml.Style, profuse bool) string {
222 // Check if the tag was explicit in the input
223 tagWasExplicit := style&yaml.TaggedStyle != 0
224
225 // In profuse mode, always show tag
226 if profuse {
227 return tag
228 }
229
230 // Default YAML tags - only show if they were explicit in the input
231 switch tag {
232 case "!!str", "!!map", "!!seq", "!!int", "!!float", "!!bool", "!!null":
233 if tagWasExplicit {
234 return tag
235 }
236 return ""
237 }
238
239 // Show all other tags (custom tags)
240 return tag
241 }
242
243 // FormatNodeCompact converts a YAML node into a compact representation.
244 // Document nodes return their content directly.
245 // Mapping/Sequence nodes use lowercase keys: "mapping:", "sequence:".
246 // Scalar nodes use style as key: "plain:", "double:", etc.
247 func FormatNodeCompact(n yaml.Node) any {
248 switch n.Kind {
249 case yaml.DocumentNode:
250 // Check if document has properties that need to be preserved
251 hasProperties := n.Anchor != "" || n.HeadComment != "" || n.LineComment != "" || n.FootComment != ""
252 if tag := formatTag(n.Tag, n.Style, false); tag != "" && tag != "!!str" {
253 hasProperties = true
254 }
255
256 // If document has no properties, return content directly (unwrap)
257 if !hasProperties {
258 if len(n.Content) > 0 {
259 return FormatNodeCompact(*n.Content[0])
260 }
261 return nil
262 }
263
264 // Document has properties - create a result map with ordered keys
265 result := MapSlice{}
266
267 // Add optional fields in order: anchor, tag, comments
268 if n.Anchor != "" {
269 result = append(result, MapItem{Key: "anchor", Value: n.Anchor})
270 }
271 if tag := formatTag(n.Tag, n.Style, false); tag != "" && tag != "!!str" {
272 result = append(result, MapItem{Key: "tag", Value: tag})
273 }
274 if n.HeadComment != "" {
275 result = append(result, MapItem{Key: "head", Value: n.HeadComment})
276 }
277 if n.LineComment != "" {
278 result = append(result, MapItem{Key: "line", Value: n.LineComment})
279 }
280 if n.FootComment != "" {
281 result = append(result, MapItem{Key: "foot", Value: n.FootComment})
282 }
283
284 // Add content if present
285 if len(n.Content) > 0 {
286 content := FormatNodeCompact(*n.Content[0])
287 // Merge the content into result at the top level
288 if contentMap, ok := content.(MapSlice); ok {
289 result = append(result, contentMap...)
290 }
291 }
292
293 return result
294
295 case yaml.MappingNode:
296 result := MapSlice{}
297
298 // Add optional fields in order: anchor, tag, comments
299 if n.Anchor != "" {
300 result = append(result, MapItem{Key: "anchor", Value: n.Anchor})
301 }
302 if tag := formatTag(n.Tag, n.Style, false); tag != "" && tag != "!!str" {
303 result = append(result, MapItem{Key: "tag", Value: tag})
304 }
305 if n.HeadComment != "" {
306 result = append(result, MapItem{Key: "head", Value: n.HeadComment})
307 }
308 if n.LineComment != "" {
309 result = append(result, MapItem{Key: "line", Value: n.LineComment})
310 }
311 if n.FootComment != "" {
312 result = append(result, MapItem{Key: "foot", Value: n.FootComment})
313 }
314
315 // Convert content (added last)
316 var content []any
317 for _, node := range n.Content {
318 content = append(content, FormatNodeCompact(*node))
319 }
320 result = append(result, MapItem{Key: "mapping", Value: content})
321 return result
322
323 case yaml.SequenceNode:
324 result := MapSlice{}
325
326 // Add optional fields in order: anchor, tag, comments
327 if n.Anchor != "" {
328 result = append(result, MapItem{Key: "anchor", Value: n.Anchor})
329 }
330 if tag := formatTag(n.Tag, n.Style, false); tag != "" && tag != "!!str" {
331 result = append(result, MapItem{Key: "tag", Value: tag})
332 }
333 if n.HeadComment != "" {
334 result = append(result, MapItem{Key: "head", Value: n.HeadComment})
335 }
336 if n.LineComment != "" {
337 result = append(result, MapItem{Key: "line", Value: n.LineComment})
338 }
339 if n.FootComment != "" {
340 result = append(result, MapItem{Key: "foot", Value: n.FootComment})
341 }
342
343 // Convert content (added last)
344 var content []any
345 for _, node := range n.Content {
346 content = append(content, FormatNodeCompact(*node))
347 }
348 result = append(result, MapItem{Key: "sequence", Value: content})
349 return result
350
351 case yaml.ScalarNode:
352 result := MapSlice{}
353
354 // Add optional fields in order: anchor, tag, comments
355 if n.Anchor != "" {
356 result = append(result, MapItem{Key: "anchor", Value: n.Anchor})
357 }
358 if tag := formatTag(n.Tag, n.Style, false); tag != "" && tag != "!!str" {
359 result = append(result, MapItem{Key: "tag", Value: tag})
360 }
361 if n.HeadComment != "" {
362 result = append(result, MapItem{Key: "head", Value: n.HeadComment})
363 }
364 if n.LineComment != "" {
365 result = append(result, MapItem{Key: "line", Value: n.LineComment})
366 }
367 if n.FootComment != "" {
368 result = append(result, MapItem{Key: "foot", Value: n.FootComment})
369 }
370
371 // Use style name as the key (added last)
372 styleName := formatStyleName(n.Style)
373 result = append(result, MapItem{Key: styleName, Value: n.Value})
374 return result
375
376 case yaml.AliasNode:
377 result := MapSlice{}
378 result = append(result, MapItem{Key: "alias", Value: n.Value})
379 return result
380
381 case yaml.StreamNode:
382 result := MapSlice{}
383
384 // Build stream content
385 content := MapSlice{}
386
387 if n.Stream != nil {
388 // Add encoding if present
389 if n.Stream.Encoding != 0 {
390 content = append(content, MapItem{Key: "encoding", Value: formatEncoding(n.Stream.Encoding)})
391 }
392
393 // Add version if present
394 if n.Stream.Version != nil {
395 content = append(content, MapItem{Key: "version", Value: formatVersion(n.Stream.Version)})
396 }
397
398 // Add tag directives if present
399 if len(n.Stream.TagDirectives) > 0 {
400 var directives []TagDirectiveInfo
401 for _, td := range n.Stream.TagDirectives {
402 directives = append(directives, TagDirectiveInfo{
403 Handle: td.Handle,
404 Prefix: td.Prefix,
405 })
406 }
407 content = append(content, MapItem{Key: "tag-directives", Value: directives})
408 }
409 }
410
411 // Use content as value, or null if empty
412 if len(content) > 0 {
413 result = append(result, MapItem{Key: "stream", Value: content})
414 } else {
415 result = append(result, MapItem{Key: "stream", Value: nil})
416 }
417
418 return result
419
420 default:
421 return nil
422 }
423 }