/
index.js
executable file
·60 lines (55 loc) · 1.86 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
#!/usr/bin/env node
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const fs = require('fs-extra');
const argv = require('yargs').argv;
const countCallbacks = require('./countCallbacks');
const countFunctionLines = require('./countFunctionLines');
const CommentMap = require('./CommentMap');
function insertComments(originalCode) {
let codeLines = originalCode.split('\n');
let newCodeLines = [];
codeLines.forEach((originalLine, index) => {
let offset = 1;
const comments = CommentMap.comments[index + offset];
if (comments) {
const indentMatch = originalLine.match(/^(\s*)[^s]/);
const indent = indentMatch ? indentMatch[1] : '';
comments.forEach(comment => {
newCodeLines.push(`${indent}// ${comment}`);
offset++;
});
}
newCodeLines.push(originalLine);
});
return newCodeLines.join('\n');
}
async function pettifyFile(filename) {
if (filename.includes('.pettified.')) return;
let originalCode;
try {
originalCode = await fs.readFile(filename, 'utf8');
} catch(e) {
console.error(e);
}
if (originalCode) {
const ast = parser.parse(originalCode);
traverse(ast, {
exit: (path) => countCallbacks(path),
FunctionDeclaration: (path) => countFunctionLines(path)
});
const newCode = insertComments(originalCode);
let outputFile = filename;
if (argv.copy) {
const pathParts = filename.split('.');
outputFile = [...pathParts.slice(0, -1), 'pettified', pathParts.slice(-1)].join('.');
}
fs.writeFile(outputFile, newCode);
console.log('Wrote out ' + outputFile);
}
}
async function main() {
const files = argv._;
files.forEach(pettifyFile);
}
main();