|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
-
-
- "use strict";
-
-
-
-
-
- const astUtils = require("../util/ast-utils");
-
-
-
-
-
- module.exports = {
- meta: {
- type: "layout",
-
- docs: {
- description: "enforce spacing around colons of switch statements",
- category: "Stylistic Issues",
- recommended: false,
- url: "https://eslint.org/docs/rules/switch-colon-spacing"
- },
-
- schema: [
- {
- type: "object",
- properties: {
- before: { type: "boolean" },
- after: { type: "boolean" }
- },
- additionalProperties: false
- }
- ],
-
- fixable: "whitespace"
- },
-
- create(context) {
- const sourceCode = context.getSourceCode();
- const options = context.options[0] || {};
- const beforeSpacing = options.before === true;
- const afterSpacing = options.after !== false;
-
-
-
- function getColonToken(node) {
- if (node.test) {
- return sourceCode.getTokenAfter(node.test, astUtils.isColonToken);
- }
- return sourceCode.getFirstToken(node, 1);
- }
-
-
-
- function isValidSpacing(left, right, expected) {
- return (
- astUtils.isClosingBraceToken(right) ||
- !astUtils.isTokenOnSameLine(left, right) ||
- sourceCode.isSpaceBetweenTokens(left, right) === expected
- );
- }
-
-
-
- function commentsExistBetween(left, right) {
- return sourceCode.getFirstTokenBetween(
- left,
- right,
- {
- includeComments: true,
- filter: astUtils.isCommentToken
- }
- ) !== null;
- }
-
-
-
- function fix(fixer, left, right, spacing) {
- if (commentsExistBetween(left, right)) {
- return null;
- }
- if (spacing) {
- return fixer.insertTextAfter(left, " ");
- }
- return fixer.removeRange([left.range[1], right.range[0]]);
- }
-
- return {
- SwitchCase(node) {
- const colonToken = getColonToken(node);
- const beforeToken = sourceCode.getTokenBefore(colonToken);
- const afterToken = sourceCode.getTokenAfter(colonToken);
-
- if (!isValidSpacing(beforeToken, colonToken, beforeSpacing)) {
- context.report({
- node,
- loc: colonToken.loc,
- message: "{{verb}} space(s) before this colon.",
- data: { verb: beforeSpacing ? "Expected" : "Unexpected" },
- fix: fixer => fix(fixer, beforeToken, colonToken, beforeSpacing)
- });
- }
- if (!isValidSpacing(colonToken, afterToken, afterSpacing)) {
- context.report({
- node,
- loc: colonToken.loc,
- message: "{{verb}} space(s) after this colon.",
- data: { verb: afterSpacing ? "Expected" : "Unexpected" },
- fix: fixer => fix(fixer, colonToken, afterToken, afterSpacing)
- });
- }
- }
- };
- }
- };
|