From 416f9418166c00bf75698697d9ac6e542e096ac4 Mon Sep 17 00:00:00 2001 From: zoncoen Date: Tue, 20 Jul 2021 02:13:35 +0900 Subject: [PATCH] Fix decode nodes included anchors --- decode.go | 2 ++ decode_test.go | 26 +++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/decode.go b/decode.go index bf177371..ab85e748 100644 --- a/decode.go +++ b/decode.go @@ -1506,6 +1506,8 @@ func (d *Decoder) DecodeFromNodeContext(ctx context.Context, node ast.Node, v in return errors.Wrapf(err, "failed to decodInit") } } + // resolve references to the anchor on the same file + d.nodeToValue(node) if err := d.decodeValue(ctx, rv.Elem(), node); err != nil { return errors.Wrapf(err, "failed to decode value") } diff --git a/decode_test.go b/decode_test.go index f9702650..46317fd8 100644 --- a/decode_test.go +++ b/decode_test.go @@ -1718,7 +1718,31 @@ func Test_UnmarshalerContext(t *testing.T) { } func TestDecoder_DecodeFromNode(t *testing.T) { - t.Run("with reference", func(t *testing.T) { + t.Run("has reference", func(t *testing.T) { + str := ` +anchor: &map + text: hello +map: *map` + var buf bytes.Buffer + dec := yaml.NewDecoder(&buf) + f, err := parser.ParseBytes([]byte(str), 0) + if err != nil { + t.Fatalf("failed to parse: %s", err) + } + type T struct { + Map map[string]string + } + var v T + if err := dec.DecodeFromNode(f.Docs[0].Body, &v); err != nil { + t.Fatalf("failed to decode: %s", err) + } + actual := fmt.Sprintf("%+v", v) + expect := fmt.Sprintf("%+v", T{map[string]string{"text": "hello"}}) + if actual != expect { + t.Fatalf("actual=[%s], expect=[%s]", actual, expect) + } + }) + t.Run("with reference option", func(t *testing.T) { anchor := strings.NewReader(` map: &map text: hello`)