-
-
Save Demian1996/d0dc27d08b38943cdb4eea212690c363 to your computer and use it in GitHub Desktop.
语法检测的git脚本demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const { exec } = require('child_process'); | |
const { ESLint } = require('eslint'); | |
function getDiffFileList() { | |
return new Promise((resolve, reject) => { | |
exec('git diff --cached --name-only --diff-filter=ACMR', (error, stdout) => { | |
if (error) { | |
reject(`exec error: ${error}`); | |
} | |
resolve(stdout.split('\n').filter((diffFile) => /(\.js|\.jsx|\.ts|\.tsx)(\n|$)/gi.test(diffFile))); | |
}); | |
}); | |
} | |
/** | |
* @description 调用eslint api | |
*/ | |
function lintFiles(fileList) { | |
const eslint = new ESLint(); | |
return eslint.lintFiles(fileList); | |
} | |
/** | |
* @description 整合并打印结果 | |
*/ | |
function output(resultList) { | |
resultList.forEach((result) => { | |
if (result.messages && result.messages.length > 0) { | |
console.error(`ESLint has found problems in file: ${result.filePath}`); | |
result.messages.forEach((msg) => { | |
if (msg.severity === 2) { | |
console.error(`Error: ${msg.message} in Line ${msg.line} Column ${msg.column}`); | |
} else { | |
console.warn(`Warning: ${msg.message} in Line ${msg.line} Column ${msg.column}`); | |
} | |
}); | |
} | |
}); | |
} | |
getDiffFileList().then(lintFiles).then(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment