UNPKG

2.41 kBJavaScriptView Raw
1// @ts-nocheck
2
3'use strict';
4
5const blockString = require('../../utils/blockString');
6const nextNonCommentNode = require('../../utils/nextNonCommentNode');
7const rawNodeString = require('../../utils/rawNodeString');
8const report = require('../../utils/report');
9const ruleMessages = require('../../utils/ruleMessages');
10const validateOptions = require('../../utils/validateOptions');
11const whitespaceChecker = require('../../utils/whitespaceChecker');
12
13const ruleName = 'declaration-block-semicolon-newline-after';
14
15const messages = ruleMessages(ruleName, {
16 expectedAfter: () => 'Expected newline after ";"',
17 expectedAfterMultiLine: () => 'Expected newline after ";" in a multi-line declaration block',
18 rejectedAfterMultiLine: () => 'Unexpected newline after ";" in a multi-line declaration block',
19});
20
21function rule(expectation, options, context) {
22 const checker = whitespaceChecker('newline', expectation, messages);
23
24 return (root, result) => {
25 const validOptions = validateOptions(result, ruleName, {
26 actual: expectation,
27 possible: ['always', 'always-multi-line', 'never-multi-line'],
28 });
29
30 if (!validOptions) {
31 return;
32 }
33
34 root.walkDecls((decl) => {
35 // Ignore last declaration if there's no trailing semicolon
36 const parentRule = decl.parent;
37
38 if (!parentRule.raws.semicolon && parentRule.last === decl) {
39 return;
40 }
41
42 const nextNode = decl.next();
43
44 if (!nextNode) {
45 return;
46 }
47
48 // Allow end-of-line comment
49 const nodeToCheck = nextNonCommentNode(nextNode);
50
51 if (!nodeToCheck) {
52 return;
53 }
54
55 checker.afterOneOnly({
56 source: rawNodeString(nodeToCheck),
57 index: -1,
58 lineCheckStr: blockString(parentRule),
59 err: (m) => {
60 if (context.fix) {
61 if (expectation.startsWith('always')) {
62 const index = nodeToCheck.raws.before.search(/\r?\n/);
63
64 if (index >= 0) {
65 nodeToCheck.raws.before = nodeToCheck.raws.before.slice(index);
66 } else {
67 nodeToCheck.raws.before = context.newline + nodeToCheck.raws.before;
68 }
69
70 return;
71 }
72
73 if (expectation === 'never-multi-line') {
74 nodeToCheck.raws.before = '';
75
76 return;
77 }
78 }
79
80 report({
81 message: m,
82 node: decl,
83 index: decl.toString().length + 1,
84 result,
85 ruleName,
86 });
87 },
88 });
89 });
90 };
91}
92
93rule.ruleName = ruleName;
94rule.messages = messages;
95module.exports = rule;