From 5174ed35ca6b6fe9aedde49ac06fe5584795d7e7 Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Thu, 26 Aug 2021 01:37:02 +0100 Subject: [PATCH] feat(parser): add Comment method to check if a line is a comment --- line.go | 18 ++++++++-- line_test.go | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 2 deletions(-) diff --git a/line.go b/line.go index 4bfbd39..e642da5 100644 --- a/line.go +++ b/line.go @@ -6,8 +6,10 @@ import ( ) const ( - lf = 10 // linefeed ("\n") character - cr = 13 // carriage return ("\r") character + lf = 10 // ASCII linefeed ("\n") character. + cr = 13 // ASCII carriage return ("\r") character. + hash = 35 // ASCII hash ("#") character. + ) // Line represents a single line of text defined as; A continuous sequence of @@ -36,6 +38,18 @@ func (s *Line) Blank() bool { return len(bytes.TrimSpace(s.Content)) == 0 } +// Comment returns true if line content is a commit comment, where the first +// non-whitespace character in the line is a hash (#). +func (s *Line) Comment() bool { + trimmed := bytes.TrimSpace(s.Content) + + if len(trimmed) == 0 { + return false + } + + return trimmed[0] == hash +} + // Lines is a slice of *Line types with some helper methods attached. type Lines []*Line diff --git a/line_test.go b/line_test.go index 5ea956f..da5344f 100644 --- a/line_test.go +++ b/line_test.go @@ -156,6 +156,99 @@ func TestLine_Blank(t *testing.T) { } } +func TestLine_Comment(t *testing.T) { + tests := []struct { + name string + line *Line + want bool + }{ + { + name: "nil", + line: &Line{}, + want: false, + }, + { + name: "empty", + line: &Line{ + Number: 1, + Content: []byte(""), + Break: []byte{}, + }, + want: false, + }, + { + name: "space only", + line: &Line{ + Number: 1, + Content: []byte(" "), + Break: []byte{}, + }, + want: false, + }, + { + name: "tab only", + line: &Line{ + Number: 1, + Content: []byte("\t\t"), + Break: []byte{}, + }, + want: false, + }, + { + name: "spaces and tabs", + line: &Line{ + Number: 1, + Content: []byte(" \t "), + Break: []byte{}, + }, + want: false, + }, + { + name: "text", + line: &Line{ + Number: 1, + Content: []byte("foobar"), + Break: []byte{}, + }, + want: false, + }, + { + name: "beings with hash", + line: &Line{ + Number: 1, + Content: []byte("# foo bar"), + Break: []byte{}, + }, + want: true, + }, + { + name: "beings with hash after whitespace", + line: &Line{ + Number: 1, + Content: []byte(" \t # foo bar"), + Break: []byte{}, + }, + want: true, + }, + { + name: "has hash in middle of text", + line: &Line{ + Number: 1, + Content: []byte(" foo # bar"), + Break: []byte{}, + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.line.Comment() + + assert.Equal(t, tt.want, got) + }) + } +} + func TestNewLines(t *testing.T) { tests := []struct { name string