forked from Chalarangelo/30-seconds-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlint-script.js
53 lines (53 loc) · 2.27 KB
/
lint-script.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
/*
This is the linter script that lints snippets.
Run using `npm run linter`.
You might have to run `npm i -g semistandard` for this script to run properly.
*/
// Load modules
const fs = require('fs-extra'), cp = require('child_process'), path = require('path'), chalk = require('chalk');
// Set variables for paths
var snippetsPath = './snippets';
// Read files, lint each one individually and update
try {
let snippetFilenames = fs.readdirSync(snippetsPath);
let jobCounter = 0;
snippetFilenames.sort((a, b) => {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
// Read each file, get its code, write it to a temporary file, pass it through
// semistandard, get the output from the file, update the original file.
for(let snippet of snippetFilenames){
// Start a timer for the file
console.time(`Linter (${snippet})`);
// Synchronously read data from the snippet, get the code, write it to a temporary file
let snippetData = fs.readFileSync(path.join(snippetsPath,snippet),'utf8');
let codeStart = snippetData.indexOf('```js'), codeEnd = snippetData.search(/```[\n\r\s]+```js/g);
let originalCode = snippetData.slice(codeStart+5,codeEnd);
while(jobCounter >= 20){
setTimeout(()=>{},1000);
}
const tempSnippet = snippet.replace('.md', '');
fs.writeFileSync(`${tempSnippet}.temp.js`,`${originalCode}`);
// Run semistandard asynchronously (only way this manages to run), get linted code
// and write back to the original snippet file. Remove temporary file
cp.exec(`semistandard "${tempSnippet}.temp.js" --fix`,{},(error, stdOut, stdErr) => {
jobCounter += 1;
let lintedCode = fs.readFileSync(`${tempSnippet}.temp.js`,'utf8');
fs.writeFile(path.join(snippetsPath,snippet), `${snippetData.slice(0, codeStart+5)+lintedCode+snippetData.slice(codeEnd)}`);
fs.unlink(`${tempSnippet}.temp.js`);
// Log a success message
console.log(`${chalk.green('SUCCESS!')} Linted snippet: ${snippet}`);
// Log the time taken for the file
console.timeEnd(`Linter (${snippet})`);
jobCounter -= 1;
});
}
}
catch (err){ // Handle errors (hopefully not!)
console.log(`${chalk.red('ERROR!')} During linting: ${err}`);
process.exit(1);
}