/
rule-notices.ts
363 lines (327 loc) · 11.3 KB
/
rule-notices.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import { END_RULE_HEADER_MARKER } from './markers.js';
import {
EMOJI_DEPRECATED,
EMOJI_FIXABLE,
EMOJI_HAS_SUGGESTIONS,
EMOJI_CONFIG,
EMOJI_REQUIRES_TYPE_CHECKING,
} from './emojis.js';
import { getConfigsForRule } from './configs.js';
import type {
RuleModule,
Plugin,
ConfigsToRules,
ConfigEmojis,
} from './types.js';
import { RULE_TYPE, RULE_TYPE_MESSAGES_NOTICES } from './rule-type.js';
import {
RuleDocTitleFormat,
RULE_DOC_TITLE_FORMAT_DEFAULT,
} from './rule-doc-title-format.js';
import { NOTICE_TYPE, SEVERITY_ERROR, SEVERITY_OFF } from './types.js';
export const NOTICE_TYPE_DEFAULT_PRESENCE_AND_ORDERING: {
[key in NOTICE_TYPE]: boolean;
} = {
// Object keys ordered in display order.
// Object values indicate whether the column is displayed by default.
[NOTICE_TYPE.DEPRECATED]: true, // Most important.
[NOTICE_TYPE.CONFIGS]: true,
[NOTICE_TYPE.FIXABLE]: true,
[NOTICE_TYPE.FIXABLE_AND_HAS_SUGGESTIONS]: true, // Potentially replaces FIXABLE and HAS_SUGGESTIONS.
[NOTICE_TYPE.HAS_SUGGESTIONS]: true,
[NOTICE_TYPE.REQUIRES_TYPE_CHECKING]: true,
[NOTICE_TYPE.TYPE]: false,
};
/**
* An object containing the text for each notice type (as a string or function to generate the string).
*/
const RULE_NOTICES: {
[key in NOTICE_TYPE]:
| string
| undefined
| ((data: {
configsEnabled: string[];
configsDisabled: string[];
configEmojis: ConfigEmojis;
urlConfigs?: string;
replacedBy: readonly string[] | undefined;
type?: RULE_TYPE;
}) => string);
} = {
// Configs notice varies based on whether the rule is enabled in one or more configs.
[NOTICE_TYPE.CONFIGS]: ({
configsEnabled,
configsDisabled,
configEmojis,
urlConfigs,
}) => {
// Add link to configs documentation if provided.
const configsLinkOrWord = urlConfigs
? `[configs](${urlConfigs})`
: 'configs';
const configLinkOrWord = urlConfigs ? `[config](${urlConfigs})` : 'config';
/* istanbul ignore next -- this shouldn't happen */
if (
(!configsEnabled || configsEnabled.length === 0) &&
(!configsDisabled || configsDisabled.length === 0)
) {
throw new Error(
'Should not be trying to display config notice for rule not enabled/disabled in any configs.'
);
}
let emoji = '';
if (configsEnabled.length + configsDisabled.length > 1) {
emoji = EMOJI_CONFIG;
} else if (configsEnabled.length > 0) {
emoji =
configEmojis.find(
(configEmoji) => configEmoji.config === configsEnabled[0]
)?.emoji ?? EMOJI_CONFIG;
} else if (configsDisabled.length > 0) {
emoji =
configEmojis.find(
(configEmoji) => configEmoji.config === configsDisabled[0]
)?.emoji ?? EMOJI_CONFIG;
}
const configsEnabledCSV = configsEnabled
.map((configEnabled) => {
const emoji = configEmojis.find(
(configEmoji) => configEmoji.config === configEnabled
)?.emoji;
return `${emoji ? `${emoji} ` : ''}\`${configEnabled}\``;
})
.join(', ');
const configsDisabledCSV = configsDisabled
.map((configDisabled) => {
const emoji = configEmojis.find(
(configEmoji) => configEmoji.config === configDisabled
)?.emoji;
return `${emoji ? `${emoji} ` : ''}\`${configDisabled}\``;
})
.join(', ');
const SENTENCE_ENABLED =
configsEnabled.length > 1
? `This rule is enabled in the following ${configsLinkOrWord}: ${configsEnabledCSV}.`
: configsEnabled.length === 1
? `This rule is enabled in the \`${configsEnabled?.[0]}\` ${configLinkOrWord}.`
: '';
const SENTENCE_DISABLED =
configsDisabled.length > 1
? `This rule is disabled in the following ${configsLinkOrWord}: ${configsDisabledCSV}.`
: configsDisabled.length === 1
? `This rule is disabled in the \`${configsDisabled?.[0]}\` ${configLinkOrWord}.`
: '';
return `${emoji} ${SENTENCE_ENABLED}${
SENTENCE_ENABLED && SENTENCE_DISABLED ? ' ' : '' // Space if two sentences.
}${SENTENCE_DISABLED}`;
},
// Deprecated notice has optional "replaced by" rules list.
[NOTICE_TYPE.DEPRECATED]: ({ replacedBy }) =>
`${EMOJI_DEPRECATED} This rule is deprecated.${
replacedBy && replacedBy.length > 0
? ` It was replaced by ${ruleNamesToList(replacedBy)}.`
: ''
}`,
[NOTICE_TYPE.TYPE]: ({ type }) => {
/* istanbul ignore next -- this shouldn't happen */
if (!type) {
throw new Error(
'Should not be trying to display type notice for rule with no type.'
);
}
return RULE_TYPE_MESSAGES_NOTICES[type];
},
// Simple strings.
[NOTICE_TYPE.FIXABLE]: `${EMOJI_FIXABLE} This rule is automatically fixable by the [\`--fix\` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix).`,
[NOTICE_TYPE.FIXABLE_AND_HAS_SUGGESTIONS]: `${EMOJI_FIXABLE}${EMOJI_HAS_SUGGESTIONS} This rule is automatically fixable by the [\`--fix\` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix) and manually fixable by [editor suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).`,
[NOTICE_TYPE.HAS_SUGGESTIONS]: `${EMOJI_HAS_SUGGESTIONS} This rule is manually fixable by [editor suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).`,
[NOTICE_TYPE.REQUIRES_TYPE_CHECKING]: `${EMOJI_REQUIRES_TYPE_CHECKING} This rule requires type information.`,
};
/**
* Convert list of rule names to string list of links.
*/
function ruleNamesToList(ruleNames: readonly string[]) {
return ruleNames
.map((ruleName) => `[\`${ruleName}\`](${ruleName}.md)`)
.join(', ');
}
/**
* Determine which notices should and should not be included at the top of a rule doc.
*/
function getNoticesForRule(
rule: RuleModule,
configsEnabled: string[],
configsDisabled: string[],
ruleDocNotices: NOTICE_TYPE[]
) {
const notices: {
[key in NOTICE_TYPE]: boolean;
} = {
// Alphabetical order.
[NOTICE_TYPE.CONFIGS]:
configsEnabled.length > 0 || configsDisabled.length > 0,
[NOTICE_TYPE.DEPRECATED]: rule.meta.deprecated || false,
// FIXABLE_AND_HAS_SUGGESTIONS potentially replaces FIXABLE and HAS_SUGGESTIONS.
[NOTICE_TYPE.FIXABLE]:
Boolean(rule.meta.fixable) &&
(!rule.meta.hasSuggestions ||
!ruleDocNotices.includes(NOTICE_TYPE.FIXABLE_AND_HAS_SUGGESTIONS)),
[NOTICE_TYPE.FIXABLE_AND_HAS_SUGGESTIONS]:
Boolean(rule.meta.fixable) && Boolean(rule.meta.hasSuggestions),
[NOTICE_TYPE.HAS_SUGGESTIONS]:
Boolean(rule.meta.hasSuggestions) &&
(!rule.meta.fixable ||
!ruleDocNotices.includes(NOTICE_TYPE.FIXABLE_AND_HAS_SUGGESTIONS)),
[NOTICE_TYPE.REQUIRES_TYPE_CHECKING]:
rule.meta.docs?.requiresTypeChecking || false,
[NOTICE_TYPE.TYPE]: Boolean(rule.meta.type),
};
// Recreate object using the ordering and presence of columns specified in ruleDocNotices.
return Object.fromEntries(
ruleDocNotices.map((type) => [type, notices[type]])
) as Record<NOTICE_TYPE, boolean>;
}
/**
* Get the lines for the notice section at the top of a rule doc.
*/
function getRuleNoticeLines(
ruleName: string,
plugin: Plugin,
configsToRules: ConfigsToRules,
pluginPrefix: string,
configEmojis: ConfigEmojis,
ignoreConfig: string[],
ruleDocNotices: NOTICE_TYPE[],
urlConfigs?: string
) {
const lines: string[] = [];
const rule = plugin.rules?.[ruleName];
/* istanbul ignore next */
if (!rule) {
// This is only to please TypeScript. We should always have a rule when this function is called.
throw new Error('Rule not found');
}
if (typeof rule !== 'object') {
// We don't support the deprecated, function-style rule format as there's not much information we can extract from it.
// https://eslint.org/docs/latest/developer-guide/working-with-rules-deprecated
return [];
}
const configsEnabled = getConfigsForRule(
ruleName,
configsToRules,
pluginPrefix,
SEVERITY_ERROR
).filter((configName) => !ignoreConfig?.includes(configName));
const configsDisabled = getConfigsForRule(
ruleName,
configsToRules,
pluginPrefix,
SEVERITY_OFF
).filter((configName) => !ignoreConfig?.includes(configName));
const notices = getNoticesForRule(
rule,
configsEnabled,
configsDisabled,
ruleDocNotices
);
let noticeType: keyof typeof notices;
for (noticeType in notices) {
const expected = notices[noticeType];
if (!expected) {
// This notice should not be included.
continue;
}
lines.push(''); // Blank line first.
const ruleNoticeStrOrFn = RULE_NOTICES[noticeType];
/* istanbul ignore next -- this won't happen since we would have already bailed out earlier. */
if (!ruleNoticeStrOrFn) {
// No notice for this column.
continue;
}
lines.push(
typeof ruleNoticeStrOrFn === 'function'
? ruleNoticeStrOrFn({
configsEnabled,
configsDisabled,
configEmojis,
urlConfigs,
replacedBy: rule.meta.replacedBy,
type: rule.meta.type as RULE_TYPE, // Convert union type to enum.
})
: ruleNoticeStrOrFn
);
}
return lines;
}
function toSentenceCase(str: string) {
return str.replace(/^\w/, function (txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1).toLowerCase();
});
}
function removeTrailingPeriod(str: string) {
return str.replace(/\.$/, '');
}
function makeTitle(
name: string,
description: string | undefined,
pluginPrefix: string,
ruleDocTitleFormat?: RuleDocTitleFormat
) {
const descriptionFormatted = description
? removeTrailingPeriod(toSentenceCase(description))
: undefined;
let ruleDocTitleFormatWithFallback: RuleDocTitleFormat =
ruleDocTitleFormat ?? RULE_DOC_TITLE_FORMAT_DEFAULT;
if (ruleDocTitleFormatWithFallback.includes('desc') && !description) {
ruleDocTitleFormatWithFallback = 'prefix-name'; // Fallback if rule missing description.
}
switch (ruleDocTitleFormatWithFallback) {
case 'desc':
return `# ${descriptionFormatted}`;
case 'desc-parens-name':
return `# ${descriptionFormatted} (\`${name}\`)`;
case 'desc-parens-prefix-name':
return `# ${descriptionFormatted} (\`${pluginPrefix}/${name}\`)`;
case 'name':
return `# \`${name}\``;
case 'prefix-name':
return `# \`${pluginPrefix}/${name}\``;
/* istanbul ignore next -- this shouldn't happen */
default:
throw new Error(
`Unhandled rule doc title format: ${ruleDocTitleFormatWithFallback}`
);
}
}
/**
* Generate a rule doc header for a particular rule.
* @returns {string} - new header including marker
*/
export function generateRuleHeaderLines(
description: string | undefined,
name: string,
plugin: Plugin,
configsToRules: ConfigsToRules,
pluginPrefix: string,
configEmojis: ConfigEmojis,
ignoreConfig: string[],
ruleDocNotices: NOTICE_TYPE[],
ruleDocTitleFormat?: RuleDocTitleFormat,
urlConfigs?: string
): string {
return [
makeTitle(name, description, pluginPrefix, ruleDocTitleFormat),
...getRuleNoticeLines(
name,
plugin,
configsToRules,
pluginPrefix,
configEmojis,
ignoreConfig,
ruleDocNotices,
urlConfigs
),
'',
END_RULE_HEADER_MARKER,
].join('\n');
}