-
-
Save sigorilla/5a9867ff995b76990d4512f70ae7bf43 to your computer and use it in GitHub Desktop.
Eslint rule to forbid writing non-ASCII characters
This file contains hidden or 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
/** | |
* @fileoverview Rule to forbid writing non-ASCII characters. | |
* @author amagitakayosi | |
*/ | |
"use strict"; | |
/** | |
* ASCII characters. | |
*/ | |
var ASCII_REGEXP = new RegExp('([^\x00-\x7F]+)', 'g'); | |
/** | |
* Allowed types of token for non-ASCII characters. | |
*/ | |
var ALLOWED_TOKENS = ['RegularExpression', 'String']; | |
//------------------------------------------------------------------------------ | |
// Rule Definition | |
//------------------------------------------------------------------------------ | |
module.exports = function (context) { | |
var configuration = context.options[0] || {}; | |
return { | |
Program: function checkForForbiddenCharacters(node) { | |
var allowedChars = configuration.allowedChars || ''; | |
var allowedCharsRegExp = new RegExp('[' + allowedChars + ']+', 'g'); | |
var errors = []; | |
var sourceCode = context.getSourceCode(); | |
var tokens = sourceCode.getTokens(node); | |
tokens.forEach(function (token) { | |
if (ALLOWED_TOKENS.indexOf(token.type) !== -1) { | |
return; | |
} | |
var value = token.value; | |
var matches = value.replace(allowedCharsRegExp, '').match(ASCII_REGEXP); | |
if (matches) { | |
errors.push({ | |
line: token.loc.start.line, | |
column: token.loc.start.column + value.indexOf(matches[0]), | |
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' | |
} | |
}, | |
additionalProperties: false | |
}]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mitchellh can we allow only emoji?