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
24 changes: 18 additions & 6 deletions lib/rules/no-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const ERROR_MESSAGE_GET_PROPERTIES =
"Use `{ prop1: this.prop1, prop2: this.prop2, ... }` instead of Ember's `getProperties` function";

const VALID_JS_VARIABLE_NAME_REGEXP = new RegExp('^[a-zA-Z_$][0-9a-zA-Z_$]*$');
const VALID_JS_ARRAY_INDEX_REGEXP = new RegExp(/^\d+$/);
// No leading zeros: `01` would be an octal literal, so it needs bracket access (`['01']`).
const VALID_JS_ARRAY_INDEX_REGEXP = new RegExp(/^(?:0|[1-9]\d*)$/);
function isValidJSVariableName(str) {
return VALID_JS_VARIABLE_NAME_REGEXP.test(str);
}
Expand All @@ -23,6 +24,9 @@ function isValidJSPath(str) {
return str.split('.').every((part) => isValidJSVariableName(part) || isValidJSArrayIndex(part));
}

// `lastObject` as a whole path segment, not part of a name like `lastObjectId` or `x_lastObject`.
const LAST_OBJECT_SEGMENT_REGEXP = /(?<![\w$])lastObject(?![\w$])/g;

// Stand-in for a path segment that needs bracket access (e.g. `bar-baz`).
// It is a valid identifier, so the path rewriting below treats it like any other property name.
const BRACKET_SEGMENT_PLACEHOLDER = '__noGetBracketSegment';
Expand Down Expand Up @@ -120,7 +124,15 @@ function fixGet({
return null;
}

return fixer.replaceText(node, `${objectTextSafe}${replacementPath}`);
const replacementText = `${objectTextSafe}${replacementPath}`;

// Optional chaining is not allowed in the tag of a tagged template: (this.foo?.bar)`baz`
const isTemplateTag = types.isTaggedTemplateExpression(node.parent) && node.parent.tag === node;
if (isTemplateTag && replacementPath.includes('?.')) {
return fixer.replaceText(node, `(${replacementText})`);
}

return fixer.replaceText(node, replacementText);
}

function reportGetProperties({ context, node, objectText, properties }) {
Expand Down Expand Up @@ -528,7 +540,7 @@ function convertLiteralTypePath({
})
.join('.');

if (pathWithPlaceholders.match(/lastObject/g)?.length > 1 && !useAt) {
if (pathWithPlaceholders.match(LAST_OBJECT_SEGMENT_REGEXP)?.length > 1 && !useAt) {
// Do not autofix when multiple `lastObject` are chained, and use `at(-1)` is not allowed.
return null;
}
Expand All @@ -545,17 +557,17 @@ function convertLiteralTypePath({

// Replace any array element access using `firstObject` and `lastObject` (foo.firstObject => foo[0] or foo?.[0]).
replacementPath = replacementPath
.replaceAll('.firstObject', shouldIgnoreOptionalChaining ? '[0]' : '.[0]') // When `firstObject` is used in the middle of the path. e.g. foo.firstObject
.replaceAll(/\.firstObject(?![\w$])/g, shouldIgnoreOptionalChaining ? '[0]' : '.[0]') // When `firstObject` is used in the middle of the path. e.g. foo.firstObject
.replace(/^firstObject\??\./, shouldIgnoreOptionalChaining ? '[0].' : '[0]?.') // When `firstObject` is used at the beginning of the path. e.g. firstObject.bar
.replace(/^firstObject$/, '[0]'); // When `firstObject` is used as the entire path.

// eslint-disable-next-line unicorn/prefer-ternary
if (useAt) {
replacementPath = replacementPath.replaceAll('lastObject', 'at(-1)');
replacementPath = replacementPath.replaceAll(LAST_OBJECT_SEGMENT_REGEXP, 'at(-1)');
} else {
replacementPath = replacementPath
.replace(
/\??\.lastObject/, // When `lastObject` is used in the middle of the path. e.g. foo.lastObject
/\??\.lastObject(?![\w$])/, // When `lastObject` is used in the middle of the path. e.g. foo.lastObject
(_, offset) =>
`${shouldIgnoreOptionalChaining ? '' : '?.'}[${objectText}.${replacementPath.slice(
0,
Expand Down
42 changes: 42 additions & 0 deletions tests/lib/rules/no-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -997,6 +997,48 @@ ruleTester.run('no-get', rule, {
},
],
},
{
// `firstObject` / `lastObject` are only replaced as whole path segments.
code: "this.get('items.firstObjectId').x;",
output: 'this.items.firstObjectId.x;',
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: "this.get('items.lastObjectId').x;",
output: 'this.items.lastObjectId.x;',
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: "this.get('items.lastObjectId');",
output: 'this.items?.lastObjectId;',
options: [{ useOptionalChaining: true }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: "this.get('x_lastObject');",
output: 'this.x_lastObject;',
options: [{ useOptionalChaining: true }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: "this.get('lastObjectId.lastObject');",
output: 'this.lastObjectId?.[this.lastObjectId.length - 1];',
options: [{ useOptionalChaining: true, useAt: false }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
// Numeric segments with a leading zero are string keys, not octal literals.
code: "this.get('a.01').x;",
output: "this.a['01'].x;",
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
// Optional chaining is not allowed in the tag of a tagged template.
code: "this.get('a.b')`tpl`;",
output: '(this.a?.b)`tpl`;',
options: [{ useOptionalChaining: true }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
// Reports violation after (classic) proxy class.
code: `
Expand Down
Loading