Skip to content

Instantly share code, notes, and snippets.

@Demian1996
Created July 4, 2021 15:12
Show Gist options
  • Save Demian1996/d0dc27d08b38943cdb4eea212690c363 to your computer and use it in GitHub Desktop.
Save Demian1996/d0dc27d08b38943cdb4eea212690c363 to your computer and use it in GitHub Desktop.
语法检测的git脚本demo
#!/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