/
index.js
89 lines (73 loc) · 2.01 KB
/
index.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
const marked = require('marked');
const prettier = require('prettier');
function getFlags(text) {
const match = text.trim().match(/^(?:\([a-zE]+\)\s*)+/);
return match ? match[0] : '';
}
function splitFlags(flags) {
return flags.trim().slice(1, -1).split(/\)\s*\(/);
}
module.exports = function transpile(text) {
const tokens = marked.lexer(text);
let currentDepth = 0;
let level = 0;
let open = false;
let buff = '';
function buffer(str) {
buff += `${str}`;
}
tokens.forEach(token => {
switch (token.type) {
case 'heading': {
let text = token.text.trim();
let type = 'describe';
const flagString = getFlags(text);
const flags = splitFlags(flagString);
text = text.replace(flagString, '');
if (flags.includes('only')) type = `${type}.only`;
if (flags.includes('skip')) type = `${type}.skip`;
if (currentDepth >= token.depth) {
level--;
buffer('});');
}
currentDepth = token.depth;
buffer(`${type}('${text}', function(){`);
level++;
break;
}
case 'paragraph': {
let text = token.text.trim();
let type = 'it';
const flagString = getFlags(text);
const flags = splitFlags(flagString);
const isAsync = flags.includes('async');
text = text.replace(flagString, '');
if (flags.includes('before')) type = `before`;
if (flags.includes('after')) type = `after`;
if (flags.includes('beforeEach')) type = `beforeEach`;
if (flags.includes('afterEach')) type = `afterEach`;
if (flags.includes('only')) type = `${type}.only`;
if (flags.includes('skip')) type = `${type}.skip`;
buffer(`${type}(${text ? `'${text}',` : ''}function(${isAsync ? 'done' : ''}){`);
level++;
open = true;
break;
}
case 'code':
buffer(token.text);
if (open) {
level--;
buffer('});\n\n');
open = false;
} else {
buffer('');
}
break;
}
});
while (level--) {
buffer('});');
}
buff = buff.replace(/,?function\(\)\{\}/g, '');
return prettier.format(buff, { parser: 'babel' });
}