-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.go
More file actions
96 lines (83 loc) · 1.73 KB
/
Copy pathquery.go
File metadata and controls
96 lines (83 loc) · 1.73 KB
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
package main
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
type QueryArgs struct {
todoID int
text string
}
type Command int
type Query struct {
command Command
args QueryArgs
}
const (
show Command = iota + 1
add
edit
toggle
remove
unknown = -1
)
func parseInput(query string) (Query, error) {
valid, _ := validQuery(query)
if !valid {
return Query{command: unknown}, errors.New(fmt.Sprint("not a valid query"))
}
tokens := strings.Split(query, " ")
command := getCommand(tokens[0])
if contains([]Command{edit, toggle, remove}, command) {
id, err := strconv.ParseInt(tokens[1], 10, 32)
if err != nil {
return Query{command: unknown}, errors.New(fmt.Sprint("where is todo id?"))
}
return Query{
command: command,
args: QueryArgs{
todoID: int(id),
text: strings.Join(tokens[2:], " "),
},
}, nil
} else if command == add {
args := QueryArgs{text: strings.Join(tokens[1:], " ")}
return Query{command, args}, nil
}
return Query{command: command}, nil
}
func getCommand(command string) Command {
validCommands := map[string]Command{
"show": 1,
"view": 1,
"add": 2,
"new": 2,
"create": 2,
"edit": 3,
"update": 3,
"toggle": 4,
"done": 4,
"remove": 5,
"delete": 5,
"rm": 5,
}
command = strings.ToLower(command)
if com, ok := validCommands[command]; ok {
return com
}
return unknown
}
func validQuery(q string) (bool, error) {
queryRegex := `((?m)(show|view)$|(?m)(add|new|create)\s(.*)$|(?m)(edit|update)\s(\d*)\s(.*)$|(?m)(toggle|done|remove|delete|rm)\s(\d*)$)`
return regexp.MatchString(queryRegex, q)
}
func contains(arr []Command, n Command) bool {
for _, val := range arr {
if val == n {
return true
}
}
return false
}