clean up of the codebase
This commit is contained in:
1 parent
7822529a38
commit
0ac61b4ece
52 files changed
+2545
-2274
No files matched your search
@@ -0,0 +1,262 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"slackerbot/internal/model"
|
||||
"slackerbot/internal/units"
|
||||
)
|
||||
|
||||
var ErrNotCommand = errors.New("not a command")
|
||||
|
||||
var unitSpace = regexp.MustCompile(`(\d)\s+(tib|tb|t|gib|gb|g|mib|mb|m|cpus|cpu|cores|core)\b`)
|
||||
var sizeToken = regexp.MustCompile(`^([+-]?)(\d+(?:\.\d+)?)(g|gb|gib|m|mb|mib|cpu|cpus|core|cores)$`)
|
||||
|
||||
func ParseScale(args string, cur model.Size) (model.Size, error) {
|
||||
args = unitSpace.ReplaceAllString(strings.ToLower(args), "$1$2")
|
||||
words := strings.Fields(args)
|
||||
if len(words) == 0 {
|
||||
return model.Size{MemoryMB: cur.MemoryMB * 2, CPUs: cur.CPUs * 2}, nil
|
||||
}
|
||||
if len(words) == 1 {
|
||||
switch words[0] {
|
||||
case "up", "out":
|
||||
return model.Size{MemoryMB: cur.MemoryMB * 2, CPUs: cur.CPUs * 2}, nil
|
||||
case "down", "in":
|
||||
return model.Size{MemoryMB: cur.MemoryMB / 2, CPUs: cur.CPUs / 2}, nil
|
||||
}
|
||||
}
|
||||
|
||||
next := cur
|
||||
var memDone, cpuDone bool
|
||||
for i, w := range words {
|
||||
parts := sizeToken.FindStringSubmatch(w)
|
||||
if parts == nil {
|
||||
if i == 0 {
|
||||
return cur, ErrNotCommand
|
||||
}
|
||||
return cur, fmt.Errorf("I didn't understand `%s`", w)
|
||||
}
|
||||
sign, num, unit := parts[1], parts[2], parts[3]
|
||||
n, _ := strconv.ParseFloat(num, 64)
|
||||
|
||||
if unit == "cpu" || unit == "cpus" || unit == "core" || unit == "cores" {
|
||||
if cpuDone {
|
||||
return cur, errors.New("CPU was given twice")
|
||||
}
|
||||
cpuDone = true
|
||||
next.CPUs = apply(sign, cur.CPUs, n)
|
||||
continue
|
||||
}
|
||||
if memDone {
|
||||
return cur, errors.New("memory was given twice")
|
||||
}
|
||||
memDone = true
|
||||
mb := n
|
||||
if strings.HasPrefix(unit, "g") {
|
||||
mb = n * 1024
|
||||
}
|
||||
next.MemoryMB = int(math.Round(apply(sign, float64(cur.MemoryMB), mb)))
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func apply(sign string, cur, n float64) float64 {
|
||||
switch sign {
|
||||
case "+":
|
||||
return cur + n
|
||||
case "-":
|
||||
return cur - n
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
type KeepSetting struct {
|
||||
Show bool
|
||||
Reset bool
|
||||
Indefinite bool
|
||||
Limit time.Duration
|
||||
}
|
||||
|
||||
var dayToken = regexp.MustCompile(`(\d+(?:\.\d+)?)([dw])`)
|
||||
|
||||
var wordUnit = regexp.MustCompile(`(\d+(?:\.\d+)?)\s*(weeks?|wks?|days?|hours?|hrs?|minutes?|mins?)\b`)
|
||||
|
||||
func ParseKeep(args string) (KeepSetting, error) {
|
||||
a := strings.ToLower(strings.TrimSpace(args))
|
||||
switch a {
|
||||
case "":
|
||||
return KeepSetting{Show: true}, nil
|
||||
case "default", "reset", "normal":
|
||||
return KeepSetting{Reset: true}, nil
|
||||
case "indefinite", "indefinitely", "forever", "alive", "running", "on":
|
||||
return KeepSetting{Indefinite: true}, nil
|
||||
}
|
||||
d, err := parseDuration(a)
|
||||
if err != nil {
|
||||
return KeepSetting{}, ErrNotCommand
|
||||
}
|
||||
if d <= 0 {
|
||||
return KeepSetting{}, errors.New("the time has to be more than zero")
|
||||
}
|
||||
return KeepSetting{Limit: d}, nil
|
||||
}
|
||||
|
||||
func parseDuration(s string) (time.Duration, error) {
|
||||
s = wordUnit.ReplaceAllStringFunc(s, func(m string) string {
|
||||
p := wordUnit.FindStringSubmatch(m)
|
||||
return p[1] + map[byte]string{'w': "w", 'd': "d", 'h': "h", 'm': "m"}[p[2][0]]
|
||||
})
|
||||
s = strings.ReplaceAll(s, " ", "")
|
||||
s = dayToken.ReplaceAllStringFunc(s, func(m string) string {
|
||||
p := dayToken.FindStringSubmatch(m)
|
||||
n, _ := strconv.ParseFloat(p[1], 64)
|
||||
hours := n * 24
|
||||
if p[2] == "w" {
|
||||
hours = n * 24 * 7
|
||||
}
|
||||
return strconv.FormatFloat(hours, 'f', -1, 64) + "h"
|
||||
})
|
||||
return time.ParseDuration(s)
|
||||
}
|
||||
|
||||
func Human(d time.Duration) string {
|
||||
d = d.Round(time.Minute)
|
||||
days := d / (24 * time.Hour)
|
||||
d -= days * 24 * time.Hour
|
||||
out := ""
|
||||
if days > 0 {
|
||||
out = fmt.Sprintf("%dd", days)
|
||||
}
|
||||
if d > 0 {
|
||||
r := strings.TrimSuffix(d.String(), "0s")
|
||||
if strings.HasSuffix(r, "h0m") {
|
||||
r = strings.TrimSuffix(r, "0m")
|
||||
}
|
||||
out += r
|
||||
}
|
||||
if out == "" {
|
||||
out = "0m"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ParseStorage(args string, curMin, curMax int64) (min, max int64, err error) {
|
||||
args = unitSpace.ReplaceAllString(strings.ToLower(args), "$1$2")
|
||||
words := strings.Fields(args)
|
||||
min, max = curMin, curMax
|
||||
var minDone, maxDone bool
|
||||
|
||||
for i := 0; i < len(words); i++ {
|
||||
target := "max"
|
||||
switch words[i] {
|
||||
case "min", "guarantee", "guaranteed", "reserve":
|
||||
target = "min"
|
||||
i++
|
||||
case "max", "cap", "limit":
|
||||
i++
|
||||
}
|
||||
if i >= len(words) {
|
||||
return curMin, curMax, fmt.Errorf("%s needs a size after it, like `%s 10G`", target, target)
|
||||
}
|
||||
p := units.StorageToken.FindStringSubmatch(words[i])
|
||||
if p == nil {
|
||||
if i == 0 {
|
||||
return curMin, curMax, ErrNotCommand
|
||||
}
|
||||
return curMin, curMax, fmt.Errorf("I didn't understand `%s`", words[i])
|
||||
}
|
||||
n := units.ToMB(p[2], p[3])
|
||||
if target == "min" {
|
||||
if minDone {
|
||||
return curMin, curMax, errors.New("min was given twice")
|
||||
}
|
||||
minDone = true
|
||||
min = int64(apply(p[1], float64(curMin), float64(n)))
|
||||
} else {
|
||||
if maxDone {
|
||||
return curMin, curMax, errors.New("max was given twice")
|
||||
}
|
||||
maxDone = true
|
||||
max = int64(apply(p[1], float64(curMax), float64(n)))
|
||||
}
|
||||
}
|
||||
return min, max, nil
|
||||
}
|
||||
|
||||
var mentionRe = regexp.MustCompile(`^<@([UW][A-Z0-9]+)(?:\|[^>]*)?>[,.]?$`)
|
||||
|
||||
type GrantCmd struct {
|
||||
ToDefault bool
|
||||
Users []string
|
||||
Actions []model.Action
|
||||
}
|
||||
|
||||
func ParseGrant(args string) (GrantCmd, error) {
|
||||
var g GrantCmd
|
||||
words := strings.Fields(args)
|
||||
i := 0
|
||||
if len(words) > 0 && strings.ToLower(words[0]) == "default" {
|
||||
g.ToDefault, i = true, 1
|
||||
}
|
||||
for ; i < len(words); i++ {
|
||||
if m := mentionRe.FindStringSubmatch(words[i]); m != nil {
|
||||
g.Users = append(g.Users, m[1])
|
||||
continue
|
||||
}
|
||||
w := strings.ToLower(strings.Trim(words[i], ",."))
|
||||
if w == "all" || slices.Contains(model.GrantActions, model.Action(w)) {
|
||||
g.Actions = append(g.Actions, model.Action(w))
|
||||
continue
|
||||
}
|
||||
if len(g.Users) == 0 && !g.ToDefault {
|
||||
return g, ErrNotCommand
|
||||
}
|
||||
return g, fmt.Errorf("I didn't understand `%s`", words[i])
|
||||
}
|
||||
switch {
|
||||
case len(g.Users) == 0 && !g.ToDefault:
|
||||
return g, ErrNotCommand
|
||||
case len(g.Users) == 0:
|
||||
return g, errors.New("name at least one person, like `grant default @alice all`")
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
func ParseToggle(word string) (on, ok bool) {
|
||||
switch strings.ToLower(word) {
|
||||
case "on", "yes", "true", "allow", "allowed", "enable":
|
||||
return true, true
|
||||
case "off", "no", "false", "deny", "denied", "disable":
|
||||
return false, true
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
func NeededPermission(verb, args string) model.Action {
|
||||
switch verb {
|
||||
case "scale":
|
||||
if _, err := ParseScale(args, model.Size{MemoryMB: 1024, CPUs: 1}); !errors.Is(err, ErrNotCommand) {
|
||||
return model.ActScale
|
||||
}
|
||||
case "keep":
|
||||
if k, err := ParseKeep(args); !errors.Is(err, ErrNotCommand) && !k.Show {
|
||||
return model.ActKeep
|
||||
}
|
||||
case "storage", "disk":
|
||||
if args == "" {
|
||||
return ""
|
||||
}
|
||||
if _, _, err := ParseStorage(args, 1024, 1024); !errors.Is(err, ErrNotCommand) {
|
||||
return model.ActStorage
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"slackerbot/internal/model"
|
||||
)
|
||||
|
||||
func TestParseScale(t *testing.T) {
|
||||
cur := model.Size{MemoryMB: 2048, CPUs: 1}
|
||||
cases := []struct {
|
||||
in string
|
||||
want model.Size
|
||||
}{
|
||||
{"", model.Size{MemoryMB: 4096, CPUs: 2}},
|
||||
{"up", model.Size{MemoryMB: 4096, CPUs: 2}},
|
||||
{"down", model.Size{MemoryMB: 1024, CPUs: 0.5}},
|
||||
{"8G 4cpu", model.Size{MemoryMB: 8192, CPUs: 4}},
|
||||
{"8gb", model.Size{MemoryMB: 8192, CPUs: 1}},
|
||||
{"+2G", model.Size{MemoryMB: 4096, CPUs: 1}},
|
||||
{"-1cpu", model.Size{MemoryMB: 2048, CPUs: 0}},
|
||||
{"512M +0.5cpu", model.Size{MemoryMB: 512, CPUs: 1.5}},
|
||||
{"1.5G 3 cores", model.Size{MemoryMB: 1536, CPUs: 3}},
|
||||
{"+2 GB", model.Size{MemoryMB: 4096, CPUs: 1}},
|
||||
{"+1cpus -512mb", model.Size{MemoryMB: 1536, CPUs: 2}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, err := ParseScale(c.in, cur)
|
||||
if err != nil || got != c.want {
|
||||
t.Fatalf("scale %q = %v, %v; want %v", c.in, got, err, c.want)
|
||||
}
|
||||
}
|
||||
if _, err := ParseScale("the database to 3 replicas", cur); !errors.Is(err, ErrNotCommand) {
|
||||
t.Fatal("a normal sentence should go to the agent")
|
||||
}
|
||||
if _, err := ParseScale("4G lots", cur); err == nil || errors.Is(err, ErrNotCommand) {
|
||||
t.Fatal("a bad second word should be a usage error")
|
||||
}
|
||||
if _, err := ParseScale("4G 8G", cur); err == nil {
|
||||
t.Fatal("memory twice should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseKeep(t *testing.T) {
|
||||
for in, want := range map[string]time.Duration{
|
||||
"24h": 24 * time.Hour, "3d": 72 * time.Hour, "1d12h": 36 * time.Hour, "2w": 336 * time.Hour,
|
||||
"5 hours": 5 * time.Hour, "2 days": 48 * time.Hour, "1d 6h": 30 * time.Hour, "90 mins": 90 * time.Minute,
|
||||
} {
|
||||
k, err := ParseKeep(in)
|
||||
if err != nil || k.Limit != want {
|
||||
t.Fatalf("keep %q = %+v, %v; want %s", in, k, err, want)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{"indefinite", "Indefinitely", "forever"} {
|
||||
if k, _ := ParseKeep(in); !k.Indefinite {
|
||||
t.Fatalf("keep %q should be indefinite", in)
|
||||
}
|
||||
}
|
||||
if k, _ := ParseKeep("default"); !k.Reset {
|
||||
t.Fatal("keep default should reset")
|
||||
}
|
||||
if k, _ := ParseKeep(""); !k.Show {
|
||||
t.Fatal("bare keep should show")
|
||||
}
|
||||
if _, err := ParseKeep("the tests passing"); !errors.Is(err, ErrNotCommand) {
|
||||
t.Fatal("a normal sentence should go to the agent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHuman(t *testing.T) {
|
||||
for d, want := range map[time.Duration]string{
|
||||
6 * time.Hour: "6h", 36 * time.Hour: "1d12h", 90 * time.Minute: "1h30m",
|
||||
45 * time.Minute: "45m", 168 * time.Hour: "7d", 0: "0m",
|
||||
} {
|
||||
if got := Human(d); got != want {
|
||||
t.Fatalf("Human(%s) = %q, want %q", d, got, want)
|
||||
}
|
||||
}
|
||||
if got := (model.Size{MemoryMB: 8192, CPUs: 4}).String(); got != "8 GB RAM, 4 CPUs" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := (model.Size{MemoryMB: 512, CPUs: 0.25}).String(); got != "512 MB RAM, 0.25 CPUs" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseStorage(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
min, max int64
|
||||
}{
|
||||
{"20G", 5120, 20480},
|
||||
{"+5G", 5120, 15360},
|
||||
{"-2G", 5120, 8192},
|
||||
{"max 30G", 5120, 30720},
|
||||
{"min 8G", 8192, 10240},
|
||||
{"min +1G max 30 GB", 6144, 30720},
|
||||
{"cap 1T", 5120, 1048576},
|
||||
}
|
||||
for _, c := range cases {
|
||||
min, max, err := ParseStorage(c.in, 5120, 10240)
|
||||
if err != nil || min != c.min || max != c.max {
|
||||
t.Fatalf("storage %q = %d/%d, %v; want %d/%d", c.in, min, max, err, c.min, c.max)
|
||||
}
|
||||
}
|
||||
if _, _, err := ParseStorage("is full, clean up the logs", 5120, 10240); !errors.Is(err, ErrNotCommand) {
|
||||
t.Fatal("a normal sentence should go to the agent")
|
||||
}
|
||||
for _, in := range []string{"min", "20G 30G", "min 5G min 6G", "20G lots"} {
|
||||
if _, _, err := ParseStorage(in, 5120, 10240); err == nil || errors.Is(err, ErrNotCommand) {
|
||||
t.Fatalf("%q should be a usage error, got %v", in, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeededPermission(t *testing.T) {
|
||||
for in, want := range map[[2]string]model.Action{
|
||||
{"scale", "up"}: model.ActScale,
|
||||
{"scale", "8G 4cpu"}: model.ActScale,
|
||||
{"scale", "the db to 3 replicas"}: "",
|
||||
{"keep", ""}: "",
|
||||
{"keep", "24h"}: model.ActKeep,
|
||||
{"keep", "indefinite"}: model.ActKeep,
|
||||
{"keep", "the tests green"}: "",
|
||||
{"storage", ""}: "",
|
||||
{"storage", "20G"}: model.ActStorage,
|
||||
{"storage", "is full, clean it up"}: "",
|
||||
{"status", ""}: "",
|
||||
} {
|
||||
if got := NeededPermission(in[0], in[1]); got != want {
|
||||
t.Errorf("%s %q needs %q, want %q", in[0], in[1], got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGrant(t *testing.T) {
|
||||
g, err := ParseGrant("<@U1> <@U2|bob>, move scale")
|
||||
if err != nil || len(g.Users) != 2 || g.Users[1] != "U2" || len(g.Actions) != 2 {
|
||||
t.Fatalf("%+v %v", g, err)
|
||||
}
|
||||
if g, _ := ParseGrant("default <@U1> all"); !g.ToDefault || g.Actions[0] != "all" {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
for _, in := range []string{"me access to the repo", "all the things", ""} {
|
||||
if _, err := ParseGrant(in); !errors.Is(err, ErrNotCommand) {
|
||||
t.Errorf("%q should go to the agent, got %v", in, err)
|
||||
}
|
||||
}
|
||||
if _, err := ParseGrant("<@U1> teleport"); err == nil || errors.Is(err, ErrNotCommand) {
|
||||
t.Error("an unknown permission after a mention should be a usage error")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user