Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/rules/text-encoding-identifier-case.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,26 @@ const string = buffer.toString('utf-8');
// ✅
const string = buffer.toString('utf8');
```

## Options

Type: `object`

### withDash

Type: `boolean`\
Default: `false`

Use WHATWG standard encoding notation with dashes (e.g., ⁠`utf-8` instead of `⁠utf8`).

```js
// ❌
/* eslint unicorn/text-encoding-identifier-case: ["error", {"withDash": true}] */
await fs.readFile(file, 'utf8');
```

```js
// ✅
/* eslint unicorn/text-encoding-identifier-case: ["error", {"withDash": true}] */
await fs.readFile(file, 'utf-8');
```
33 changes: 27 additions & 6 deletions rules/text-encoding-identifier-case.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ const messages = {
[MESSAGE_ID_SUGGESTION]: 'Replace `{{value}}` with `{{replacement}}`.',
};

const getReplacement = encoding => {
const getReplacement = (encoding, withDash) => {
switch (encoding.toLowerCase()) {
// eslint-disable-next-line unicorn/text-encoding-identifier-case
case 'utf-8':
case 'utf8': {
return 'utf8';
// eslint-disable-next-line unicorn/text-encoding-identifier-case
return withDash ? 'utf-8' : 'utf8';
}

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

/** @param {import('eslint').Rule.RuleContext} context */
const create = () => ({
Literal(node) {
const create = context => {
const {
withDash,
} = context.options[0];

context.on('Literal', node => {
if (typeof node.value !== 'string') {
return;
}
Expand All @@ -58,7 +63,7 @@ const create = () => ({
const {raw} = node;
const value = raw.slice(1, -1);

const replacement = getReplacement(value);
const replacement = getReplacement(value, withDash);
if (!replacement || replacement === value) {
return;
}
Expand Down Expand Up @@ -88,8 +93,20 @@ const create = () => ({
];

return problem;
});
};

const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
withDash: {
type: 'boolean',
},
},
},
});
];

/** @type {import('eslint').Rule.RuleModule} */
const config = {
Expand All @@ -102,6 +119,10 @@ const config = {
},
fixable: 'code',
hasSuggestions: true,
schema,
defaultOptions: [{
withDash: false,
}],
messages,
},
};
Expand Down
Loading
Loading