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

Feature: Introduce new rule: newline-before-throw #4380

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ export const rules = {
"match-default-export-name": true,
"new-parens": true,
"newline-before-return": true,
"newline-before-throw": true,
"newline-per-chained-call": true,
"no-angle-bracket-type-assertion": true,
"no-boolean-literal-compare": true,
Expand Down
1 change: 1 addition & 0 deletions src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ export function readConfigurationFile(filepath: string): RawConfigFile {
}
} catch (e) {
const error = e as Error;

// include the configuration file being parsed in the error since it may differ from the directly referenced config
throw new Error(`${error.message} in ${filepath}`);
}
Expand Down
1 change: 1 addition & 0 deletions src/linter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ export class Linter {
const INVALID_SOURCE_ERROR = dedent`
Invalid source file: ${fileName}. Ensure that the files supplied to lint have a .ts, .tsx, .d.ts, .js or .jsx extension.
`;

throw new FatalError(INVALID_SOURCE_ERROR);
}
return sourceFile;
Expand Down
1 change: 1 addition & 0 deletions src/rules/memberOrderingRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ class MemberOrderingWalker extends Lint.AbstractWalker<Options> {
return name;
}
}

throw new Error("Expected to find a name");
}

Expand Down
86 changes: 86 additions & 0 deletions src/rules/newlineBeforeThrowRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/**
* @license
* Copyright 2018 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 { getPreviousStatement } 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: "newline-before-throw",
description: "Enforces blank line before throw when not the only line in the block.",
rationale: "Helps maintain a readable style in your codebase.",
optionsDescription: "Not configurable.",
options: {},
optionExamples: [true],
type: "style",
typescriptOnly: true,
};
/* tslint:enable:object-literal-sort-keys */

public static FAILURE_STRING = "Missing blank line before throw";

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(
new NewlineBeforeThrowWalker(sourceFile, this.ruleName, undefined),
);
}
}

class NewlineBeforeThrowWalker extends Lint.AbstractWalker<void> {
public walk(sourceFile: ts.SourceFile) {
const cb = (node: ts.Node): void => {
if (node.kind === ts.SyntaxKind.ThrowStatement) {
this.visitThrowStatement(node as ts.ThrowStatement);
}
return ts.forEachChild(node, cb);
};
return ts.forEachChild(sourceFile, cb);
}

private visitThrowStatement(node: ts.ThrowStatement) {
const prev = getPreviousStatement(node);
if (prev === undefined) {
// throw is not within a block (e.g. the only child of an IfStatement) or the first statement of the block
// no need to check for preceding newline
return;
}

let start = node.getStart(this.sourceFile);
let line = ts.getLineAndCharacterOfPosition(this.sourceFile, start).line;
const comments = ts.getLeadingCommentRanges(this.sourceFile.text, node.pos);
if (comments !== undefined) {
// check for blank lines between comments
for (let i = comments.length - 1; i >= 0; --i) {
const endLine = ts.getLineAndCharacterOfPosition(this.sourceFile, comments[i].end)
.line;
if (endLine < line - 1) {
return;
}
start = comments[i].pos;
line = ts.getLineAndCharacterOfPosition(this.sourceFile, start).line;
}
}
const prevLine = ts.getLineAndCharacterOfPosition(this.sourceFile, prev.end).line;

if (prevLine >= line - 1) {
// Previous statement is on the same or previous line
this.addFailure(start, start, Rule.FAILURE_STRING);
}
}
}
1 change: 1 addition & 0 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ export async function run(options: Options, logger: Logger): Promise<Status> {
logger.error(`${error.message}\n`);
return Status.FatalError;
}

throw error;
}
}
Expand Down
114 changes: 114 additions & 0 deletions test/rules/newline-before-throw/default/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
function foo(bar) {
if (!bar) {
throw new Error();
}
throw new Error();
~nil [0]
}

function foo(bar) {
if (!bar) {
var e = new Error();
throw e;
~nil [0]
}

throw bar;
}

function foo(bar) {
if (!bar) {
throw new Error();
}
/* multi-line
~nil [0]
comment */
throw new Error();
}

var fn = () => null;
function foo() {
fn();
throw new Error();
~nil [0]
}

function foo(fn) {
fn(); throw new Error();
~nil [0]
}

function foo() {
throw new Error();
}

function foo() {

throw new Error();
}

function foo(bar) {
if (!bar) throw new Error();
}

function foo(bar) {
let someCall;
if (!bar) throw new Error();
}

function foo(bar) {
if (!bar) { throw new Error() };
}

function foo(bar) {
if (!bar) {
throw new Error();
}
}

function foo(bar) {
if (!bar) {
throw new Error();
}

throw bar;
}

function foo(bar) {
if (!bar) {

throw new Error();
}
}

function foo() {

// comment
throw new Error();
}

function test() {
console.log("Any statement");
// Any comment

throw new Error();
}

function foo() {
fn();
// comment

// comment
throw new Error();
}

function bar() {
"some statement";
//comment
~nil [0]
//comment
//comment
throw new Error();
}

[0]: Missing blank line before throw
5 changes: 5 additions & 0 deletions test/rules/newline-before-throw/default/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"newline-before-throw": true
}
}
1 change: 1 addition & 0 deletions test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,6 @@ export function createTempFile(extension: string) {
return attempt;
}
}

throw new Error("Couldn't create temp file");
}