Skip to content

fields.go - Add YAML path to all fields #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}
}
}