-
Notifications
You must be signed in to change notification settings - Fork 3
/
ArgStore.go
65 lines (52 loc) · 1.55 KB
/
ArgStore.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
package main
import (
"regexp"
"strings"
)
// ArgStore holds a mapping between argument keys and values
type ArgStore map[string]string
const (
// TODOs:
// - Restrict input set for key: [a-zA-Z0-9-_]
// - key should have shortest match, to allow value to contain "="
argPattern = "(?P<key>.*)=(?P<value>.*)"
)
var (
argRegex *regexp.Regexp // not used at the moment
)
func init() {
argRegex = regexp.MustCompile(argPattern)
}
// ArgStoreFromArgs takes a list of provided arguments and checks
// that they are in format "<key>=<value>". It will return
// an error on duplicate keys.
func ArgStoreFromArgs(args []string) (as ArgStore) {
as = make(ArgStore, len(args))
for _, arg := range args {
splitIdx := strings.Index(arg, "=")
Assert(splitIdx != -1, "No '=' found in argument")
Assert(splitIdx != 0, "No key found in argument")
Assert(splitIdx != (len(arg)-1), "No value found in argument")
key := arg[:splitIdx]
value := arg[(splitIdx + 1):]
if _, exists := as[key]; !exists {
as[key] = value
} else {
panic("Duplicate key found: " + key)
}
}
return as
}
// ArgStoreFromTemplateExamples returns an ArgStore that is filled with
// all the example texts contained in the provided template
func ArgStoreFromTemplateExamples(ct *ChronicleTemplate) (as ArgStore) {
contentIDs := ct.GetContentIDs(false)
as = make(ArgStore, len(contentIDs))
for _, id := range contentIDs {
ce, _ := ct.GetContent(id)
if IsSet(ce.Example()) {
as[id] = ce.Example()
}
}
return as
}