-
Notifications
You must be signed in to change notification settings - Fork 135
/
metas.go
116 lines (96 loc) · 2.62 KB
/
metas.go
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
package yamltemplate
import (
"fmt"
"strings"
"unicode"
"github.com/k14s/ytt/pkg/structmeta"
"github.com/k14s/ytt/pkg/template"
"github.com/k14s/ytt/pkg/yamlmeta"
)
var (
nodeSpecificKeywords = map[string]string{
"if/end": "if",
"else/end": "else",
"elif/end": "elif",
"for/end": "for",
"def/end": "def",
}
)
type Metas struct {
Block []*yamlmeta.Meta // meant to execute some code
Values []*yamlmeta.Meta // meant to return interpolated value
Annotations []MetaAndAnnotation
needsEnds int
}
type MetaAndAnnotation struct {
Meta *yamlmeta.Meta
Annotation *structmeta.Annotation
}
func NewStructMetaFromMeta(meta *yamlmeta.Meta) (structmeta.Meta, error) {
structMeta, err := structmeta.NewMetaFromString(meta.Data)
if err != nil {
return structmeta.Meta{}, fmt.Errorf(
"Unknown comment syntax at %s: '%s': %s",
meta.Position.AsString(), meta.Data, err)
}
return structMeta, nil
}
func NewMetas(node yamlmeta.Node) (Metas, error) {
metas := Metas{}
for _, meta := range node.GetMetas() {
structMeta, err := NewStructMetaFromMeta(meta)
if err != nil {
return metas, err
}
for _, ann := range structMeta.Annotations {
if len(ann.Name) == 0 {
// Default code and value annotations to make templates less verbose
ann.Name = template.AnnotationCode
if node.GetPosition().IsKnown() {
if meta.Position.Line() == node.GetPosition().Line() {
ann.Name = template.AnnotationValue
}
}
}
switch ann.Name {
case template.AnnotationValue:
metas.Values = append(metas.Values, &yamlmeta.Meta{
Position: meta.Position,
Data: ann.Content,
})
case template.AnnotationCode:
if metas.needsEnds > 0 {
return metas, fmt.Errorf(
"Unexpected code at %s after use of '*/end', expected YAML node",
meta.Position.AsString())
}
code := ann.Content
spacePrefix := metas.spacePrefix(code)
for keyword, replacementKeyword := range nodeSpecificKeywords {
if strings.HasPrefix(code, spacePrefix+keyword) {
metas.needsEnds += 1
code = strings.Replace(code, spacePrefix+keyword, spacePrefix+replacementKeyword, 1)
}
}
metas.Block = append(metas.Block, &yamlmeta.Meta{
Position: meta.Position,
Data: code,
})
case template.AnnotationComment:
// ignore
default:
metas.Annotations = append(metas.Annotations, MetaAndAnnotation{meta, ann})
}
}
}
return metas, nil
}
func (m Metas) NeedsEnd() bool { return m.needsEnds != 0 }
func (m Metas) spacePrefix(str string) string {
for i, r := range str {
if !unicode.IsSpace(r) {
return str[:i]
}
}
return ""
}