From 834a8fa1cc54d083ab63ebb6ef3dfddf21e51c32 Mon Sep 17 00:00:00 2001 From: Andrew Kroh Date: Tue, 3 Oct 2023 01:34:37 -0400 Subject: [PATCH] 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. --- fields.go | 14 ++++++++++++++ fields_test.go | 5 +++++ 2 files changed, 19 insertions(+) diff --git a/fields.go b/fields.go index 63f8ad3..a981f50 100644 --- a/fields.go +++ b/fields.go @@ -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 { @@ -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 diff --git a/fields_test.go b/fields_test.go index 38429eb..571af0a 100644 --- a/fields_test.go +++ b/fields_test.go @@ -18,6 +18,7 @@ package fleetpkg import ( + "fmt" "testing" ) @@ -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") + } } }