Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
日本語禁止するESLintルール
/**
* @fileoverview Rule to forbid writing Japanese
* @author amagitakayosi
*/
"use strict";
var path = require('path');
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function (context) {
return {
"Program": function checkForForbiddenCharacters(node) {
// 除外するファイルは無視する
var excludePaths = context.options[0].excludePaths;
for (var i = 0; i < excludePaths.length; i++) {
var excludePathFull = path.resolve(__dirname, '..', excludePaths[i]) + '';
if (context.getFilename().match(excludePathFull)) {
return;
}
}
// 許容する文字を指定
var allowedChars = context.options[0].allowedChars || '';
var allowedCharsRegExp = new RegExp(
'[' +allowedChars + ']+', 'g'
);
var errors = [];
// asciiでない文字を含むトークンを記憶する
var sourceCode = context.getSourceCode();
var tokens = sourceCode.getTokens(node);
tokens.forEach(function (token) {
var value = token.value;
var matches = value.match(/([^\x00-\x7F]+)/g);
if (matches) {
value = value.replace(allowedCharsRegExp, '');
}
matches = value.match(/([^\x00-\x7F]+)/g);
if (matches) {
errors.push({
line : token.loc.start.line,
column : token.loc.start.column,
char : matches[0],
});
}
});
// エラーを出力
errors.forEach(function (error) {
context.report(node, {
line : error.line,
column : error.column,
}, 'Non-ascii character "' + error.char + '" found');
});
}
};
};
module.exports.schema = [
{
"type": "object",
"properties": {
"allowedChars": {
"type": "string",
},
"excludePaths": {
"type": "array",
},
},
"additionalProperties": false,
},
];
@sigorilla

This comment has been minimized.

Copy link

commented Jun 1, 2016

Awesome! 💯 It works for all languages, not only Japanese 😄

JFYI: my fork with some changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.