forked from recursecenter/pairing-bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse_cmd.go
98 lines (87 loc) · 2.53 KB
/
parse_cmd.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"errors"
"fmt"
"regexp"
"strings"
)
type parsingErr struct{ msg string }
func (e parsingErr) Error() string {
return fmt.Sprintf("Error when parsing command: %s", e.msg)
}
func parseCmd(cmdStr string) (string, []string, error) {
var err error
var cmdList = []string{
"subscribe",
"unsubscribe",
"help",
"schedule",
"skip",
"unskip",
"status"}
var daysList = []string{
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"}
// convert the string to a slice
// after this, we have a value "cmd" of type []string
// where cmd[0] is the command and cmd[1:] are any arguments
space := regexp.MustCompile(`\s+`)
cmdStr = space.ReplaceAllString(cmdStr, ` `)
cmdStr = strings.TrimSpace(cmdStr)
cmdStr = strings.ToLower(cmdStr)
cmd := strings.Split(cmdStr, ` `)
// Big validation logic -- hellooo darkness my old frieeend
switch {
// if there's nothing in the command string srray
case len(cmd) == 0:
err = errors.New("the user-issued command was blank")
return "help", nil, err
// if there's a valid command and if there's no arguments
case contains(cmdList, cmd[0]) && len(cmd) == 1:
if cmd[0] == "schedule" || cmd[0] == "skip" || cmd[0] == "unskip" {
err = &parsingErr{"the user issued a command without args, but it reqired args"}
return "help", nil, err
}
return cmd[0], nil, err
// if there's a valid command and there's some arguments
case contains(cmdList, cmd[0]) && len(cmd) > 1:
switch {
case cmd[0] == "subscribe" || cmd[0] == "unsubscribe" || cmd[0] == "help" || cmd[0] == "status":
err = &parsingErr{"the user issued a command with args, but it disallowed args"}
return "help", nil, err
case cmd[0] == "skip" && (len(cmd) != 2 || cmd[1] != "tomorrow"):
err = &parsingErr{"the user issued SKIP with malformed arguments"}
return "help", nil, err
case cmd[0] == "unskip" && (len(cmd) != 2 || cmd[1] != "tomorrow"):
err = &parsingErr{"the user issued UNSKIP with malformed arguments"}
return "help", nil, err
case cmd[0] == "schedule":
for _, v := range cmd[1:] {
if !contains(daysList, v) {
err = &parsingErr{"the user issued SCHEDULE with malformed arguments"}
return "help", nil, err
}
}
fallthrough
default:
return cmd[0], cmd[1:], err
}
// if there's not a valid command
default:
err = &parsingErr{"the user-issued command wasn't valid"}
return "help", nil, err
}
}
func contains(list []string, cmd string) bool {
for _, v := range list {
if v == cmd {
return true
}
}
return false
}