From 442737fd7ced9dbbcb15b9d1804b24fd3d0d7d4a Mon Sep 17 00:00:00 2001 From: txtpbfmt team Date: Mon, 15 Jan 2024 04:13:37 -0800 Subject: [PATCH] Add a method for checking if a node is a blank line. PiperOrigin-RevId: 598573944 --- ast/ast.go | 9 ++++++- ast/ast_test.go | 68 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/ast/ast.go b/ast/ast.go index 489e9b7..1759624 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -207,11 +207,18 @@ func (n *Node) getChildValue(field string) *Value { return nil } -// IsCommentOnly returns true if this is a comment-only node. +// IsCommentOnly returns true if this is a comment-only node. Even a node that +// only contains a blank line is considered a comment-only node in the sense +// that it has no proto content. func (n *Node) IsCommentOnly() bool { return n.Name == "" && n.Children == nil } +// IsBlankLine returns true if this is a blank line node. +func (n *Node) IsBlankLine() bool { + return n.IsCommentOnly() && len(n.PreComments) == 1 && n.PreComments[0] == "" +} + type fixData struct { inline bool } diff --git a/ast/ast_test.go b/ast/ast_test.go index b3eb171..dd2babf 100644 --- a/ast/ast_test.go +++ b/ast/ast_test.go @@ -185,6 +185,12 @@ bar: 2 foo: true # bar } # trailing comment +`, + want: []bool{false, true}, + }, + { + in: `foo: 1 + `, want: []bool{false, true}, }, @@ -210,6 +216,68 @@ bar: 2 } } +func TestIsBlankLine(t *testing.T) { + inputs := []struct { + in string + want []bool + }{{ + in: `foo: 1 +bar: 2`, + want: []bool{false, false}, + }, + { + in: `foo: 1 +bar: 2 +`, + want: []bool{false, false}, + }, + { + in: `foo: 1 +bar: 2 +# A trailing comment. +`, + want: []bool{false, false, false}, + }, + { + in: `first { + foo: true # bar +} +# trailing comment +`, + want: []bool{false, false}, + }, + { + in: `foo: 1 + +`, + want: []bool{false, true}, + }, + { + in: `# Header comment. + +foo: 1 +`, + // The blank line is part of the node of the `foo: 1` item. + want: []bool{false, false}, + }, + } + for _, input := range inputs { + nodes, err := parser.Parse([]byte(input.in)) + if err != nil { + t.Errorf("Parse %v returned err %v", input.in, err) + continue + } + if len(nodes) != len(input.want) { + t.Errorf("For %v, expect %v nodes, got %v", input.in, len(input.want), len(nodes)) + } + for i, n := range nodes { + if got := n.IsBlankLine(); got != input.want[i] { + t.Errorf("For %v, nodes[%v].IsBlankLine() = %v, want %v", input.in, i, got, input.want[i]) + } + } + } +} + func TestFixInline(t *testing.T) { content := `first { }`