Skip to content

Commit

Permalink
Merge 1271fbd into 1a871c1
Browse files Browse the repository at this point in the history
  • Loading branch information
belak committed Dec 28, 2016
2 parents 1a871c1 + 1271fbd commit 3a9a9be
Show file tree
Hide file tree
Showing 2 changed files with 113 additions and 0 deletions.
50 changes: 50 additions & 0 deletions utils.go
@@ -0,0 +1,50 @@
package irc

import (
"bytes"
"regexp"
)

var maskTranslations = map[byte]string{
'?': ".",
'*': ".*",
}

// MaskToRegex converts an irc mask to a go Regexp for more convenient
// use. This should never return an error, but we have this here just
// in case.
func MaskToRegex(rawMask string) (*regexp.Regexp, error) {
input := bytes.NewBufferString(rawMask)

output := &bytes.Buffer{}
output.WriteByte('^')

for {
c, err := input.ReadByte()
if err != nil {
break
}

if c == '\\' {
c, err = input.ReadByte()
if err != nil {
output.WriteString(regexp.QuoteMeta("\\"))
break
}

if c == '?' || c == '*' || c == '\\' {
output.WriteString(regexp.QuoteMeta(string(c)))
} else {
output.WriteString(regexp.QuoteMeta("\\" + string(c)))
}
} else if trans, ok := maskTranslations[c]; ok {
output.WriteString(trans)
} else {
output.WriteString(regexp.QuoteMeta(string(c)))
}
}

output.WriteByte('$')

return regexp.Compile(output.String())
}
63 changes: 63 additions & 0 deletions utils_test.go
@@ -0,0 +1,63 @@
package irc

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestMaskToRegex(t *testing.T) {
t.Parallel()

var testCases = []struct {
Input string
Expect string
}{
{ // Empty should be fine
Input: "",
Expect: "^$",
},
{ // EVERYONE!
Input: "*!*@*",
Expect: "^.*!.*@.*$",
},
{
Input: "",
Expect: "^$",
},
{
Input: "",
Expect: "^$",
},
{ // Escape the slash
Input: "a\\\\b",
Expect: "^a\\\\b$",
},
{ // Escape a *
Input: "a\\*b",
Expect: "^a\\*b$",
},
{ // Escape a ?
Input: "a\\?b",
Expect: "^a\\?b$",
},
{ // Single slash in the middle of a string should be a slash
Input: "a\\b",
Expect: "^a\\\\b$",
},
{ // Single slash should just match a single slash
Input: "\\",
Expect: "^\\\\$",
},
{
Input: "\\a?",
Expect: "^\\\\a.$",
},
}

for _, testCase := range testCases {
ret, err := MaskToRegex(testCase.Input)
assert.NoError(t, err)
assert.Equal(t, testCase.Expect, ret.String())
}
}

0 comments on commit 3a9a9be

Please sign in to comment.