From 1d409c964a0a00334fb74fde1aa794fd3d0a1785 Mon Sep 17 00:00:00 2001 From: "stuart.warren" Date: Thu, 10 Oct 2019 16:05:29 +0100 Subject: [PATCH 1/2] test: adds extra doc separator FIXME --- format_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/format_test.go b/format_test.go index e9fe2f2..f32ea31 100644 --- a/format_test.go +++ b/format_test.go @@ -60,3 +60,50 @@ bar: t.Logf("got:\n%v\n", out) t.Logf("expected:\n%v\n", exp) } + +func TestYamlMultiSort(t *testing.T) { + var in = `--- +k: + c: l + i: + i: k + v: + # comment + c: i +--- +k: + c: l + i: + i: k + v: + # comment + c: i +` + var expected = `--- +k: + c: l + i: + i: k + v: + # comment + c: i +--- +k: + c: l + i: + i: k + v: + # comment + c: i +` + exp := []byte(expected) + out, err := yamlfmt.Format(bytes.NewBuffer([]byte(in))) + if err != nil { + t.Fatalf("Unexpected error: %s\n", err) + } + if !bytes.Equal(out, exp) { + t.Fatalf("Got:\n%s\nexpected:\n%s\n", out, exp) + } + t.Logf("got:\n%v\n", out) + t.Logf("expected:\n%v\n", exp) +} From 261e9fabd3fa46eca7f39e6890f4fcf3227211b9 Mon Sep 17 00:00:00 2001 From: Stuart Warren Date: Thu, 10 Oct 2019 21:31:01 +0100 Subject: [PATCH 2/2] fix: resolve issue with extra doc separators fixes #11 --- format.go | 7 ++++--- format_test.go | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/format.go b/format.go index 2d9fa0b..646e3d8 100644 --- a/format.go +++ b/format.go @@ -17,10 +17,10 @@ const indent = 2 func Format(r io.Reader) ([]byte, error) { dec := yaml.NewDecoder(r) out := bytes.NewBuffer(nil) - enc := yaml.NewEncoder(out) - enc.SetIndent(indent) - defer enc.Close() for { + enc := yaml.NewEncoder(out) + enc.SetIndent(indent) + defer enc.Close() var doc yaml.Node err := dec.Decode(&doc) if err == io.EOF { @@ -33,6 +33,7 @@ func Format(r io.Reader) ([]byte, error) { if err := enc.Encode(sortYAML(&doc)); err != nil { return nil, fmt.Errorf("failed encoding: %s", err) } + enc.Close() } return out.Bytes(), nil } diff --git a/format_test.go b/format_test.go index f32ea31..f39af21 100644 --- a/format_test.go +++ b/format_test.go @@ -27,7 +27,7 @@ k: c: i ` exp := []byte(expected) - out, err := yamlfmt.Format(bytes.NewBuffer([]byte(in))) + out, err := yamlfmt.Format(bytes.NewReader([]byte(in))) if err != nil { t.Fatalf("Unexpected error: %s\n", err) } @@ -50,7 +50,7 @@ bar: foo: baz # comment ` exp := []byte(expected) - out, err := yamlfmt.Format(bytes.NewBuffer([]byte(in))) + out, err := yamlfmt.Format(bytes.NewReader([]byte(in))) if err != nil { t.Fatalf("Unexpected error: %s\n", err) } @@ -86,7 +86,7 @@ k: i: k v: # comment - c: i + c: i --- k: c: l @@ -97,7 +97,7 @@ k: c: i ` exp := []byte(expected) - out, err := yamlfmt.Format(bytes.NewBuffer([]byte(in))) + out, err := yamlfmt.Format(bytes.NewReader([]byte(in))) if err != nil { t.Fatalf("Unexpected error: %s\n", err) }