summaryrefslogtreecommitdiff
path: root/internal/fix/fix.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/fix/fix.go')
-rw-r--r--internal/fix/fix.go64
1 files changed, 64 insertions, 0 deletions
diff --git a/internal/fix/fix.go b/internal/fix/fix.go
new file mode 100644
index 0000000..2a83a28
--- /dev/null
+++ b/internal/fix/fix.go
@@ -0,0 +1,64 @@
+package fix
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "regexp"
+ "strings"
+
+ lru "github.com/hashicorp/golang-lru"
+)
+
+var errNotRE = errors.New("not re")
+
+type Fix struct {
+ last *lru.Cache
+ w io.Writer
+}
+
+func New(w io.Writer) *Fix {
+ last, _ := lru.New(100)
+ return &Fix{last: last, w: w}
+}
+
+func (f *Fix) Fix(text, nick string) {
+ defer f.last.Add(nick, text)
+ if !strings.HasPrefix(text, "s") {
+ return
+ }
+ if tofix, ok := f.last.Get(nick); ok {
+ global := strings.HasSuffix(text, "g")
+ fixed, err := replace(tofix.(string), text[1:], global)
+ if err == nil && fixed != tofix {
+ fmt.Fprintf(f.w, "%v meant to say: %s", nick, fixed)
+ }
+ }
+}
+
+func replace(s, r string, global bool) (string, error) {
+ // min: at least two separators
+ if len(r) < 2 {
+ return "", errNotRE
+ }
+ z := strings.Split(r[1:], string(r[0]))
+ // match // and ///
+ if len(z) < 2 || len(z) > 3 {
+ return "", errNotRE
+ }
+ re, err := regexp.Compile(z[0])
+ if err != nil {
+ return "", err
+ }
+ i := 1
+ if global {
+ i = -1
+ }
+ return re.ReplaceAllStringFunc(s, func(b string) string {
+ if i != 0 {
+ i--
+ return z[1]
+ }
+ return b
+ }), nil
+}