Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Chore: enable require-unicode-regexp on ESLint codebase (#11422)
  • Loading branch information
not-an-aardvark committed Feb 22, 2019
1 parent f6ba633 commit 5018378
Show file tree
Hide file tree
Showing 114 changed files with 310 additions and 308 deletions.
14 changes: 7 additions & 7 deletions Makefile.js
Expand Up @@ -42,7 +42,7 @@ const { cat, cd, cp, echo, exec, exit, find, ls, mkdir, pwd, rm, test } = requir
const PERF_MULTIPLIER = 13e6;

const OPEN_SOURCE_LICENSES = [
/MIT/, /BSD/, /Apache/, /ISC/, /WTF/, /Public Domain/, /LGPL/
/MIT/u, /BSD/u, /Apache/u, /ISC/u, /WTF/u, /Public Domain/u, /LGPL/u
];

//------------------------------------------------------------------------------
Expand Down Expand Up @@ -135,7 +135,7 @@ function generateBlogPost(releaseInfo, prereleaseMajorVersion) {
const ruleList = ls("lib/rules")

// Strip the .js extension
.map(ruleFileName => ruleFileName.replace(/\.js$/, ""))
.map(ruleFileName => ruleFileName.replace(/\.js$/u, ""))

/*
* Sort by length descending. This ensures that rule names which are substrings of other rule names are not
Expand Down Expand Up @@ -699,7 +699,7 @@ target.gensite = function(prereleaseVersion) {
} else {

// extract the title from the file itself
title = text.match(/#([^#].+)\n/);
title = text.match(/#([^#].+)\n/u);
if (title) {
title = title[1].trim();
} else {
Expand All @@ -720,10 +720,10 @@ target.gensite = function(prereleaseVersion) {
].join("\n");

// 6. Remove .md extension for relative links and change README to empty string
text = text.replace(/\((?!https?:\/\/)([^)]*?)\.md(.*?)\)/g, "($1$2)").replace("README.html", "");
text = text.replace(/\((?!https?:\/\/)([^)]*?)\.md(.*?)\)/gu, "($1$2)").replace("README.html", "");

// 7. Check if there's a trailing white line at the end of the file, if there isn't one, add it
if (!/\n$/.test(text)) {
if (!/\n$/u.test(text)) {
text = `${text}\n`;
}

Expand Down Expand Up @@ -827,8 +827,8 @@ target.checkRuleFiles = function() {
*/
function hasIdInTitle(id) {
const docText = cat(docFilename);
const idOldAtEndOfTitleRegExp = new RegExp(`^# (.*?) \\(${id}\\)`); // original format
const idNewAtBeginningOfTitleRegExp = new RegExp(`^# ${id}: `); // new format is same as rules index
const idOldAtEndOfTitleRegExp = new RegExp(`^# (.*?) \\(${id}\\)`, "u"); // original format
const idNewAtBeginningOfTitleRegExp = new RegExp(`^# ${id}: `, "u"); // new format is same as rules index
/*
* 1. Added support for new format.
* 2. Will remove support for old format after all docs files have new format.
Expand Down
4 changes: 2 additions & 2 deletions lib/cli-engine.js
Expand Up @@ -258,7 +258,7 @@ function processFile(filename, configHelper, options, linter) {
*/
function createIgnoreResult(filePath, baseDir) {
let message;
const isHidden = /^\./.test(path.basename(filePath));
const isHidden = /^\./u.test(path.basename(filePath));
const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
const isInBowerComponents = baseDir && path.relative(baseDir, filePath).startsWith("bower_components");

Expand Down Expand Up @@ -757,7 +757,7 @@ class CLIEngine {
if (typeof resolvedFormatName === "string") {

// replace \ with / for Windows compatibility
const normalizedFormatName = resolvedFormatName.replace(/\\/g, "/");
const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/");

const cwd = this.options ? this.options.cwd : process.cwd();
const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
Expand Down
4 changes: 2 additions & 2 deletions lib/config/config-file.js
Expand Up @@ -61,7 +61,7 @@ const resolver = new ModuleResolver();
* @private
*/
function readFile(filePath) {
return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/, "");
return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
}

/**
Expand All @@ -73,7 +73,7 @@ function readFile(filePath) {
* @private
*/
function isFilePath(filePath) {
return path.isAbsolute(filePath) || !/\w|@/.test(filePath.charAt(0));
return path.isAbsolute(filePath) || !/\w|@/u.test(filePath.charAt(0));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/config/config-initializer.js
Expand Up @@ -152,7 +152,7 @@ function configureRules(answers, config) {
bar.tick(0); // Shows the progress bar

// Get the SourceCode of all chosen files
const patterns = answers.patterns.split(/[\s]+/);
const patterns = answers.patterns.split(/[\s]+/u);

try {
sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => {
Expand Down
2 changes: 1 addition & 1 deletion lib/config/config-validator.js
Expand Up @@ -76,7 +76,7 @@ function validateRuleSeverity(options) {
return normSeverity;
}

throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, "")}').\n`);
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);

}

Expand Down
2 changes: 1 addition & 1 deletion lib/config/plugins.js
Expand Up @@ -84,7 +84,7 @@ class Plugins {
const shortName = naming.getShorthandName(longName, "eslint-plugin");
let plugin = null;

if (pluginName.match(/\s+/)) {
if (pluginName.match(/\s+/u)) {
const whitespaceError = new Error(`Whitespace found in plugin name '${pluginName}'`);

whitespaceError.messageTemplate = "whitespace-found";
Expand Down
2 changes: 1 addition & 1 deletion lib/formatters/codeframe.js
Expand Up @@ -47,7 +47,7 @@ function formatFilePath(filePath, line, column) {
*/
function formatMessage(message, parentResult) {
const type = (message.fatal || message.severity === 2) ? chalk.red("error") : chalk.yellow("warning");
const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/, "$1"))}`;
const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/u, "$1"))}`;
const ruleId = message.fatal ? "" : chalk.dim(`(${message.ruleId})`);
const filePath = formatFilePath(parentResult.filePath, message.line, message.column);
const sourceCode = parentResult.output ? parentResult.output : parentResult.source;
Expand Down
4 changes: 2 additions & 2 deletions lib/formatters/stylish.js
Expand Up @@ -65,7 +65,7 @@ module.exports = function(results) {
message.line || 0,
message.column || 0,
messageType,
message.message.replace(/([^ ])\.$/, "$1"),
message.message.replace(/([^ ])\.$/u, "$1"),
chalk.dim(message.ruleId || "")
];
}),
Expand All @@ -75,7 +75,7 @@ module.exports = function(results) {
return stripAnsi(str).length;
}
}
).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`;
).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`;
});

const total = errorCount + warningCount;
Expand Down
8 changes: 4 additions & 4 deletions lib/linter.js
Expand Up @@ -164,15 +164,15 @@ function getDirectiveComments(filename, ast, ruleMapper) {

ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
const trimmedCommentText = comment.value.trim();
const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/.exec(trimmedCommentText);
const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/u.exec(trimmedCommentText);

if (!match) {
return;
}

const directiveValue = trimmedCommentText.slice(match.index + match[1].length);

if (/^eslint-disable-(next-)?line$/.test(match[1])) {
if (/^eslint-disable-(next-)?line$/u.test(match[1])) {
if (comment.loc.start.line === comment.loc.end.line) {
const directiveType = match[1].slice("eslint-".length);

Expand Down Expand Up @@ -276,7 +276,7 @@ function normalizeEcmaVersion(ecmaVersion, isModule) {
return ecmaVersion;
}

const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//g;
const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu;

/**
* Checks whether or not there is a comment which has "eslint-env *" in a given text.
Expand Down Expand Up @@ -498,7 +498,7 @@ function parse(text, providedParserOptions, parserName, parserMap, filePath) {
} catch (ex) {

// If the message includes a leading line number, strip it:
const message = `Parsing error: ${ex.message.replace(/^line \d+:/i, "").trim()}`;
const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;

return {
success: false,
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/array-callback-return.js
Expand Up @@ -17,8 +17,8 @@ const astUtils = require("../util/ast-utils");
// Helpers
//------------------------------------------------------------------------------

const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/;
const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/;
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/u;

/**
* Checks a given code path segment is reachable.
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/arrow-body-style.js
Expand Up @@ -82,7 +82,7 @@ module.exports = {
* @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed.
*/
function hasASIProblem(token) {
return token && token.type === "Punctuator" && /^[([/`+-]/.test(token.value);
return token && token.type === "Punctuator" && /^[([/`+-]/u.test(token.value);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/camelcase.js
Expand Up @@ -90,7 +90,7 @@ module.exports = {
*/
function isAllowed(name) {
return allow.findIndex(
entry => name === entry || name.match(new RegExp(entry))
entry => name === entry || name.match(new RegExp(entry)) // eslint-disable-line require-unicode-regexp
) !== -1;
}

Expand Down Expand Up @@ -142,7 +142,7 @@ module.exports = {
* private/protected identifiers, strip them before checking if underscored
*/
const name = node.name,
nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/g, "")),
nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/gu, "")),
effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;

// First, we ignore the node if it match the ignore list
Expand Down
8 changes: 4 additions & 4 deletions lib/rules/capitalized-comments.js
Expand Up @@ -16,8 +16,8 @@ const astUtils = require("../util/ast-utils");
//------------------------------------------------------------------------------

const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN,
WHITESPACE = /\s/g,
MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/; // TODO: Combine w/ max-len pattern?
WHITESPACE = /\s/gu,
MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/u; // TODO: Combine w/ max-len pattern?

/*
* Base schema body for defining the basic capitalization rule, ignorePattern,
Expand Down Expand Up @@ -96,7 +96,7 @@ function createRegExpForIgnorePatterns(normalizedOptions) {
const ignorePatternStr = normalizedOptions[key].ignorePattern;

if (ignorePatternStr) {
const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`);
const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); // eslint-disable-line require-unicode-regexp

normalizedOptions[key].ignorePatternRegExp = regExp;
}
Expand Down Expand Up @@ -215,7 +215,7 @@ module.exports = {

// 2. Check for custom ignore pattern.
const commentWithoutAsterisks = comment.value
.replace(/\*/g, "");
.replace(/\*/gu, "");

if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) {
return true;
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/curly.js
Expand Up @@ -191,7 +191,7 @@ module.exports = {
return true;
}

if (/^[([/`+-]/.test(tokenAfter.value)) {
if (/^[([/`+-]/u.test(tokenAfter.value)) {

// If the next token starts with a character that would disrupt ASI, insert a semicolon.
return true;
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/default-case.js
Expand Up @@ -4,7 +4,7 @@
*/
"use strict";

const DEFAULT_COMMENT_PATTERN = /^no default$/i;
const DEFAULT_COMMENT_PATTERN = /^no default$/iu;

//------------------------------------------------------------------------------
// Rule Definition
Expand Down Expand Up @@ -39,7 +39,7 @@ module.exports = {
create(context) {
const options = context.options[0] || {};
const commentPattern = options.commentPattern
? new RegExp(options.commentPattern)
? new RegExp(options.commentPattern) // eslint-disable-line require-unicode-regexp
: DEFAULT_COMMENT_PATTERN;

const sourceCode = context.getSourceCode();
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/dot-notation.js
Expand Up @@ -14,7 +14,7 @@ const astUtils = require("../util/ast-utils");
// Rule Definition
//------------------------------------------------------------------------------

const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u;
const keywords = require("../util/keywords");

module.exports = {
Expand Down Expand Up @@ -61,7 +61,7 @@ module.exports = {
let allowPattern;

if (options.allowPattern) {
allowPattern = new RegExp(options.allowPattern);
allowPattern = new RegExp(options.allowPattern); // eslint-disable-line require-unicode-regexp
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/eol-last.js
Expand Up @@ -97,7 +97,7 @@ module.exports = {
loc: location,
messageId: "unexpected",
fix(fixer) {
const finalEOLs = /(?:\r?\n)+$/,
const finalEOLs = /(?:\r?\n)+$/u,
match = finalEOLs.exec(sourceCode.text),
start = match.index,
end = sourceCode.text.length;
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/func-call-spacing.js
Expand Up @@ -93,8 +93,8 @@ module.exports = {
return;
}

const textBetweenTokens = text.slice(prevToken.range[1], parenToken.range[0]).replace(/\/\*.*?\*\//g, "");
const hasWhitespace = /\s/.test(textBetweenTokens);
const textBetweenTokens = text.slice(prevToken.range[1], parenToken.range[0]).replace(/\/\*.*?\*\//gu, "");
const hasWhitespace = /\s/u.test(textBetweenTokens);
const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens);

/*
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/getter-return.js
Expand Up @@ -14,7 +14,7 @@ const astUtils = require("../util/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/;
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;

/**
* Checks a given code path segment is reachable.
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/handle-callback-err.js
Expand Up @@ -52,7 +52,7 @@ module.exports = {
*/
function matchesConfiguredErrorName(name) {
if (isPattern(errorArgument)) {
const regexp = new RegExp(errorArgument);
const regexp = new RegExp(errorArgument); // eslint-disable-line require-unicode-regexp

return regexp.test(name);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/id-match.js
Expand Up @@ -53,7 +53,7 @@ module.exports = {
// Options
//--------------------------------------------------------------------------
const pattern = context.options[0] || "^.+$",
regexp = new RegExp(pattern);
regexp = new RegExp(pattern); // eslint-disable-line require-unicode-regexp

const options = context.options[1] || {},
properties = !!options.properties,
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/indent-legacy.js
Expand Up @@ -975,7 +975,7 @@ module.exports = {
* @returns {boolean} the result
*/
function isWrappedInParenthesis(node) {
const regex = /^return\s*?\(\s*?\);*?/;
const regex = /^return\s*?\(\s*?\);*?/u;

const statementWithoutArgument = sourceCode.getText(node).replace(
sourceCode.getText(node.argument), ""
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/indent.js
Expand Up @@ -442,7 +442,7 @@ class OffsetStorage {
const offset = (
offsetInfo.from &&
offsetInfo.from.loc.start.line === token.loc.start.line &&
!/^\s*?\n/.test(token.value) &&
!/^\s*?\n/u.test(token.value) &&
!offsetInfo.force
) ? 0 : offsetInfo.offset * this._indentSize;

Expand Down Expand Up @@ -785,7 +785,7 @@ module.exports = {
* or the total number of linebreaks if the string is all whitespace.
*/
function countTrailingLinebreaks(string) {
const trailingWhitespace = string.match(/\s*$/)[0];
const trailingWhitespace = string.match(/\s*$/u)[0];
const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());

return linebreakMatches === null ? 0 : linebreakMatches.length;
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/jsx-quotes.js
Expand Up @@ -20,14 +20,14 @@ const QUOTE_SETTINGS = {
quote: "\"",
description: "singlequote",
convert(str) {
return str.replace(/'/g, "\"");
return str.replace(/'/gu, "\"");
}
},
"prefer-single": {
quote: "'",
description: "doublequote",
convert(str) {
return str.replace(/"/g, "'");
return str.replace(/"/gu, "'");
}
}
};
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/key-spacing.js
Expand Up @@ -528,7 +528,7 @@ module.exports = {
* @returns {Object} Whitespace before and after the property's colon.
*/
function getPropertyWhitespace(property) {
const whitespace = /(\s*):(\s*)/.exec(sourceCode.getText().slice(
const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice(
property.key.range[1], property.value.range[0]
));

Expand Down

0 comments on commit 5018378

Please sign in to comment.