diff options
author | Dimitri Sokolyuk <demon@dim13.org> | 2018-01-01 16:47:42 +0100 |
---|---|---|
committer | Dimitri Sokolyuk <demon@dim13.org> | 2018-01-01 16:47:42 +0100 |
commit | b805a548e3ead263010cbf03717aa9ac52ab301d (patch) | |
tree | 76bee1feb9fb3d40ae7f65c2811752285bb28b32 | |
parent | 92c01374aa44e5800ce19a294170ad317489b439 (diff) |
readd regexp fixer
-rw-r--r-- | main.go | 12 | ||||
-rw-r--r-- | re.go | 33 | ||||
-rw-r--r-- | re_test.go | 29 |
3 files changed, 74 insertions, 0 deletions
@@ -4,6 +4,7 @@ import ( "flag" "fmt" "log" + "strings" irc "github.com/fluffle/goirc/client" ) @@ -29,6 +30,7 @@ func (n *Notify) Write(p []byte) (int, error) { } func privmsg(room string) irc.HandlerFunc { + last := make(map[string]string) return func(conn *irc.Conn, line *irc.Line) { switch t := line.Text(); { case isFlood(t): @@ -36,6 +38,15 @@ func privmsg(room string) irc.HandlerFunc { log.Println("kick", line.Nick) conn.Kick(room, line.Nick) } + case strings.HasPrefix(t, "s"): + global := strings.HasSuffix(t, "g") + if tofix, ok := last[line.Nick]; ok { + fixed := re(tofix, t[1:], global) + if fixed != "" && fixed != tofix { + fmt.Fprintf(NewNotify(conn, line.Target()), "%v meant to say: %q", line.Nick, fixed) + last[line.Nick] = fixed + } + } default: for _, v := range getLinks(t) { title, err := getTitle(v) @@ -46,6 +57,7 @@ func privmsg(room string) irc.HandlerFunc { fmt.Fprintf(NewNotify(conn, line.Target()), "Title: %v", title) } } + last[line.Nick] = t } } } @@ -0,0 +1,33 @@ +package main + +import ( + "regexp" + "strings" +) + +func re(s, r string, global bool) string { + // min: at least two separators + if len(s) < 2 { + return "" + } + z := strings.Split(r[1:], string(r[0])) + // match // and /// + if len(z) < 2 || len(z) > 3 { + return "" + } + re, err := regexp.Compile(z[0]) + if err != nil { + return "" + } + i := 1 + if global { + i = -1 + } + return re.ReplaceAllStringFunc(s, func(b string) string { + if i != 0 { + i -= 1 + return z[1] + } + return b + }) +} diff --git a/re_test.go b/re_test.go new file mode 100644 index 0000000..6b6d94d --- /dev/null +++ b/re_test.go @@ -0,0 +1,29 @@ +package main + +import "testing" + +func TestRE(t *testing.T) { + testCases := []struct { + r, s, x string + global bool + }{ + {"/ddd/xxx/", "abd ddd xxx", "abd xxx xxx", false}, + {",ddd,xxx,", "abd ddd xxx", "abd xxx xxx", false}, + {"/ddd/xxx", "abd ddd xxx", "abd xxx xxx", false}, + {"/x$/X", "abd ddd xxx", "abd ddd xxX", false}, + {"/ /A", "abd ddd xxx", "abdAddd xxx", false}, + {"/ /A", "abd ddd xxx", "abdAdddAxxx", true}, + {"///", "abd ddd xxx", "abd ddd xxx", false}, + {"//", "abd ddd xxx", "abd ddd xxx", false}, + {"/", "abd ddd xxx", "", false}, + {"/^d/X", "abd ddd xxx", "abd ddd xxx", false}, + } + for _, tc := range testCases { + t.Run(tc.r, func(t *testing.T) { + res := re(tc.s, tc.r, tc.global) + if res != tc.x { + t.Errorf("got %q, want %q", res, tc.x) + } + }) + } +} |