Skip to content

Instantly share code, notes, and snippets.

@shenqihui
Created December 21, 2021 03:50
Show Gist options
  • Save shenqihui/8321f6265389b653099e36930efc0043 to your computer and use it in GitHub Desktop.
Save shenqihui/8321f6265389b653099e36930efc0043 to your computer and use it in GitHub Desktop.
husky custom linter
#!/usr/bin/env node
// 这个需要加 x 权限,记得
const argv = require('yargs').argv;
const path = require('path');
// const fs = require('fs-extra');
const _ = require('lodash');
function imgLinter() {
const base = path.resolve(__dirname, 'src', 'assets');
let errorArr = [];
_.each(argv._, (elem) => {
if (_.startsWith(elem, base)) {
errorArr.push(`文件 src/assets${_.replace(elem, base, '')} 不能放在这里,需要就近放回使用的地方`);
}
});
return {
msg: '图片存放不规范',
errorArr
};
}
function nameLinter() {
const base = path.resolve(__dirname) + '/';
let errorArr = [];
_.each(argv._, (elem) => {
const offsetPath = _.replace(elem, base, '');
if (/[A-Z]+/.test(offsetPath)) {
errorArr.push(`文件 ${offsetPath} 有大写`);
}
else if (/[\u4e00-\u9fa5]+/.test(offsetPath)) {
errorArr.push(`文件 ${offsetPath} 有中文`);
}
else if (/[\s]+/.test(offsetPath)) {
errorArr.push(`文件 ${offsetPath} 有空格`);
}
else if (/[@]+/.test(offsetPath)) {
errorArr.push(`文件 ${offsetPath} 有@`);
}
});
return {
msg: '路径不规范,不能有大写和中文和特殊字符',
errorArr
};
}
let errorArr = [];
let msg = '';
if ('name' === argv.type) {
const res = nameLinter();
msg = res.msg;
errorArr = res.errorArr;
}
else if ('img' === argv.type) {
const res = imgLinter();
msg = res.msg;
errorArr = res.errorArr;
}
if (errorArr && errorArr.length) {
process.exitCode = 1;
console.error(msg);
console.error(errorArr.join('\n') + '\n\n\n');
}
else {
process.exitCode = 0;
}
{
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": "eslint",
"*.{png,jpeg,jpg}": "./file-linter.js --type img",
"*.*": "./file-linter.js --type name"
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment