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

(feature): FixFormatter: new formatter for printing fixed files #2149

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions src/formatters/fixFormatter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* @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 * as fs from "fs";
import {AbstractFormatter} from "../language/formatter/abstractFormatter";
import {IFormatterMetadata} from "../language/formatter/formatter";
import {dedent} from "../utils";
import {Fix, RuleFailure} from "./../language/rule/rule";

export class Formatter extends AbstractFormatter {
/* tslint:disable:object-literal-sort-keys */
public static metadata: IFormatterMetadata = {
formatterName: "fix",
description: "Formats the file passed in returns the formatted source",
sample: dedent`
export class FormattedClass {
public someMethod() {
return "This class has been formatted";
}
}`,
consumer: "machine",
};
/* tslint:enable:object-literal-sort-keys */

public format(failures: RuleFailure[]): string {
this.ensureExactlyOneFileInFailuresList(failures);

const fileName = failures[0].getFileName();
const fixes = failures.map((f) => f.getFix()).filter((f): f is Fix => !!f) as Fix[];
const source = fs.readFileSync(fileName, { encoding: "utf-8" });

return Fix.applyAll(source, fixes);
}

public ensureExactlyOneFileInFailuresList(failures: RuleFailure[]) {
const visitedCache: { [fileName: string]: true } = {};

for (const failure of failures) {
const fileName = failure.getFileName();

if (!(fileName in visitedCache)) {
visitedCache[fileName] = true;
}

if (Object.keys(visitedCache).length > 1) {
const files = Object.keys(visitedCache);
const filesFormattedForMsg = files.map((name) => `\t- ${name}`).join("\n");
const msg = "Only one file can be formatted with the fix formatter. \n\n" +
`Attempted to format files:\n ${filesFormattedForMsg}`;
throw new Error(msg);
}
}

if (Object.keys(visitedCache).length !== 1) {
throw new Error("Must have exactly one file with failures to apply Fix formatter.");
}
}
}
1 change: 1 addition & 0 deletions src/formatters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ export { Formatter as VerboseFormatter } from "./verboseFormatter";
export { Formatter as StylishFormatter } from "./stylishFormatter";
export { Formatter as FileslistFormatter } from "./fileslistFormatter";
export { Formatter as CodeFrameFormatter } from "./codeFrameFormatter";
export { Formatter as FixFormatter } from "./fixFormatter";
1 change: 1 addition & 0 deletions test/files/formatters/fixFormatter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
var x = 123;
86 changes: 86 additions & 0 deletions test/formatters/fixFormatterTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/**
* @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 * as path from "path";
import * as ts from "typescript";

import {Fix, IFormatter, Replacement, RuleFailure, TestUtils} from "../lint";

describe("Fix Formatter", () => {
let sourceFile: ts.SourceFile;
let formatter: IFormatter;

before(() => {
const Formatter = TestUtils.getFormatter("fix");
const sourceFilePath = path.resolve(__dirname, "../../../test/files/formatters/fixFormatter.test.ts");
sourceFile = TestUtils.getSourceFileAbsolute(sourceFilePath);
formatter = new Formatter();
});

it("returns the formatted source", () => {
const failures = [
new RuleFailure(
sourceFile,
0,
3,
"",
"no-var-keyword",
new Fix("no-var-keyword", [new Replacement(0, 3, "let")]),
),
];

const actualResult = formatter.format(failures);
assert.deepEqual(actualResult, "let x = 123;\n");
});

it("fails when there are multiple files given", () => {
const failures = [
new RuleFailure(
sourceFile,
0,
3,
"",
"no-var-keyword",
new Fix("no-var-keyword", [new Replacement(0, 3, "let")]),
),
new RuleFailure(
TestUtils.getSourceFile("formatters/jsonFormatter.test.ts"),
0,
3,
"",
"no-var-keyword",
new Fix("no-var-keyword", [new Replacement(0, 3, "let")]),
),
];

try {
formatter.format(failures);
throw new Error("Should not happen");
} catch (e) {
assert.include(e.message, "Only one file can be formatted with the fix formatter.");
}
});

it("throws an an error when there are no failures", () => {
try {
formatter.format([]);
throw new Error("Should not happen");
} catch (e) {
assert.deepEqual("Must have exactly one file with failures to apply Fix formatter.", e.message);
}
});
});
6 changes: 6 additions & 0 deletions test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ export function getSourceFile(fileName: string): ts.SourceFile {
return Lint.getSourceFile(fileName, source);
}

export function getSourceFileAbsolute(fileName: string): ts.SourceFile {
const source = fs.readFileSync(fileName, "utf8");

return Lint.getSourceFile(fileName, source);
}

export function getRule(ruleName: string) {
const rulesDirectory = path.join(path.dirname(module.filename), "../src/rules");
return Lint.findRule(ruleName, rulesDirectory);
Expand Down