Skip to content

Commit

Permalink
Add a method for checking if a node is a blank line.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 598573944
  • Loading branch information
txtpbfmt-copybara-robot committed Jan 15, 2024
1 parent 75d56e8 commit 442737f
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 1 deletion.
9 changes: 8 additions & 1 deletion ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
68 changes: 68 additions & 0 deletions ast/ast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,12 @@ bar: 2
foo: true # bar
}
# trailing comment
`,
want: []bool{false, true},
},
{
in: `foo: 1
`,
want: []bool{false, true},
},
Expand All @@ -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 { }`

Expand Down

0 comments on commit 442737f

Please sign in to comment.