UNPKG

2.38 kBJavaScriptView Raw
1// @ts-nocheck
2
3'use strict';
4
5const beforeBlockString = require('../../utils/beforeBlockString');
6const blockString = require('../../utils/blockString');
7const hasBlock = require('../../utils/hasBlock');
8const hasEmptyBlock = require('../../utils/hasEmptyBlock');
9const report = require('../../utils/report');
10const ruleMessages = require('../../utils/ruleMessages');
11const validateOptions = require('../../utils/validateOptions');
12const whitespaceChecker = require('../../utils/whitespaceChecker');
13
14const ruleName = 'block-opening-brace-space-after';
15
16const messages = ruleMessages(ruleName, {
17 expectedAfter: () => 'Expected single space after "{"',
18 rejectedAfter: () => 'Unexpected whitespace after "{"',
19 expectedAfterSingleLine: () => 'Expected single space after "{" of a single-line block',
20 rejectedAfterSingleLine: () => 'Unexpected whitespace after "{" of a single-line block',
21 expectedAfterMultiLine: () => 'Expected single space after "{" of a multi-line block',
22 rejectedAfterMultiLine: () => 'Unexpected whitespace after "{" of a multi-line block',
23});
24
25function rule(expectation, options, context) {
26 const checker = whitespaceChecker('space', expectation, messages);
27
28 return (root, result) => {
29 const validOptions = validateOptions(result, ruleName, {
30 actual: expectation,
31 possible: [
32 'always',
33 'never',
34 'always-single-line',
35 'never-single-line',
36 'always-multi-line',
37 'never-multi-line',
38 ],
39 });
40
41 if (!validOptions) {
42 return;
43 }
44
45 // Check both kinds of statements: rules and at-rules
46 root.walkRules(check);
47 root.walkAtRules(check);
48
49 function check(statement) {
50 // Return early if blockless or has an empty block
51 if (!hasBlock(statement) || hasEmptyBlock(statement)) {
52 return;
53 }
54
55 checker.after({
56 source: blockString(statement),
57 index: 0,
58 err: (m) => {
59 if (context.fix) {
60 if (expectation.startsWith('always')) {
61 statement.first.raws.before = ' ';
62
63 return;
64 }
65
66 if (expectation.startsWith('never')) {
67 statement.first.raws.before = '';
68
69 return;
70 }
71 }
72
73 report({
74 message: m,
75 node: statement,
76 index: beforeBlockString(statement, { noRawBefore: true }).length + 1,
77 result,
78 ruleName,
79 });
80 },
81 });
82 }
83 };
84}
85
86rule.ruleName = ruleName;
87rule.messages = messages;
88module.exports = rule;