-
Notifications
You must be signed in to change notification settings - Fork 1
/
parsers.ts
72 lines (60 loc) · 2.3 KB
/
parsers.ts
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
export interface Trigger {
kind: string
options: {
[key: string]: string
}
}
/**
* Extracts a list of triggers from a note. Triggers are lines within the
* note which start with `/automate:${kind}` and may contain a list of comma
* separated options in the form of `key=value`.
* @param note The note containing instructions which should be parsed.
* @returns A list of triggers which were discovered in the note.
*/
export function parse(note: string): Trigger[] {
return (note || "").split('\n').map(l => l.trim()).filter(l => !!l && l.startsWith('/automate:')).map(l => l.substring('/automate:'.length)).map(v => ({
kind: !!~v.indexOf(' ') && v.substring(0, v.indexOf(' ')) || v,
options: parseOptions(!!~v.indexOf(' ') && v.substring(v.indexOf(' ') + 1) || '')
}))
}
function parseOptions(options: string): { [key: string]: string } {
let opts = options;
let results = {}
const optionSeparators = [',', ' ']
while (opts) {
const key = opts.substring(0, opts.indexOf('=')).trim()
const valueBase = opts.substring(opts.indexOf('=') + 1).trim()
if (valueBase[0] === '"') {
const value = valueBase.substring(1, valueBase.indexOf('"', 1))
results[key] = value
if (!~valueBase.indexOf('"', 1)) {
throw new Error(`Invalid options string: ${options}`)
}
opts = valueBase.substring(valueBase.indexOf('"', 1) + 1)
} else {
let hadSeparator = false
for (const separator of optionSeparators) {
if (!~valueBase.indexOf(separator)) continue;
const value = valueBase.substring(0, valueBase.indexOf(separator))
results[key] = value
opts = valueBase.substring(valueBase.indexOf(separator) + 1)
hadSeparator = true
break
}
if (!hadSeparator) {
results[key] = valueBase
break
}
}
while (opts.startsWith(' ')) {
opts = opts.substring(1).trim()
}
}
return results
}
export interface StockTrigger extends Trigger {
kind: "stocks"
}
export function isStocksTrigger(trigger: Trigger): trigger is StockTrigger {
return trigger.kind === "stocks"
}