2020-05-05 04:29:10 +02:00
|
|
|
// Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
|
|
|
|
// released under the MIT license
|
|
|
|
|
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"regexp"
|
2020-05-05 23:20:50 +02:00
|
|
|
"regexp/syntax"
|
2020-05-05 04:29:10 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// yet another glob implementation in Go
|
|
|
|
|
|
|
|
func CompileGlob(glob string) (result *regexp.Regexp, err error) {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
buf.WriteByte('^')
|
2020-05-05 23:20:50 +02:00
|
|
|
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)))
|
2020-05-05 04:29:10 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
buf.WriteByte('$')
|
|
|
|
return regexp.Compile(buf.String())
|
|
|
|
}
|