3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-23 04:19:25 +01:00
ergo/irc/utils/glob.go
2020-05-05 17:20:55 -04:00

32 lines
644 B
Go

// Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
// released under the MIT license
package utils
import (
"bytes"
"regexp"
"regexp/syntax"
)
// yet another glob implementation in Go
func CompileGlob(glob string) (result *regexp.Regexp, err error) {
var buf bytes.Buffer
buf.WriteByte('^')
for _, r := range glob {
switch r {
case '*':
buf.WriteString("(.*)")
case '?':
buf.WriteString("(.)")
case 0xFFFD:
return nil, &syntax.Error{Code: syntax.ErrInvalidUTF8, Expr: glob}
default:
buf.WriteString(regexp.QuoteMeta(string(r)))
}
}
buf.WriteByte('$')
return regexp.Compile(buf.String())
}