Skip to content
This repository has been archived by the owner on Jun 26, 2023. It is now read-only.

Commit

Permalink
Merge pull request #23 from dragon3/use-bufio-reader
Browse files Browse the repository at this point in the history
  • Loading branch information
b4b4r07 authored Jun 15, 2020
2 parents 59f1177 + 7451570 commit c580daf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
18 changes: 13 additions & 5 deletions lint/internal/policy/funcs/unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package funcs
import (
"bufio"
"fmt"
"io"
"regexp"
"strings"

Expand All @@ -27,15 +28,22 @@ var GrepFunc = function.New(&function.Spec{
pattern := args[0].AsString()
text := args[1].AsString()
var matches []string
in := strings.NewReader(text)
scanner := bufio.NewScanner(in)
for scanner.Scan() {
matched, err := regexp.MatchString(pattern, scanner.Text())

r := bufio.NewReader(strings.NewReader(text))
for {
l, err := r.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return cty.NilVal, err
}
l = strings.TrimRight(l, "\n")
matched, err := regexp.MatchString(pattern, l)
if err != nil {
return cty.NilVal, err
}
if matched {
matches = append(matches, scanner.Text())
matches = append(matches, l)
}
}
return cty.StringVal(strings.Join(matches, "\n")), nil
Expand Down
16 changes: 16 additions & 0 deletions lint/internal/policy/funcs/unix_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
package funcs

import (
"bufio"
"math/rand"
"testing"

"github.com/zclconf/go-cty/cty"
)

func RandomString(n int) string {
var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letter[rand.Intn(len(letter))]
}
return string(b)
}

func TestGrep(t *testing.T) {
tests := map[string]struct {
Pattern cty.Value
Expand All @@ -22,6 +33,11 @@ func TestGrep(t *testing.T) {
cty.StringVal("test\nhogehoge\nfoo\nbar\n"),
cty.StringVal(""),
},
"MatchLongString": {
cty.StringVal("hoge"),
cty.StringVal(RandomString(bufio.MaxScanTokenSize) + "\nhogehoge\nfoo\nbar\nhogebaz\n" + RandomString(bufio.MaxScanTokenSize+1)),
cty.StringVal("hogehoge\nhogebaz"),
},
}

for name, test := range tests {
Expand Down

0 comments on commit c580daf

Please sign in to comment.