-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathRule.ts
243 lines (206 loc) · 8.3 KB
/
Rule.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Utils from './utils';
import Condition from "./Condition";
import Mocks from "./Mocks";
import ThreadAction, {ActionAfterMatchType, BooleanActionType, InboxActionType} from './ThreadAction';
export class Rule {
public readonly condition: Condition;
public readonly thread_action: Readonly<ThreadAction>;
public readonly stage: number;
constructor(condition_str: string, thread_action: ThreadAction, stage: number) {
this.condition = new Condition(condition_str);
this.thread_action = thread_action;
this.stage = stage;
}
toString() {
return this.condition.toString();
}
private static parseBooleanValue(str: string): boolean {
if (str.length === 0) {
return false;
}
return ["-1", "0", "no", "n", "false", "f"].indexOf(str.trim().toLowerCase()) < 0;
}
private static parseNumberValue(str: string): number {
const result = parseInt(str.trim());
if (isNaN(result)) {
return Number.MAX_VALUE;
}
return result;
}
private static parseStringList(str: string, delimiter: string): string[] {
if (str.length === 0) {
return [];
}
return str.split(delimiter).map(s => s.trim());
}
private static parseBooleanActionType(str: string): BooleanActionType {
if (str.length === 0) {
return BooleanActionType.DEFAULT;
}
if (Rule.parseBooleanValue(str)) {
return BooleanActionType.ENABLE;
}
return BooleanActionType.DISABLE;
}
private static parseInboxActionType(str: string): InboxActionType {
if (str.length === 0) {
return InboxActionType.DEFAULT;
}
const result = InboxActionType[str.toUpperCase() as keyof typeof InboxActionType];
Utils.assert(result !== undefined, `Can't parse inbox action value ${str}.`);
return result;
}
private static parseActionAfterMatchType(str: string): ActionAfterMatchType {
if (str.length === 0) {
return ActionAfterMatchType.DEFAULT;
}
const result = ActionAfterMatchType[str.toUpperCase() as keyof typeof ActionAfterMatchType];
Utils.assert(result !== undefined, `Can't parse action_after_match value ${str}.`);
return result;
}
public static parseRules(values: string[][]): Rule[] {
const row_num = values.length;
const column_num = values[0].length;
// get header map from first row
const header_map: { [key: string]: number } = {
conditions: -1,
add_labels: -1,
move_to: -1,
mark_important: -1,
mark_read: -1,
stage: -1,
auto_label: -1,
disabled: -1,
action_after_match: -1,
};
for (let column = 0; column < column_num; column++) {
const name = values[0][column];
if (!(name in header_map)) {
throw `Invalid rule header:"${name}"`;
}
header_map[name] = column;
}
// Ensure all expected headers exist
for (const header_name in header_map) {
if (header_map[header_name] < 0) {
throw `Missing rule header: ${header_name}`;
}
}
// get rest rows
let rules = [];
for (let row = 1; row < row_num; row++) {
const condition_str = values[row][header_map["conditions"]];
if (condition_str.length === 0) {
continue;
}
const disabled = Rule.parseBooleanValue(values[row][header_map["disabled"]]);
if (disabled) {
continue;
}
const thread_action = new ThreadAction();
thread_action.addLabels(Rule.parseStringList(values[row][header_map["add_labels"]], ","));
thread_action.move_to = Rule.parseInboxActionType(values[row][header_map["move_to"]]);
thread_action.important = Rule.parseBooleanActionType(values[row][header_map["mark_important"]]);
thread_action.read = Rule.parseBooleanActionType(values[row][header_map["mark_read"]]);
thread_action.auto_label = Rule.parseBooleanActionType(values[row][header_map["auto_label"]]);
const actionAfterMatchStr = values[row][header_map["action_after_match"]] || '';
thread_action.action_after_match = Rule.parseActionAfterMatchType(actionAfterMatchStr);
const stage = Rule.parseNumberValue(values[row][header_map["stage"]]);
rules.push(new Rule(condition_str, thread_action, stage));
}
// sort by stage
rules.sort((a: Rule, b: Rule) => a.stage - b.stage);
return rules;
}
public static getRules(): Rule[] {
const values: string[][] = Utils.withTimer("GetRuleValues", () => {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('rules');
if (sheet === null) {
throw "Active sheet 'rules' not found";
}
const column_num = sheet.getLastColumn();
const row_num = sheet.getLastRow();
return sheet.getRange(1, 1, row_num, column_num)
.getDisplayValues()
.map(row => row.map(cell => cell.trim()));
});
const rules = Rule.parseRules(values);
console.log(`Parsed rules:\n${rules.map(rule => rule.toString()).join("\n---\n")}`);
return rules;
}
public static testRules(it: Function, expect: Function) {
if (typeof SpreadsheetApp !== 'undefined') {
// This can only be tested in the Sheet
it('Reads in default rules from Sheet', () => {
const rules = Rule.getRules();
expect(rules.length).toBeGreaterThan(0);
});
}
it('Reads in Header', () => {
const sheet = Mocks.getMockTestSheet([]);
const rules = Rule.parseRules(sheet);
expect(rules.length).toBe(0);
})
it('Fails with header missing item', () => {
const sheet = Mocks.getMockTestSheet([]);
sheet[0] = sheet[0].slice(0, -2);
expect(() => {Rule.parseRules(sheet)}).toThrow();
})
it('Loads Empty Rules', () => {
const sheet = Mocks.getMockTestSheet([{}, {}]);
const rules = Rule.parseRules(sheet);
expect(rules.length).toBe(0);
})
it('Loads Simple Rule', () => {
const sheet = Mocks.getMockTestSheet([
{
conditions: '(body /to: me/i)',
add_labels: 'abc, xyz',
stage: "5",
}]);
const rules = Rule.parseRules(sheet);
expect(rules.length).toBe(1);
expect(rules[0].stage).toBe(5);
expect(rules[0].thread_action.label_names.size).toBe(2);
})
it('Loaded Rules are sorted by stage', () => {
const sheet = Mocks.getMockTestSheet([
{
conditions: '(body /to: me/i)',
add_labels: 'abc, xyz',
stage: "5",
},
{
conditions: '(body /to: me/i)',
add_labels: 'abc, xyz',
stage: "15",
},
{
conditions: '(body /to: me/i)',
add_labels: 'abc, xyz',
stage: "1",
}
]);
const rules = Rule.parseRules(sheet);
expect(rules.length).toBe(3);
expect(rules[0].stage).toBe(1);
expect(rules[1].stage).toBe(5);
expect(rules[2].stage).toBe(15);
})
}
}