Skip to content

Commit

Permalink
Update: key-spacing rule whitespace fixer (fixes eslint#6167) (eslint…
Browse files Browse the repository at this point in the history
  • Loading branch information
RRMoelker authored and btmills committed May 19, 2016
1 parent 04bd586 commit 74c458d
Show file tree
Hide file tree
Showing 2 changed files with 276 additions and 8 deletions.
54 changes: 47 additions & 7 deletions lib/rules/key-spacing.js
Expand Up @@ -118,6 +118,8 @@ module.exports = {
recommended: false
},

fixable: "whitespace",

schema: [{
anyOf: [
{
Expand Down Expand Up @@ -270,20 +272,58 @@ module.exports = {
*/
function report(property, side, whitespace, expected, mode) {
var diff = whitespace.length - expected,
key = property.key,
firstTokenAfterColon = sourceCode.getTokenAfter(getNextColon(key)),
location = side === "key" ? key.loc.start : firstTokenAfterColon.loc.start;
nextColon = getNextColon(property.key),
tokenBeforeColon = sourceCode.getTokenBefore(nextColon),
tokenAfterColon = sourceCode.getTokenAfter(nextColon),
isKeySide = side === "key",
locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start,
isExtra = diff > 0,
diffAbs = Math.abs(diff),
spaces = Array(diffAbs + 1).join(" "),
fix,
range;

if ((
diff && mode === "strict" ||
diff < 0 && mode === "minimum" ||
diff > 0 && !expected && mode === "minimum") &&
!(expected && containsLineTerminator(whitespace))
) {
context.report(property[side], location, messages[side], {
error: diff > 0 ? "Extra" : "Missing",
computed: property.computed ? "computed " : "",
key: getKey(property)
if (isExtra) {

// Remove whitespace
if (isKeySide) {
range = [tokenBeforeColon.end, tokenBeforeColon.end + diffAbs];
} else {
range = [tokenAfterColon.start - diffAbs, tokenAfterColon.start];
}
fix = function(fixer) {
return fixer.removeRange(range);
};
} else {

// Add whitespace
if (isKeySide) {
fix = function(fixer) {
return fixer.insertTextAfter(tokenBeforeColon, spaces);
};
} else {
fix = function(fixer) {
return fixer.insertTextBefore(tokenAfterColon, spaces);
};
}
}

context.report({
node: property[side],
loc: locStart,
message: messages[side],
data: {
error: isExtra ? "Extra" : "Missing",
computed: property.computed ? "computed " : "",
key: getKey(property)
},
fix: fix
});
}
}
Expand Down

0 comments on commit 74c458d

Please sign in to comment.