Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

New rule prefer-object-spread #2624

Merged
merged 4 commits into from
May 17, 2017
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
1 change: 1 addition & 0 deletions src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ export const rules = {
}],
"prefer-function-over-method": true,
"prefer-method-signature": true,
"prefer-object-spread": true,
"prefer-switch": true,
"prefer-template": true,
"quotemark": [true, "double", "avoid-escape"],
Expand Down
3 changes: 3 additions & 0 deletions src/configs/latest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ export const rules = {

// added in v5.2
"no-object-literal-type-assertion": true,

// added in v5.3
"prefer-object-spread": true,
};
// tslint:enable object-literal-sort-keys

Expand Down
2 changes: 1 addition & 1 deletion src/language/rule/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export class Replacement {

public static applyAll(content: string, replacements: Replacement[]) {
// sort in reverse so that diffs are properly applied
replacements.sort((a, b) => b.end - a.end);
replacements.sort((a, b) => b.end - a.end || b.start - a.start);
Copy link
Contributor

Choose a reason for hiding this comment

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

we shouldn't even be applying overlapping fixes

return replacements.reduce((text, r) => r.apply(text), content);
}

Expand Down
115 changes: 115 additions & 0 deletions src/rules/preferObjectSpreadRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {
isBinaryExpression, isCallExpression, isIdentifier, isObjectLiteralExpression,
isPropertyAccessExpression, isSpreadElement,
} from "tsutils";
import * as ts from "typescript";

import * as Lint from "../index";
export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "prefer-object-spread",
description: "Enforces the use of the ES2015 object spread operator over `Object.assign()` where appropriate.",
rationale: "Object spread allows for better type checking and inference.",
optionsDescription: "Not configurable.",
options: null,
optionExamples: [true],
type: "functionality",
typescriptOnly: false,
hasFix: true,
};
/* tslint:enable:object-literal-sort-keys */

public static FAILURE_STRING = "Use the object spread operator instead.";
public static ASSIGNMENT_FAILURE_STRING = "'Object.assign' returns the first argument. Prefer object spread if you want a new object.";

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}

function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (isCallExpression(node) && node.arguments.length !== 0 &&
isPropertyAccessExpression(node.expression) && node.expression.name.text === "assign" &&
isIdentifier(node.expression.expression) && node.expression.expression.text === "Object" &&
// Object.assign(...someArray) cannot be written as object spread
!node.arguments.some(isSpreadElement)) {
if (node.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING, createFix(node, ctx.sourceFile));
} else {
const parent = node.parent!;
if (parent.kind === ts.SyntaxKind.VariableDeclaration ||
isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
ctx.addFailureAtNode(node, Rule.ASSIGNMENT_FAILURE_STRING, createFix(node, ctx.sourceFile));
}
}
}
return ts.forEachChild(node, cb);
});
}

function createFix(node: ts.CallExpression, sourceFile: ts.SourceFile): Lint.Fix {
const args = node.arguments;
const fix = [
Lint.Replacement.replaceFromTo(node.getStart(sourceFile), args[0].getStart(sourceFile), "{"),
new Lint.Replacement(node.end - 1, 1, "}"),
];
for (let i = 0; i < args.length; ++i) {
const arg = args[i];
if (isObjectLiteralExpression(arg)) {
if (arg.properties.length === 0) {
let end = arg.end;
if (i !== args.length - 1) {
end = args[i + 1].getStart(sourceFile);
} else if (args.hasTrailingComma) {
end = args.end;
}
// remove empty object iteral and the following comma if exists
fix.push(Lint.Replacement.deleteFromTo(arg.getStart(sourceFile), end));
} else {
fix.push(
// remove open brace
Lint.Replacement.deleteText(arg.getStart(sourceFile), 1),
// remove trailing comma if exists and close brace
Lint.Replacement.deleteFromTo(arg.properties[arg.properties.length - 1].end, arg.end),
);
}
} else {
const parens = needsParens(arg);
fix.push(Lint.Replacement.appendText(arg.getStart(sourceFile), parens ? "...(" : "..."));
if (parens) {
fix.push(Lint.Replacement.appendText(arg.end, ")"));
}
}
}

return fix;
}

function needsParens(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.ConditionalExpression:
case ts.SyntaxKind.BinaryExpression:
return true;
default:
return false;
}
}
14 changes: 14 additions & 0 deletions test/rules/prefer-object-spread/test.ts.fix
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const original = {a: 1, b:2};
{...original, c: 3};
{a: 1, b: 2, c: 3};
Object.assign({a:1}, ...[{b: 2}, {c: 3}])
Object.assign(original, {c: 3});
var result = {...original, c: 3};
result = {...original, c: 3};
var result = {...original, c: 3};

{a: 1,};
{a: 1, ...(foo ? {b: 2} : {c: 3})};
{a: 1, ...{b: 2}};
{};
{};
27 changes: 27 additions & 0 deletions test/rules/prefer-object-spread/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const original = {a: 1, b:2};
Object.assign({}, original, {c: 3});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
Object.assign({a: 1, b: 2}, {c: 3});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
Object.assign({a:1}, ...[{b: 2}, {c: 3}])
Object.assign(original, {c: 3});
var result = Object.assign(original, {c: 3});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [1]
result = Object.assign(original, {c: 3});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [1]
var result = Object.assign({}, original, {c: 3});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]

Object.assign({}, {}, {a: 1,},);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
Object.assign({a: 1}, foo ? {b: 2} : {c: 3});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
Object.assign({a: 1, ...{b: 2}});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
Object.assign({}, {});
~~~~~~~~~~~~~~~~~~~~~ [0]
Object.assign({}, {},);
~~~~~~~~~~~~~~~~~~~~~~ [0]

[0]: Use the object spread operator instead.
[1]: 'Object.assign' returns the first argument. Prefer object spread if you want a new object.
5 changes: 5 additions & 0 deletions test/rules/prefer-object-spread/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"prefer-object-spread": true
}
}
3 changes: 1 addition & 2 deletions tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@

"ban": [true,
["describe", "only"],
["it", "only"],
["Object", "assign"]
["it", "only"]
],

"interface-name": false,
Expand Down