forked from CodecrumbsIO/codecrumbs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodecrumbs.js
More file actions
80 lines (65 loc) · 2.18 KB
/
Copy pathcodecrumbs.js
File metadata and controls
80 lines (65 loc) · 2.18 KB
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
const babylon = require('babylon');
const babelTraverse = require('babel-traverse');
const CRUMB = 'codecrumb',
CRUMB_SHORT_HANDLER = 'cc';
const parseCodecrumbComment = (node = {}) => {
const comment = node.value || '';
const cc = { original: comment };
const afterAlias = comment.split(':')[1];
if (afterAlias) {
const simplified = afterAlias.split(';');
cc.name = simplified[0];
cc.details = simplified[1];
}
return cc;
};
const isCodecrumb = (node = {}) => {
const comment = node.value || '';
return comment.startsWith(CRUMB) || comment.startsWith(CRUMB_SHORT_HANDLER);
};
const getCrumbs = fileCode => {
let ast = {};
const crumbsList = [];
try {
ast = babylon.parse(fileCode, { sourceType: 'module' });
} catch (e) {
console.log(e);
return crumbsList;
}
babelTraverse.default(ast, {
enter(path) {
const node = path.node;
if (!node || !(node.leadingComments || node.trailingComments))
return;
const leadingComment = node.leadingComments
? node.leadingComments[node.leadingComments.length - 1]
: null;
let trailingComment = node.trailingComments
? node.trailingComments[0]
: null;
if (
trailingComment &&
trailingComment.loc.start.line !== node.loc.start.line
) {
trailingComment = null;
}
[leadingComment, trailingComment].forEach(comment => {
if (comment && isCodecrumb(comment)) {
const params = parseCodecrumbComment(comment);
const loc = node.loc.start;
crumbsList.push({
name: params.name || '', //TODO: check, can be bug with layout calc
displayLoc: `(${loc.line},${loc.column})`,
crumbedLineNode: node,
crumbNode: comment,
params
});
}
});
}
});
return crumbsList;
};
module.exports = {
getCrumbs
};