Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ESLint I18n Rule] Cleanup #181959

Merged
merged 1 commit into from
Apr 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,25 +78,35 @@ export const I18nTranslateShouldStartWithTheRightId: Rule.RuleModule = {
}

if (identifier && !identifier.startsWith(`${i18nAppId}.`)) {
const oldI18nIdentifierArray = identifier.split('.');
const i18nIdentifierRange = node.arguments[0].range;

const newI18nIdentifier =
const oldI18nIdentifierArray = identifier.split('.');
const correctI18nIdentifier =
oldI18nIdentifierArray[0] === 'xpack'
? `${i18nAppId}.${oldI18nIdentifierArray.slice(2).join('.')}`
: `${i18nAppId}.${oldI18nIdentifierArray.slice(1).join('.')}`;

const opts = node.arguments[1]
? sourceCode.getText().slice(node.arguments[1].range[0], node.arguments[1].range[1])
: "{ defaultMessage: '' }";
const hasExistingOpts = node.arguments.length > 1;

report({
node: node as any,
message: RULE_WARNING_MESSAGE,
fix(fixer) {
return fixer.replaceTextRange(
node.range,
`i18n.translate('${newI18nIdentifier}', ${opts})`
);
return [
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 main changes:

1: Added the additional fixer which adds an import { i18n } from '@kbn/i18n' line to the imports if it wasn't there before.
2: In the previous approach we targeted the whole i18n.translate() node and reconstructed it by using the correct first parameter and getting the existing options object (if any) from the source code. Now we are a bit smarter still: we don't target the full node, we target the node of the first parameter, we just update that with the correct identifier and keep the rest of the code intact.

hasExistingOpts
? // if there are existing options, only replace the i18n identifier and keep the options
fixer.replaceTextRange(i18nIdentifierRange, `\'${correctI18nIdentifier}\'`)
: // if there are no existing options, add an options object with an empty default message
fixer.replaceTextRange(
i18nIdentifierRange,
`\'${correctI18nIdentifier}\', { defaultMessage: '' }`
),
!hasI18nImportLine && rangeToAddI18nImportLine
? replaceMode === 'replace'
? fixer.replaceTextRange(rangeToAddI18nImportLine, i18nImportLine)
: fixer.insertTextAfterRange(rangeToAddI18nImportLine, `\n${i18nImportLine}`)
: null,
].filter(isTruthy);
},
});
}
Expand Down