From f3fc3d06d6fd50484dd93ea0188824ab857b28d8 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Fri, 15 Jul 2016 11:48:40 -0400 Subject: [PATCH] parse: ignore leading whitespace for comments Comments were only ignored if the string parsed started with "#". This commit trims leading whitespace and tab characters to make sure all lines with "#" being the first non-whitespace character are ignored. Signed-off-by: Stephen Chung --- check_test.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++- parse.go | 7 ++++-- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/check_test.go b/check_test.go index bd757ef..eef9b1e 100644 --- a/check_test.go +++ b/check_test.go @@ -108,7 +108,7 @@ func TestTimeComparison(t *testing.T) { // This is the format of time from FreeBSD spec := ` /set type=file time=5.000000000 -. type=dir +. type=dir file time=5.000000000 .. ` @@ -139,3 +139,69 @@ func TestTimeComparison(t *testing.T) { t.Fatal(res.Failures) } } + +func TestIgnoreComments(t *testing.T) { + dir, err := ioutil.TempDir("", "test-comments.") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dir) + + // This is the format of time from FreeBSD + spec := ` +/set type=file time=5.000000000 +. type=dir + file1 time=5.000000000 +.. +` + + fh, err := os.Create(filepath.Join(dir, "file1")) + if err != nil { + t.Fatal(err) + } + // This is what mode we're checking for. Round integer of epoch seconds + epoch := time.Unix(5, 0) + if err := os.Chtimes(fh.Name(), epoch, epoch); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(dir, epoch, epoch); err != nil { + t.Fatal(err) + } + if err := fh.Close(); err != nil { + t.Error(err) + } + + dh, err := ParseSpec(bytes.NewBufferString(spec)) + if err != nil { + t.Fatal(err) + } + + res, err := Check(dir, dh, nil) + if err != nil { + t.Error(err) + } + + if len(res.Failures) > 0 { + t.Fatal(res.Failures) + } + + // now change the spec to a comment that looks like an actual Entry but has + // whitespace in front of it + spec = ` +/set type=file time=5.000000000 +. type=dir + file1 time=5.000000000 + #file2 time=5.000000000 +.. +` + dh, err = ParseSpec(bytes.NewBufferString(spec)) + + res, err = Check(dir, dh, nil) + if err != nil { + t.Error(err) + } + + if len(res.Failures) > 0 { + t.Fatal(res.Failures) + } +} diff --git a/parse.go b/parse.go index 826e174..5155f74 100644 --- a/parse.go +++ b/parse.go @@ -16,11 +16,14 @@ func ParseSpec(r io.Reader) (*DirectoryHierarchy, error) { } for s.Scan() { str := s.Text() + trimmedStr := strings.TrimLeftFunc(str, func(c rune) bool { + return c == ' ' || c == '\t' + }) e := Entry{Pos: i} switch { - case strings.HasPrefix(str, "#"): + case strings.HasPrefix(trimmedStr, "#"): e.Raw = str - if strings.HasPrefix(str, "#mtree") { + if strings.HasPrefix(trimmedStr, "#mtree") { e.Type = SignatureType } else { e.Type = CommentType