-
Notifications
You must be signed in to change notification settings - Fork 0
/
makerflow.js
531 lines (492 loc) · 18 KB
/
makerflow.js
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
const config = require('./config');
const vscode = require('vscode');
const utcToZonedTime = require('date-fns-tz/utcToZonedTime');
const zonedTimeToUtc = require('date-fns-tz/zonedTimeToUtc');
const formatDistanceToNowStrict = require('date-fns/formatDistanceToNowStrict');
const parseJSON = require('date-fns/parseJSON');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const todoUtils = require('./todo-utils');
const eventUtils = require('./event-utils');
const pluralize = require('pluralize');
const { groupBy } = require('lodash');
let context = null;
let statusBarItem = null;
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
let tasksStatusItem = null;
let calendarStatusItem = null;
const beginFlowMode = async function () {
if (getSavedFlowMode() !== null) return;
await config.warnAboutApiTokenAvailability();
const apiTokenAvailable = await config.isApiTokenAvailable();
statusBarItem.text = "Flow Mode: Starting..."
context.globalState.update('startingFlowMode', true);
if (!apiTokenAvailable && vscode.workspace.getConfiguration('makerflow').doNotAskForApiToken) {
behaveAsInFlowMode(null, true);
} else if (apiTokenAvailable) {
exec("makerflow start --json --source=vscode", (error, stdout, stderr) => {
if (error) {
console.error(error);
statusBarItem.text = "Flow Mode: Off"
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
statusBarItem.text = "Flow Mode: Off"
return;
}
if (cliRespondedWithApiTokenUnavailable(stdout)) {
behaveAsInFlowMode(null, true);
} else {
try {
const response = JSON.parse(sanitizeCliOutput(stdout, true));
behaveAsInFlowMode(response.data, false);
} catch (e) {
console.error(`error behaving in flow mode for stdout ${stdout}`)
console.error(e)
}
}
});
}
context.globalState.update('startingFlowMode', false);
}
const endFlowMode = async function() {
if (getSavedFlowMode() === null) return;
await config.warnAboutApiTokenAvailability();
const apiTokenAvailable = await config.isApiTokenAvailable();
statusBarItem.text = "Flow Mode: Stopping..."
context.globalState.update('stoppingFlowMode', true);
if (!apiTokenAvailable && vscode.workspace.getConfiguration('makerflow').doNotAskForApiToken) {
behaveAsNOTInFlowMode(true);
} else if (apiTokenAvailable) {
const {error, stderr} = await exec("makerflow stop --json --source=vscode")
if (error) {
console.error(error);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
behaveAsNOTInFlowMode(false);
}
context.globalState.update('stoppingFlowMode', false);
}
const getOngoingFlowMode = async function() {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return null;
const {error, stdout, stderr} = await exec("makerflow ongoing --json --source=vscode")
if (error) {
console.error(error);
return null;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return null;
}
if (cliRespondedWithApiTokenUnavailable(stdout)) {
return null
}
try {
const newLocal = sanitizeCliOutput(stdout, true);
const response = JSON.parse(newLocal);
return response != null && response.hasOwnProperty("data") ? response.data : null
} catch (e) {
console.error(`error when fetching ongoingFlowMode for stdout ${stdout}`)
console.error(e);
}
}
const getAndProcessOngoingFlow = function() {
getOngoingFlowMode().then(flowMode => {
if (typeof flowMode !== 'undefined' && flowMode !== null && Object.keys(flowMode).length > 0) {
if (getSavedFlowMode() !== null && !(context.globalState.get('startingFlowMode') || context.globalState.get('stoppingFlowMode'))) {
updateElapsedTimeOnStatusBar();
return;
}
behaveAsInFlowMode(flowMode, true);
} else {
if (getSavedFlowMode() === null) return;
behaveAsNOTInFlowMode(true);
}
})
}
const getOngoingBreakMode = async function() {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return null;
const {error, stdout, stderr} = await exec("makerflow break ongoing --json --source=vscode")
if (error) {
console.error(error);
return null;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return null;
}
let response = null
try {
if (cliRespondedWithApiTokenUnavailable(stdout)) {
return null
}
const newLocal = sanitizeCliOutput(stdout, true);
response = JSON.parse(newLocal);
} catch (e) {
console.error(`error on getOngoingBreakMode for stdout: ${stdout}`)
console.error(e)
}
return response != null && response ? response : null
}
const getAndProcessOngoingBreak = function() {
getOngoingBreakMode().then(breakMode => {
if (typeof breakMode !== 'undefined' && breakMode !== null && Object.keys(breakMode).length > 0) {
if (getSavedBreakMode() !== null) {
updateElapsedTimeOnStatusBar();
return;
}
behaveAsInBreakMode(breakMode);
} else {
if (getSavedBreakMode() === null) return;
behaveAsNOTInBreakMode();
}
})
}
const toggleFlowMode = async function() {
statusBarItem.text = "Flow Mode: Toggling..."
if (await getOngoingFlowMode() === null) {
beginFlowMode();
} else {
endFlowMode();
}
}
const setContext = function (extensionContext) {
context = extensionContext;
}
const showFlowModeStartedNotification = function() {
const configVscode = vscode.workspace.getConfiguration('makerflow');
if (configVscode.doNotShowFlowModeNotification) return;
const dontShowAgainOption = "Don't show again";
const stopOption = "Stop";
vscode.window.showInformationMessage("Flow Mode running",
stopOption, dontShowAgainOption)
.then(option => {
if (option === dontShowAgainOption) {
configVscode.update("doNotShowFlowModeNotifications", true, true);
}
if (option === stopOption) {
endFlowMode();
}
});
}
const showFlowModeEndedNotification = function() {
const configVscode = vscode.workspace.getConfiguration('makerflow');
if (configVscode.doNotShowFlowModeNotification) return;
const dontShowAgainOption = "Don't show again";
vscode.window.showInformationMessage("Flow Mode ended",
dontShowAgainOption)
.then(option => {
if (option === dontShowAgainOption) {
configVscode.update("doNotShowFlowModeNotifications", true, true);
}
});
}
const setStatusBarItem = function(providedStatusBarItem) {
statusBarItem = providedStatusBarItem;
}
const setTasksStatusBarItem = function(providedStatusBarItem) {
tasksStatusItem = providedStatusBarItem;
}
const setCalendarStatusBarItem = function(providedStatusBarItem) {
calendarStatusItem = providedStatusBarItem;
}
const updateElapsedTimeOnStatusBar = function() {
let flowMode = getSavedFlowMode()
let breakMode = getSavedBreakMode();
if ((flowMode === null || Object.keys(flowMode).length === 0)
&& (breakMode === null || Object.keys(breakMode).length === 0)) return;
const prefix = flowMode === null ? "On Break: " : "Flow Mode: ";
statusBarItem.text = prefix + getElapsedTime(flowMode === null ? breakMode : flowMode);
}
const startBreak = async function(reason) {
await config.warnAboutApiTokenAvailability();
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable && vscode.workspace.getConfiguration('makerflow').doNotAskForApiToken) {
return;
} else if (apiTokenAvailable) {
statusBarItem.text = "Starting Break..."
exec(`makerflow break start --json${reason ? ' --reason=' + reason : ''} --source=vscode`, (error, stdout, stderr) => {
if (error) {
console.error(error);
statusBarItem.text = "Error when starting break"
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
statusBarItem.text = "Error when starting break"
return;
}
if (cliRespondedWithApiTokenUnavailable(stdout)) {
statusBarItem.text = "Cannot start break without API token"
return;
} else {
const response = JSON.parse(sanitizeCliOutput(stdout, true));
behaveAsInBreakMode(response);
}
});
}
}
const stopBreak = async function() {
await config.warnAboutApiTokenAvailability();
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable && vscode.workspace.getConfiguration('makerflow').doNotAskForApiToken) {
return;
} else if (apiTokenAvailable) {
statusBarItem.text = "Stopping Break..."
exec(`makerflow break stop --json --source=vscode`, (error, stdout, stderr) => {
if (error) {
console.error(error);
statusBarItem.text = "Error when stopping break"
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
statusBarItem.text = "Error when stopping break"
return;
}
if (cliRespondedWithApiTokenUnavailable(stdout)) {
statusBarItem.text = "Cannot stop break without API token"
return;
} else {
const response = JSON.parse(sanitizeCliOutput(stdout, true));
behaveAsNOTInBreakMode(response.data);
}
});
}
}
const clickStatusBar = function() {
const savedBreakMode = getSavedBreakMode();
if (savedBreakMode !== null && Object.keys(savedBreakMode).length > 0) {
stopBreak();
} else {
toggleFlowMode();
}
}
const fetchTasks = async function() {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return [];
const { error, stdout, stderr } = await exec(`makerflow tasks todo --json --source=vscode`)
if (error) {
console.error(error);
return [];
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return [];
}
const newLocal = sanitizeCliOutput(stdout, true);
const response = JSON.parse(newLocal);
return response != null ? response : []
}
const fetchTasksAndProcess = async function() {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return;
const tasks = await fetchTasks();
if (tasks.length === 0) {
tasksStatusItem.text = "No new tasks"
context.globalState.update('todos', []);
return;
}
tasks.forEach(t => todoUtils.enrichTodo(t));
context.globalState.update('todos', tasks);
let text = tasks.length + " new " + pluralize("tasks", tasks.length) + " - "
const slackTasks = tasks.filter(todoUtils.isSlackTodo);
let requireSeparator = false;
if (slackTasks.length > 0) {
text += "Slack: " + slackTasks.length;
requireSeparator = true;
}
const githubTasks = tasks.filter(todoUtils.isGithubTodo);
if (githubTasks.length > 0) {
if (requireSeparator) text += " | ";
text += "Github: " + githubTasks.length;
requireSeparator = true;
}
const bitbucketTasks = tasks.filter(todoUtils.isBitbucketTodo);
if (bitbucketTasks.length > 0) {
if (requireSeparator) text += " | ";
text += "Bitbucket: " + bitbucketTasks.length;
requireSeparator = true;
}
tasksStatusItem.text = text;
}
const fetchCalendarEvents = async function() {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return [];
const { error, stdout, stderr } = await exec(`makerflow events list --json --source=vscode`)
if (error) {
console.error(error);
return [];
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return [];
}
const newLocal = sanitizeCliOutput(stdout, true);
const response = JSON.parse(newLocal);
return response != null && response.hasOwnProperty("events") ? response.events : []
}
const fetchCalendarEventsAndProcess = async function() {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return;
const events = await fetchCalendarEvents();
if (events.length === 0) {
calendarStatusItem.text = "No upcoming calendar events"
context.globalState.update('calendarEvents', []);
return;
}
context.globalState.update('calendarEvents', events);
const groups = groupBy(events, eventUtils.calendarEventOngoingUpcoming);
let text = "Calendar - ";
let requireSeparator = false;
Object.keys(groups).forEach(function(key) {
if (requireSeparator) text += " | ";
text += key + ": " + groups[key].length;
requireSeparator = true;
});
calendarStatusItem.text = text;
}
const listTasks = async function() {
const tasks = context.globalState.get('todos');
if (tasks.length === 0) return;
tasks.forEach(t => todoUtils.enrichTodo(t));
const quickPickItems = tasks.map(todoUtils.createQuickPickItem);
const item = await vscode.window.showQuickPick(quickPickItems, {
placeHolder: "Select a task"
});
if (!item) return;
todoUtils.executeAction(item.todo, markAsDone);
}
const listEvents = async function() {
const events = context.globalState.get('calendarEvents');
if (events.length === 0) return;
const quickPickItems = events.map(eventUtils.createQuickPickItem);
const item = await vscode.window.showQuickPick(quickPickItems, {
placeHolder: "Select an event"
});
if (!item) return;
eventUtils.executeAction(item.event);
}
const markAsDone = async function(todo) {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return;
const { error, stdout, stderr } = await exec(`makerflow todo done ${JSON.stringify(todo)} --json --source=vscode`)
if (error) {
console.error(error);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
const newLocal = sanitizeCliOutput(stdout, true);
return JSON.parse(newLocal);
}
const recordProductiveActivity = async function(min, max) {
const apiTokenAvailable = await config.isApiTokenAvailable();
if (!apiTokenAvailable) return;
const { error, stderr } = await exec(`makerflow productive-activity --min=${min} --max=${max}`)
if (error) {
console.error(error);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
}
module.exports = {
beginFlowMode,
endFlowMode,
setContext,
toggleFlowMode,
showFlowModeStartedNotification,
showFlowModeEndedNotification,
setStatusBarItem,
setTasksStatusBarItem,
setCalendarStatusBarItem,
getAndProcessOngingFlow: getAndProcessOngoingFlow,
updateElapsedTimeOnStatusBar,
startBreak,
stopBreak,
getAndProcessOngoingBreak,
clickStatusBar,
fetchTasks,
fetchTasksAndProcess,
fetchCalendarEventsAndProcess,
listTasks,
recordProductiveActivity,
listEvents
}
/**
*
* @param {string} stdout
* @param {boolean} expectJson
* @returns {string} sanitized output
*/
function sanitizeCliOutput(stdout, expectJson) {
const newLocal = stdout.replaceAll('[0m', '');
if (stdout.length === 0 ) return stdout
let trimmedOutput = newLocal.trim();
if (trimmedOutput === "null") return trimmedOutput;
if (expectJson && !(trimmedOutput.charAt(0) === '{' || trimmedOutput.charAt(0) === '[')) {
trimmedOutput = trimmedOutput.substring(1)
}
return trimmedOutput;
}
function cliRespondedWithApiTokenUnavailable(stdout) {
return stdout.indexOf("API token not available") !== -1;
}
function getSavedFlowMode() {
return context.globalState.get('ongoingFlowMode', null);
}
function getSavedBreakMode() {
return context.globalState.get('ongoingBreakMode', null);
}
function behaveAsNOTInFlowMode(clientOnly) {
if (clientOnly && !context.globalState.get('startingFlowMode')) {
exec("makerflow stop --client-only --json --source=vscode");
}
showFlowModeEndedNotification();
context.globalState.update('ongoingFlowMode', null);
statusBarItem.text = "Flow Mode: Off";
}
function behaveAsNOTInBreakMode() {
context.globalState.update('ongoingBreakMode', null);
if (statusBarItem.text.indexOf("Break") !== -1) {
statusBarItem.text = "Flow Mode: Off";
}
}
function behaveAsInFlowMode(flowMode, clientOnly) {
if (clientOnly && !context.globalState.get('stoppingFlowMode')) {
exec("makerflow start --client-only --json --source=vscode");
}
showFlowModeStartedNotification();
if (typeof flowMode === "undefined" || flowMode === null) {
flowMode = {
start: zonedTimeToUtc(Date.now(), timeZone)
}
}
context.globalState.update('ongoingFlowMode', flowMode);
updateElapsedTimeOnStatusBar();
tasksStatusItem.text = "End flow mode to see tasks and notifications";
}
function behaveAsInBreakMode(breakMode) {
if (typeof breakMode === "undefined" || breakMode === null) {
breakMode = {
start: zonedTimeToUtc(Date.now(), timeZone)
}
}
context.globalState.update('ongoingBreakMode', breakMode);
updateElapsedTimeOnStatusBar();
}
function getElapsedTime(flowMode) {
return formatDistanceToNowStrict(utcToZonedTime(parseJSON(flowMode.start), timeZone));
}