-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflowery.js
516 lines (377 loc) · 12.4 KB
/
flowery.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
#!/usr/bin/env node
// if ( process.env.NODE_ENV && process.env.NODE_ENV !== 'production' ) {
// process.stdout.write( '\u001B[2J\u001B[0;0f' );
// }
/*
Usage
# CLI
- let flowery run flow for you
$ flowery // equals to $ flow --json | flowery
- pipe in content
$ flow --json | flowery // useful for adding arguments to flow
- pass in txt file generated by flow
$ flowery log.txt
# API
import flowery from './flowery';
var result = flowery('json string generated by flow');
console.log(result)
// {arrErrors: [...], arrMessages: [...], joinedMessages: '....' }
*/
import fs from 'fs';
import path from 'path';
import {execFile} from 'child_process';
import chalk from 'chalk';
const SIMPLE = 1;
const NORMAL = 2;
const TYPE_ERROR = 3;
const INVERTED = 4;
const mapFiles = {};
let arrMessages, results;
// invoked via API (from node.js)
export default function flowery( json:String ) {
// console.log( 'API 收到資料: ', json );
let data = parseJson( json )
if ( !data ) return process.exit( 1 );
let arrErrors = generateErrorObjects( data );
if ( arrErrors ) {
arrMessages = generateErrorMessages( arrErrors );
let joinedMessages = arrMessages.join( '' );
console.log( joinedMessages );
return {arrErrors, arrMessages, joinedMessages}
}else {
return null;
}
}
// console.log( '\n版號: ', require('./package.json').version );
let vPath = ( __dirname.indexOf('build') == -1 ) ? './package.json' : '../package.json';
const $VERSION = require(vPath).version;
// invoked via CLI
if ( process.argv.length > 2 ) {
let arg = process.argv[2];
if( arg == '--version' || arg == '-v' ){
console.log($VERSION);
process.exit(0);
}
// 有傳入檔案名稱的話,代表已有 flow 生成的 json log txt,可直接開檔
readFile( arg )
.then( data => {
go( data );
} );
} else {
readStdin()
.then( data => {
debugger;
go( data );
} )
.catch( err => {
// 既沒有 CLI argument,也沒有 pipe 東西進來,就代為執行 $ flow | flowery
runner();
} )
}
function go( data ) {
// console.log( 'stdin data: ', data );
let arrErrors = generateErrorObjects( data )
if ( arrErrors ) {
arrMessages = generateErrorMessages( arrErrors );
results = arrMessages.join( '' );
writeFile( chalk.stripColor(results) );
console.log( results );
console.log( `\nflowery v${$VERSION}` );
return results;
}else {
console.log( 'No Error!' );
return 'No Error!';
}
}
// use chalk.stripColor() instead
function stripColors(str){
return str.replace( /\x1b\[[0-9;]*m/g, '' );
}
// runs flow then pipe into flowery
// equals CLI command '$ flow --json | flowery'
function runner() {
execFile( 'flow', ['--json'], function( error, stdout, stderr ) {
if ( stderr && stderr.indexOf('Flow server launched for') == -1 ) {
return console.log( 'Flowery runner error: ', stderr );
}
let data = parseJson( stdout );
if ( !data ) return process.exit( 1 );
go( data );
} );
// check if flow existed
/*execFile( 'which', ['flow'], function( error, stdout, stderr ) {
if(!stdout){
return console.log('Flow not found, be sure to install it first.');
}
execFile( 'flow', ['--json'], function( error, stdout, stderr ) {
if ( stderr ) {
return console.log( 'runner err: ', stderr );
}
let data = parseJson( stdout );
if ( !data ) return process.exit( 1 );
go( data );
} );
})*/
}
// 如果是透過 cli pipe 進來的,就從 stdin 讀資料
// $ flow | babel-node code.js
function readStdin() {
return new Promise( ( resolve, reject ) => {
let content;
process.stdin.setEncoding( 'utf8' );
process.stdin.on( 'readable', function() {
content = process.stdin.read();
if ( content !== null ) {
// 有讀到東西,但有可能是 JSON
content = parseJson( content )
if ( !content ) return process.exit( 1 );
resolve( content );
} else {
reject( 'no data' );
process.stdin.end(); // pause()
}
} );
} )
}
// 將 json string 轉回 js obj
function parseJson( data ) {
let content;
try {
content = JSON.parse( data );
}catch ( e ) {
console.error( 'Invalid JSON format, did you forget to add "--json" argument to flow?' );
return null;
}
return content;
}
// 讀取檔案,並解析 JSON 後返還結果
function readFile( name ) {
let data, content;
return new Promise( ( resolve, reject ) => {
data = fs.readFileSync( name, {encoding:'utf8'} );
content = parseJson( data );
resolve( content );
} )
}
// 逐條將每個錯誤整理成 {invoke:..., receive:..., type:...} 正規化格式,方便日後使用
function generateErrorObjects( {errors, passed, version} ) {
if ( passed ) return null;
let invoke, receive, lines, errLineContent, errSelection;
let arrErrors = errors.map( item => {
let arrMessage = item.message;
switch ( arrMessage.length ) {
case 1:
invoke = arrMessage[0];
lines = getTargetFile( invoke.path );
errLineContent = lines[invoke.line - 1];
errSelection = errLineContent.substring( invoke.start - 1, invoke.end );
let msg = invoke.descr.split( '\n' );
let o = {
errTarget: msg[0],
errMsg: msg[1],
errPath: invoke.path,
errLine: invoke.line,
errLineContent,
errSelection,
errStart: invoke.start,
errEnd: invoke.end,
}
return {invoke: o, receive: null, type: SIMPLE };
case 2:
invoke = arrMessage[0];
receive = arrMessage[1]; // 用不到
if (arrMessage[0].descr.indexOf('type is incompatible') != -1) {
// 特例:處理只有2筆 messages 但應該是 type error
arrMessage.unshift('dummy');
}else{
lines = getTargetFile( invoke.path );
errLineContent = lines[invoke.line - 1];
errSelection = errLineContent.substring( invoke.start - 1, invoke.end );
// errMsg: "Property not found in" ← in 拿掉,將 length 組合進去
// errTarget: "property length" ← 取出 length 值
var msg = invoke.descr.split( '\n' );
let prop = msg[0].replace( 'property ', '' );
prop = chalk.yellow(prop);
let _msg = msg[1].replace( 'Property', 'Property ' + prop ).replace( ' in', '' )
var o = {
errTarget: msg[0],
errMsg: _msg,
errPath: invoke.path,
errLine: invoke.line,
errLineContent,
errSelection,
errStart: invoke.start,
errEnd: invoke.end,
}
return {invoke: o, receive: null, type: NORMAL };
}
case 3:
if ( arrMessage[1].descr.indexOf( 'type is incompatible' ) != -1 ) {
// +TYPE ERROR+
invoke = arrMessage[1];
receive = arrMessage[2];
lines = getTargetFile( invoke.path );
errLineContent = lines[invoke.line - 1];
errSelection = errLineContent.substring( invoke.start - 1, invoke.end );
msg = invoke.descr.split( '\n' );
var o1 = {
errTarget: msg[0],
errMsg: msg[1],
errPath: invoke.path,
errLine: invoke.line,
errLineContent,
errSelection,
errStart: invoke.start,
errEnd: invoke.end,
}
var o2 = {
errTarget: receive.descr,
errMsg: null,
errPath: receive.path,
errLine: receive.line,
errLineContent: getTargetFile( receive.path )[receive.line - 1],
errSelection: null,
errStart: receive.start,
errEnd: receive.end,
}
return { invoke: o1, receive: o2, type: TYPE_ERROR };
}else {
// +INVERTED+
invoke = arrMessage[2];
receive = arrMessage[1];
lines = getTargetFile( invoke.path );
errLineContent = lines[invoke.line - 1];
errSelection = errLineContent.substring( invoke.start - 1, invoke.end );
msg = receive.descr.split( '\n' );
var o1 = {
errTarget: null,
errMsg: msg[1].replace( 'Property cannot be accessed on ', '' ), // 人工改過
errPath: invoke.path,
errLine: invoke.line,
errLineContent: getTargetFile( invoke.path )[invoke.line - 1],
errSelection: null,
errStart: invoke.start,
errEnd: invoke.end,
}
lines = getTargetFile( receive.path );
errLineContent = lines[receive.line - 1];
errSelection = errLineContent.substring( receive.start - 1, receive.end );
// 將字串加工成易讀的訊息
msg = receive.descr.split( '\n' );
// msg[0] errTarget: "property length"
// msg[1] errMsg: "Property cannot be accessed on possibly null value"
let prop = msg[0].replace( 'property ', '' ); // 得到 length 字串
prop = chalk.yellow(prop);
msg[1] = msg[1].split( ' ' );
msg[1].splice( 1, 0, prop );
msg[1] = msg[1].join( ' ' );
var o2 = {
errTarget: msg[0],
errMsg: msg[1],
errPath: receive.path,
errLine: receive.line,
errLineContent: getTargetFile( receive.path )[receive.line - 1],
errSelection: null,
errStart: receive.start,
errEnd: receive.end,
}
}
return { invoke: o1, receive: o2, type: INVERTED };
}
} )
// 加上日期與錯誤數量等 meta data
// let date = 'Created: ' + new Date().toString() + '\n';
// arrErrors = [{ createdDate: date }, {total: arrErrors.length}, ...arrErrors];
return arrErrors;
}
// 將整理好的 errors arr 逐條生成易讀的錯誤訊息
// 內含 color code
function generateErrorMessages( arrErrors ) {
// 應用:從 errObj 內生成錯誤訊息字串,方便 screen print 或寫出檔案
let arrMessages = arrErrors.reduce(
( ac, item, idx ) => {
return [...ac, formatMessage( item, idx )];
}, []
);
// 偷加上日期與錯誤數量等 meta data
let date = 'Created: ' + new Date().toString() + '\n';
arrMessages = [date, ...arrMessages, `\nTotal Errors: ${chalk.white.bgRed(arrMessages.length)}`];
// console.log( '\n\n>>arrMessages: ', JSON.stringify(arrMessages, null, 2) );
// console.log( '錯誤數量:', errCount );
return arrMessages;
}
// 這是 arrErrors 的一種應用,就是漂亮的打印出來
// errObj: { invoke: o1, receive: o2, type: INVERTED }
function formatMessage( {invoke, receive, type}, idx ) {
idx = idx + 1;
let template, result, spaces, spaces2;
// console.log( '\ninvokeObj: ', invoke, '\n\nreceive: ', receive, '\ntype: ', type );
switch ( type ){
case SIMPLE:
spaces = new Array( invoke.errStart ).join( ' ' );
template = `
${chalk.white.bgRed(`${idx}. Error:`)}\n
${invoke.errPath}, line ${chalk.white(invoke.errLine)}
${invoke.errLineContent}
${spaces}${chalk.white('↑')} ${chalk.white(invoke.errMsg)}: ${chalk.yellow(invoke.errTarget)}
`;
break;
case NORMAL:
spaces = new Array( invoke.errStart ).join( ' ' );
template = `
${chalk.white.bgRed(`${idx}. Error:`)}\n
${invoke.errPath}, line ${chalk.white(invoke.errLine)}
${invoke.errLineContent}
${spaces}${chalk.white('↑')} ${chalk.white(invoke.errMsg)}
`;
break;
case TYPE_ERROR:
// debugger;
spaces = new Array( invoke.errStart ).join( ' ' );
spaces2 = new Array( receive.errStart ).join( ' ' );
template = `
${chalk.white.bgRed(`${idx}. Error:`)}\n
${invoke.errPath}, line ${chalk.white(invoke.errLine)}
${invoke.errLineContent}
${spaces}${chalk.white('↑ type should be')} ${chalk.yellow(receive.errTarget)}${chalk.white(', got')} ${chalk.yellow(invoke.errTarget)}
From:
${receive.errPath}, line ${chalk.white(receive.errLine)}
${receive.errLineContent}
${spaces2}${chalk.white('↑ cause')}
`;
break;
case INVERTED:
// debugger;
spaces = new Array( invoke.errStart ).join( ' ' );
spaces2 = new Array( receive.errStart ).join( ' ' );
// 特別之處: 這裏拿到的 inovke 與 receive 在早先整理時已被對調過
template = `
${chalk.white.bgRed(`${idx}. Error:`)}\n
${invoke.errPath}, line ${chalk.white(invoke.errLine)}
${invoke.errLineContent}
${spaces}${chalk.white('↑')} ${chalk.white(invoke.errMsg)}
From:
${receive.errPath}, line ${chalk.white(receive.errLine)}
${receive.errLineContent}
${spaces2}${chalk.white('↑')} ${chalk.white(receive.errMsg)}
`;
break;
}
result = template.replace( /\t/gi, '' );
return result;
}
function getTargetFile( file ) {
// 先檢查是否已讀過此檔案
let contents = mapFiles[file];
if(!contents){
contents = fs.readFileSync( file, {encoding:'utf8'} ).split( '\n' );
mapFiles[file] = contents;
}
return contents;
}
function writeFile( data ) {
fs.writeFile( 'flow-results.txt', data, function( err ) {
if ( err ) throw err;
// console.log( '\nflow-results.txt saved.' );
} );
}