Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/chartconfig/load.go

raw symbols SCIP
1 // Copyright 2023 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 chartconfig
6
7 import (
8 _ "embed"
9 "fmt"
10 "reflect"
11 "sort"
12 "strconv"
13 "strings"
14 "unicode"
15 )
16
17 //go:embed config.txt
18 var chartConfig []byte
19
20 func Raw() []byte {
21 return chartConfig
22 }
23
24 // Load loads and parses the current chart config.
25 func Load() ([]ChartConfig, error) {
26 return Parse(chartConfig)
27 }
28
29 // Parse parses ChartConfig records from the provided raw data, returning an
30 // error if the config has invalid syntax. See the package documentation for a
31 // description of the record syntax.
32 //
33 // Even with correct syntax, the resulting chart config may not meet all the
34 // requirements described in the package doc. Call [Validate] to check whether
35 // the config data is coherent.
36 func Parse(data []byte) ([]ChartConfig, error) {
37 // Collect field information for the record type.
38 var (
39 prefixes []string // for parse errors
40 fields = make(map[string]reflect.StructField) // key -> struct field
41 )
42 {
43 typ := reflect.TypeOf(ChartConfig{})
44 for i := 0; i < typ.NumField(); i++ {
45 f := typ.Field(i)
46 key := strings.ToLower(f.Name)
47 if _, ok := fieldParsers[key]; !ok {
48 panic(fmt.Sprintf("no parser for field %q", f.Name))
49 }
50 prefixes = append(prefixes, "'"+key+":'")
51 fields[key] = f
52 }
53 sort.Strings(prefixes)
54 }
55
56 // Read records, separated by '---'
57 var (
58 records []ChartConfig
59 inProgress = new(ChartConfig) // record value currently being parsed
60 set = make(map[string]bool) // fields that are set so far; empty records are skipped
61 )
62 flushRecord := func() {
63 if len(set) > 0 { // only flush non-empty records
64 records = append(records, *inProgress)
65 }
66 inProgress = new(ChartConfig)
67 set = make(map[string]bool)
68 }
69
70 // Within bucket braces in counter fields, newlines are ignored.
71 // if we're in the middle of a multiline counter field, accumulatedCounterText
72 // contains the joined lines of the field up to the current line. Once
73 // a line containing an end brace is reached, line will be set to the
74 // joined lines of accumulatedCounterText and processed as a single line.
75 var accumulatedCounterText string
76
77 for lineNum, line := range strings.Split(string(data), "\n") {
78 if line == "---" {
79 if accumulatedCounterText != "" {
80 return nil, fmt.Errorf("line %d: reached end of record while processing multiline counter field", lineNum)
81 }
82 flushRecord()
83 continue
84 }
85 text, _, _ := strings.Cut(line, "#") // trim comments
86
87 // Processing of counter fields which can appear across multiple lines.
88 // See comment on accumulatedCounterText.
89 if accumulatedCounterText == "" {
90 if oi := strings.Index(text, "{"); oi >= 0 {
91 if strings.Contains(text[:oi], "}") {
92 return nil, fmt.Errorf("line %d: invalid line %q: unexpected '}'", lineNum, line)
93 }
94 if strings.Contains(text[oi+len("{"):], "{") {
95 return nil, fmt.Errorf("line %d: invalid line %q: unexpected '{'", lineNum, line)
96 }
97 if !strings.HasPrefix(text, "counter:") {
98 return nil, fmt.Errorf("line %d: invalid line %q: '{' is only allowed to appear within a counter field", lineNum, line)
99 }
100 accumulatedCounterText = strings.TrimRightFunc(text, unicode.IsSpace)
101 // Don't continue here. If the counter field is a single line
102 // the check for the close brace below will close the line
103 // and process it as text. Set text to "" so when it's appended to
104 // accumulatedCounterText we don't add the line twice.
105 text = ""
106 } else if strings.Contains(text, "}") {
107 return nil, fmt.Errorf("line %d: invalid line %q: unexpected '}'", lineNum, line)
108 }
109 }
110 if accumulatedCounterText != "" {
111 if strings.Contains(text, "{") {
112 return nil, fmt.Errorf("line %d: invalid line %q: '{' is only allowed to appear once within a counter field", lineNum, line)
113 }
114 accumulatedCounterText += strings.TrimSpace(text)
115 if ci := strings.Index(accumulatedCounterText, "}"); ci >= 0 {
116 if strings.Contains(accumulatedCounterText[ci+len("}"):], "}") {
117 return nil, fmt.Errorf("line %d: invalid line %q: unexpected '}'", lineNum, line)
118 }
119 if ci > 0 && strings.HasSuffix(accumulatedCounterText[:ci], ",") {
120 return nil, fmt.Errorf("line %d: invalid line %q: unexpected '}' after ','", lineNum, line)
121 }
122 text = accumulatedCounterText
123 accumulatedCounterText = ""
124 } else {
125 // We're in the middle of a multiline counter field. Continue
126 // processing.
127 continue
128 }
129 }
130
131 var key string
132 for k := range fields {
133 prefix := k + ":"
134 if strings.HasPrefix(text, prefix) {
135 key = k
136 text = text[len(prefix):]
137 break
138 }
139 }
140
141 text = strings.TrimSpace(text)
142 if text == "" {
143 // Check for empty lines before the field == nil check below.
144 // Lines consisting only of whitespace and comments are OK.
145 continue
146 }
147 if key == "" {
148 return nil, fmt.Errorf("line %d: invalid line %q: lines must be '---', consist only of whitespace/comments, or start with %s", lineNum, line, strings.Join(prefixes, ", "))
149 }
150 field := fields[key]
151 v := reflect.ValueOf(inProgress).Elem().FieldByName(field.Name)
152 if set[key] && field.Type.Kind() != reflect.Slice {
153 return nil, fmt.Errorf("line %d: field %s may not be repeated", lineNum, strings.ToLower(field.Name))
154 }
155 parser := fieldParsers[key]
156 if err := parser(v, text); err != nil {
157 return nil, fmt.Errorf("line %d: field %q: %v", lineNum, field.Name, err)
158 }
159 set[key] = true
160 }
161
162 if accumulatedCounterText != "" {
163 return nil, fmt.Errorf("reached end of file while processing multiline counter field")
164 }
165
166 flushRecord()
167 return records, nil
168 }
169
170 // A fieldParser parses the provided input and writes to v, which must be
171 // addressable.
172 type fieldParser func(v reflect.Value, input string) error
173
174 var fieldParsers = map[string]fieldParser{
175 "title": parseString,
176 "description": parseString,
177 "issue": parseSlice(parseString),
178 "type": parseString,
179 "program": parseString,
180 "counter": parseString,
181 "depth": parseInt,
182 "error": parseFloat,
183 "version": parseString,
184 }
185
186 func parseString(v reflect.Value, input string) error {
187 v.SetString(input)
188 return nil
189 }
190
191 func parseInt(v reflect.Value, input string) error {
192 i, err := strconv.ParseInt(input, 10, 64)
193 if err != nil {
194 return fmt.Errorf("invalid int value %q", input)
195 }
196 v.SetInt(i)
197 return nil
198 }
199
200 func parseFloat(v reflect.Value, input string) error {
201 f, err := strconv.ParseFloat(input, 64)
202 if err != nil {
203 return fmt.Errorf("invalid float value %q", input)
204 }
205 v.SetFloat(f)
206 return nil
207 }
208
209 func parseSlice(elemParser fieldParser) fieldParser {
210 return func(v reflect.Value, input string) error {
211 elem := reflect.New(v.Type().Elem()).Elem()
212 v.Set(reflect.Append(v, elem))
213 elem = v.Index(v.Len() - 1)
214 if err := elemParser(elem, input); err != nil {
215 return err
216 }
217 return nil
218 }
219 }