github-pages-deploy-action/node_modules/eslint/lib/rules/object-property-newline.js

100 lines
3.7 KiB
JavaScript
Raw Permalink Normal View History

2020-03-07 11:45:40 +08:00
/**
* @fileoverview Rule to enforce placing object properties on separate lines.
* @author Vitor Balocco
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "layout",
docs: {
description: "enforce placing object properties on separate lines",
category: "Stylistic Issues",
recommended: false,
url: "https://eslint.org/docs/rules/object-property-newline"
},
schema: [
{
type: "object",
properties: {
allowAllPropertiesOnSameLine: {
type: "boolean",
default: false
},
allowMultiplePropertiesPerLine: { // Deprecated
type: "boolean",
default: false
}
},
additionalProperties: false
}
],
2020-05-15 05:33:08 +08:00
fixable: "whitespace",
messages: {
propertiesOnNewlineAll: "Object properties must go on a new line if they aren't all on the same line.",
propertiesOnNewline: "Object properties must go on a new line."
}
2020-03-07 11:45:40 +08:00
},
create(context) {
const allowSameLine = context.options[0] && (
(context.options[0].allowAllPropertiesOnSameLine || context.options[0].allowMultiplePropertiesPerLine /* Deprecated */)
);
2020-05-15 05:33:08 +08:00
const messageId = allowSameLine
? "propertiesOnNewlineAll"
: "propertiesOnNewline";
2020-03-07 11:45:40 +08:00
const sourceCode = context.getSourceCode();
return {
ObjectExpression(node) {
if (allowSameLine) {
if (node.properties.length > 1) {
const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]);
const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]);
if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) {
// All keys and values are on the same line
return;
}
}
}
for (let i = 1; i < node.properties.length; i++) {
const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.properties[i - 1]);
const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.properties[i]);
if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) {
context.report({
node,
2020-06-27 02:01:06 +08:00
loc: firstTokenOfCurrentProperty.loc,
2020-05-15 05:33:08 +08:00
messageId,
2020-03-07 11:45:40 +08:00
fix(fixer) {
const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty);
const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]];
// Don't perform a fix if there are any comments between the comma and the next property.
if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) {
return null;
}
return fixer.replaceTextRange(rangeAfterComma, "\n");
}
});
}
}
}
};
}
};