summaryrefslogtreecommitdiff
path: root/internal/fix/fix.go
blob: a1c1c2d989dfccb88b412935d87443621969f9a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package fix

import (
	"errors"
	"fmt"
	"io"
	"regexp"
	"strings"

	lru "github.com/hashicorp/golang-lru"
)

var errNotRE = errors.New("not re")

type Fix struct {
	cache *lru.Cache
	w     io.Writer
}

func (f Fix) get(nick string) (string, bool) {
	if text, ok := f.cache.Get(nick); ok {
		return text.(string), true
	}
	return "", false
}

func (f Fix) set(nick, text string) {
	f.cache.Add(nick, text)
}

func New(w io.Writer) *Fix {
	cache, _ := lru.New(100)
	return &Fix{cache: cache, w: w}
}

func (f Fix) Fix(text, nick string) {
	defer f.set(nick, text)
	if !strings.HasPrefix(text, "s") {
		return
	}
	if tofix, ok := f.get(nick); ok {
		global := strings.HasSuffix(text, "g")
		fixed, err := replace(tofix, 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
}