Skip to content
Permalink
Browse files

Fix: Allow same-line comments in padded-blocks (fixes #5055)

This allows comments that occur on the same line as the opening or
closing brace.
  • Loading branch information...
btmills committed Feb 1, 2016
1 parent 67e1743 commit fae1884d23fada3c9c2fb9d2d7d08d20b888e7e1
Showing with 20 additions and 18 deletions.
  1. +18 −18 lib/rules/padded-blocks.js
  2. +2 −0 tests/lib/rules/padded-blocks.js
@@ -16,20 +16,6 @@ module.exports = function(context) {
var ALWAYS_MESSAGE = "Block must be padded by blank lines.",
NEVER_MESSAGE = "Block must not be padded by blank lines.";

/**
* Retrieves an array of all comments defined inside the given node.
* @param {ASTNode} node The AST node.
* @returns {ASTNode[]} An array of comment nodes.
*/
function getCommentsInNode(node) {
var allComments = context.getAllComments();

return allComments.filter(function(comment) {
return node.range[0] < comment.range[0] &&
node.range[1] > comment.range[1];
});
}

/**
* Checks if the location of a node or token is before the location of another node or token
* @param {ASTNode|Token} a The node or token to check if its location is before b.
@@ -50,8 +36,15 @@ module.exports = function(context) {
first = node.body[0],
firstLine = first.loc.start.line,
expectedFirstLine = blockStart + 2,
comments = getCommentsInNode(node),
firstComment = comments[0];
leadingComments = (node.body[0].leadingComments || []).slice(),
firstComment;

while (leadingComments.length > 0 &&
leadingComments[0].loc.start.line <= node.loc.start.line) {
leadingComments.shift();
}

firstComment = leadingComments[0];

if (firstComment && isLocatedBefore(firstComment, first)) {
firstLine = firstComment.loc.start.line;
@@ -71,8 +64,15 @@ module.exports = function(context) {
lastToken = context.getLastToken(last),
lastLine = lastToken.loc.end.line,
expectedLastLine = blockEnd - 2,
comments = getCommentsInNode(node),
lastComment = comments[comments.length - 1];
trailingComments = (node.body[node.body.length - 1].trailingComments || []).slice(),
lastComment;

while (trailingComments.length > 0 &&
trailingComments[trailingComments.length - 1].loc.end.line >= node.loc.end.line) {
trailingComments.pop();
}

lastComment = trailingComments[trailingComments.length - 1];

if (lastComment && isLocatedBefore(lastToken, lastComment)) {
lastLine = lastComment.loc.end.line;
@@ -30,6 +30,8 @@ ruleTester.run("padded-blocks", rule, {
{code: "{\n\na();\n//comment\n\n}" },
{code: "{\n\na()\n//comment\n\n}" },
{code: "{\n\na = 1\n\n}" },
{code: "{//comment\n\na();\n\n}" },
{code: "{\n\na();\n\n/* comment */ }" },
{code: "{\na();\n}", options: ["never"]},
{code: "{\na();}", options: ["never"]},
{code: "{a();\n}", options: ["never"]},

0 comments on commit fae1884

Please sign in to comment.
You can’t perform that action at this time.