Debian Codegraph @

yaml/yaml.go

raw symbols SCIP
1 // Copyright 2019 Red Hat, Inc
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.)
14
15 package json
16
17 import (
18 "github.com/coreos/vcontext/tree"
19
20 "gopkg.in/yaml.v3"
21 )
22
23 func UnmarshalToContext(raw []byte) (tree.Node, error) {
24 var ast yaml.Node
25 if err := yaml.Unmarshal(raw, &ast); err != nil {
26 return nil, err
27 }
28 return fromYamlNode(ast), nil
29 }
30
31 func fromYamlNode(n yaml.Node) tree.Node {
32 m := tree.Marker{
33 StartP: &tree.Pos{
34 Line: int64(n.Line),
35 Column: int64(n.Column),
36 },
37 }
38 switch n.Kind {
39 case 0:
40 // empty
41 return nil
42 case yaml.DocumentNode:
43 if len(n.Content) == 0 {
44 return nil
45 }
46 return fromYamlNode(*n.Content[0])
47 case yaml.MappingNode:
48 ret := tree.MapNode{
49 Marker: m,
50 Children: make(map[string]tree.Node, len(n.Content)/2),
51 Keys: make(map[string]tree.Leaf, len(n.Content)/2),
52 }
53 // MappingNodes list keys and values like [k, v, k, v...]
54 for i := 0; i < len(n.Content); i += 2 {
55 key := *n.Content[i]
56 value := *n.Content[i+1]
57 ret.Keys[key.Value] = tree.Leaf{
58 Marker: tree.Marker{
59 StartP: &tree.Pos{
60 Line: int64(key.Line),
61 Column: int64(key.Column),
62 },
63 },
64 }
65 ret.Children[key.Value] = fromYamlNode(value)
66 }
67 return ret
68 case yaml.SequenceNode:
69 ret := tree.SliceNode{
70 Marker: m,
71 Children: make([]tree.Node, 0, len(n.Content)),
72 }
73 for _, child := range n.Content {
74 ret.Children = append(ret.Children, fromYamlNode(*child))
75 }
76 return ret
77 default: // scalars and aliases
78 return tree.Leaf{
79 Marker: m,
80 }
81 }
82 }