Skip to content

Commit 834a8fa

Browse files
authored
fields.go - Add YAML path to all fields (#9)
Include the YAML path (e.g. `$[1].fields[2]`) to the field definition in fleetpkg.Field.
1 parent 848c67f commit 834a8fa

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

fields.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ type Field struct {
6565
AdditionalAttributes map[string]any `json:"_additional_attributes,omitempty" yaml:",inline"`
6666

6767
FileMetadata `json:"-" yaml:"-"`
68+
69+
YAMLPath string `json:"-" yaml:"-"` // YAML path
6870
}
6971

7072
func (f *Field) UnmarshalYAML(value *yaml.Node) error {
@@ -117,10 +119,22 @@ func readFields(path string) ([]Field, error) {
117119
return nil, fmt.Errorf("failed reading from %q: %w", path, err)
118120
}
119121

122+
for i := range fields {
123+
annotateYAMLPath(fmt.Sprintf("$[%d]", i), &fields[i])
124+
}
120125
annotateFileMetadata(path, &fields)
126+
121127
return fields, err
122128
}
123129

130+
// annotateYAMLPath sets the YAML path of each field.
131+
func annotateYAMLPath(yamlPath string, field *Field) {
132+
field.YAMLPath = yamlPath
133+
for i := range field.Fields {
134+
annotateYAMLPath(fmt.Sprintf("%s.fields[%d]", yamlPath, i), &field.Fields[i])
135+
}
136+
}
137+
124138
// FlattenFields returns a flat representation of the fields. It
125139
// removes all nested fields and creates top-level fields whose
126140
// name is constructed by joining the parts with dots. The returned

fields_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
package fleetpkg
1919

2020
import (
21+
"fmt"
2122
"testing"
2223
)
2324

@@ -78,5 +79,9 @@ func TestReadFields(t *testing.T) {
7879
if f.Column() == 0 {
7980
t.Errorf("sourceColumn is empty")
8081
}
82+
fmt.Printf("%s:%d:%d %s - %s\n", f.Path(), f.Line(), f.Column(), f.Name, f.YAMLPath)
83+
if f.YAMLPath == "" {
84+
t.Errorf("YAMLPath is empty")
85+
}
8186
}
8287
}

0 commit comments

Comments
 (0)