Skip to content

Commit

Permalink
fields.go - Add YAML path to all fields (#9)
Browse files Browse the repository at this point in the history
Include the YAML path (e.g. `$[1].fields[2]`) to the field definition
in fleetpkg.Field.
  • Loading branch information
andrewkroh authored Oct 3, 2023
1 parent 848c67f commit 834a8fa
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
14 changes: 14 additions & 0 deletions fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ type Field struct {
AdditionalAttributes map[string]any `json:"_additional_attributes,omitempty" yaml:",inline"`

FileMetadata `json:"-" yaml:"-"`

YAMLPath string `json:"-" yaml:"-"` // YAML path
}

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

for i := range fields {
annotateYAMLPath(fmt.Sprintf("$[%d]", i), &fields[i])
}
annotateFileMetadata(path, &fields)

return fields, err
}

// annotateYAMLPath sets the YAML path of each field.
func annotateYAMLPath(yamlPath string, field *Field) {
field.YAMLPath = yamlPath
for i := range field.Fields {
annotateYAMLPath(fmt.Sprintf("%s.fields[%d]", yamlPath, i), &field.Fields[i])
}
}

// FlattenFields returns a flat representation of the fields. It
// removes all nested fields and creates top-level fields whose
// name is constructed by joining the parts with dots. The returned
Expand Down
5 changes: 5 additions & 0 deletions fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package fleetpkg

import (
"fmt"
"testing"
)

Expand Down Expand Up @@ -78,5 +79,9 @@ func TestReadFields(t *testing.T) {
if f.Column() == 0 {
t.Errorf("sourceColumn is empty")
}
fmt.Printf("%s:%d:%d %s - %s\n", f.Path(), f.Line(), f.Column(), f.Name, f.YAMLPath)
if f.YAMLPath == "" {
t.Errorf("YAMLPath is empty")
}
}
}

0 comments on commit 834a8fa

Please sign in to comment.