golang.org/x/arch@v0.17.0/internal/unify/yaml_test.go (about)

     1  // Copyright 2025 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package unify
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"iter"
    11  
    12  	"gopkg.in/yaml.v3"
    13  )
    14  
    15  func mustParse(expr string) Closure {
    16  	var c Closure
    17  	if err := yaml.Unmarshal([]byte(expr), &c); err != nil {
    18  		panic(err)
    19  	}
    20  	return c
    21  }
    22  
    23  func printYaml(val any) {
    24  	b, err := yaml.Marshal(val)
    25  	if err != nil {
    26  		panic(err)
    27  	}
    28  	var node yaml.Node
    29  	if err := yaml.Unmarshal(b, &node); err != nil {
    30  		panic(err)
    31  	}
    32  
    33  	// Map lines to start offsets. We'll use this to figure out when nodes are
    34  	// "small" and should use inline style.
    35  	lines := []int{-1, 0}
    36  	for pos := 0; pos < len(b); {
    37  		next := bytes.IndexByte(b[pos:], '\n')
    38  		if next == -1 {
    39  			break
    40  		}
    41  		pos += next + 1
    42  		lines = append(lines, pos)
    43  	}
    44  	lines = append(lines, len(b))
    45  
    46  	// Strip comments and switch small nodes to inline style
    47  	cleanYaml(&node, lines, len(b))
    48  
    49  	b, err = yaml.Marshal(&node)
    50  	if err != nil {
    51  		panic(err)
    52  	}
    53  	fmt.Println(string(b))
    54  }
    55  
    56  func cleanYaml(node *yaml.Node, lines []int, endPos int) {
    57  	node.HeadComment = ""
    58  	node.FootComment = ""
    59  	node.LineComment = ""
    60  
    61  	for i, n2 := range node.Content {
    62  		end2 := endPos
    63  		if i < len(node.Content)-1 {
    64  			end2 = lines[node.Content[i+1].Line]
    65  		}
    66  		cleanYaml(n2, lines, end2)
    67  	}
    68  
    69  	// Use inline style?
    70  	switch node.Kind {
    71  	case yaml.MappingNode, yaml.SequenceNode:
    72  		if endPos-lines[node.Line] < 40 {
    73  			node.Style = yaml.FlowStyle
    74  		}
    75  	}
    76  }
    77  
    78  func allYamlNodes(n *yaml.Node) iter.Seq[*yaml.Node] {
    79  	return func(yield func(*yaml.Node) bool) {
    80  		if !yield(n) {
    81  			return
    82  		}
    83  		for _, n2 := range n.Content {
    84  			for n3 := range allYamlNodes(n2) {
    85  				if !yield(n3) {
    86  					return
    87  				}
    88  			}
    89  		}
    90  	}
    91  }