Skip to content

Commit 1a7603d

Browse files
carlosjeurissenfisker
authored andcommitted
Add whatwgEncoding option to text-encoding-identifier-case
1 parent 43bc429 commit 1a7603d

File tree

5 files changed

+630
-6
lines changed

5 files changed

+630
-6
lines changed

docs/rules/text-encoding-identifier-case.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,15 @@ const string = buffer.toString('utf-8');
3737
//
3838
const string = buffer.toString('utf8');
3939
```
40+
41+
## Options
42+
43+
### withDash
44+
45+
Type: `boolean`\
46+
Default: `false`
47+
48+
- `false` (default)
49+
- Prefer `utf8` without a dash (Node.js style)
50+
- `true`
51+
- Prefer `utf-8` with a dash (WHATWG standard, required for HTML)

rules/text-encoding-identifier-case.js

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@ const messages = {
88
[MESSAGE_ID_SUGGESTION]: 'Replace `{{value}}` with `{{replacement}}`.',
99
};
1010

11-
const getReplacement = encoding => {
11+
const getReplacement = (encoding, withDash) => {
1212
switch (encoding.toLowerCase()) {
1313
// eslint-disable-next-line unicorn/text-encoding-identifier-case
1414
case 'utf-8':
1515
case 'utf8': {
16-
return 'utf8';
16+
// eslint-disable-next-line unicorn/text-encoding-identifier-case
17+
return withDash ? 'utf-8' : 'utf8';
1718
}
1819

1920
case 'ascii': {
@@ -34,8 +35,12 @@ const isFsReadFileEncoding = node =>
3435
&& node.parent.arguments[0].type !== 'SpreadElement';
3536

3637
/** @param {import('eslint').Rule.RuleContext} context */
37-
const create = () => ({
38-
Literal(node) {
38+
const create = context => {
39+
const {
40+
withDash,
41+
} = context.options[0];
42+
43+
context.on('Literal', node => {
3944
if (typeof node.value !== 'string') {
4045
return;
4146
}
@@ -58,7 +63,7 @@ const create = () => ({
5863
const {raw} = node;
5964
const value = raw.slice(1, -1);
6065

61-
const replacement = getReplacement(value);
66+
const replacement = getReplacement(value, withDash);
6267
if (!replacement || replacement === value) {
6368
return;
6469
}
@@ -88,8 +93,20 @@ const create = () => ({
8893
];
8994

9095
return problem;
96+
});
97+
};
98+
99+
const schema = [
100+
{
101+
type: 'object',
102+
additionalProperties: false,
103+
properties: {
104+
withDash: {
105+
type: 'boolean',
106+
},
107+
},
91108
},
92-
});
109+
];
93110

94111
/** @type {import('eslint').Rule.RuleModule} */
95112
const config = {
@@ -102,6 +119,10 @@ const config = {
102119
},
103120
fixable: 'code',
104121
hasSuggestions: true,
122+
schema,
123+
defaultOptions: [{
124+
withDash: false,
125+
}],
105126
messages,
106127
},
107128
};

0 commit comments

Comments
 (0)