Skip to content

Instantly share code, notes, and snippets.

@fand
Last active June 1, 2016 10:51
Show Gist options
  • Save fand/c13213f81bfce11f4132 to your computer and use it in GitHub Desktop.
Save fand/c13213f81bfce11f4132 to your computer and use it in GitHub Desktop.
日本語禁止する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
Copy link

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