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

Suggest language when one isn't found #116

Merged
merged 7 commits into from
Nov 8, 2018
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
9 changes: 7 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
},
"devDependencies": {
"@types/cosmiconfig": "5.0.3",
"@types/fast-levenshtein": "0.0.1",
"@types/jest": "23.3.9",
"@types/yargs": "12.0.1",
"@unibeautify/beautifier-eslint": "0.6.0",
Expand All @@ -61,6 +62,7 @@
"dependencies": {
"chalk": "^2.4.1",
"cosmiconfig": "^5.0.6",
"fast-levenshtein": "^2.0.6",
"g-search": "^0.3.0",
"requireg": "^0.2.1",
"unibeautify": "^0.17.0",
Expand Down
85 changes: 59 additions & 26 deletions src/commands/BeautifyCommand.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { BeautifyData } from "unibeautify";
import { BeautifyData, Unibeautify } from "unibeautify";
import cosmiconfig from "cosmiconfig";
import * as fs from "fs";
import * as levenshtein from "fast-levenshtein";

import { setupUnibeautify } from "../utils";
import { setupUnibeautify, getAllLanguages } from "../utils";
import { BaseCommand } from "./BaseCommand";

export class BeautifyCommand extends BaseCommand {
Expand All @@ -11,30 +12,28 @@ export class BeautifyCommand extends BaseCommand {
public beautify(programArgs: IArgs): Promise<string> {
const { language, filePath } = programArgs;
return setupUnibeautify().then(unibeautify => {
if (!language) {
const error = new Error("A language is required.");
return this.handleError(error, 1);
}
return Promise.all([
this.readConfig(programArgs),
this.readText(filePath),
]).then(([config, text]) => {
const data: BeautifyData = {
filePath: filePath,
languageName: language,
options: (config as any) || {},
text,
};
return unibeautify
.beautify(data)
.then((result: string) => {
return this.writeToFileOrStdout({ result, programArgs }).then(
() => result
);
})
.catch((error: Error) => {
return this.handleError(error, 1);
});
return this.validateLanguage(language, unibeautify).then(() => {
return Promise.all([
this.readConfig(programArgs),
this.readText(filePath),
]).then(([config, text]) => {
const data: BeautifyData = {
filePath: filePath,
languageName: language,
options: (config as any) || {},
text,
};
return unibeautify
.beautify(data)
.then((result: string) => {
return this.writeToFileOrStdout({ result, programArgs }).then(
() => result
);
})
.catch((error: Error) => {
return this.handleError(error, 1);
});
});
});
});
}
Expand Down Expand Up @@ -143,6 +142,40 @@ export class BeautifyCommand extends BaseCommand {
});
});
}

private validateLanguage(
language: string | undefined,
unibeautify: Unibeautify
): Promise<void> {
if (!language) {
const error = new Error("A language is required.");
return this.handleError(error, 1);
}
const langs = unibeautify.findLanguages({ name: language });
if (langs.length === 0) {
const allLanguages = getAllLanguages();
const distances: number[] = allLanguages.map(lang =>
levenshtein.get(lang.toLowerCase(), language.toLowerCase())
);
const bestDistance: number = Math.min(...distances);
const distanceThreshold = 2;
const bestMatchLanguages = allLanguages.filter(
(lang, index) =>
distances[index] <= Math.min(distanceThreshold, bestDistance)
);
if (bestMatchLanguages.length > 0) {
const limit = 3;
const error = new Error(
`Language '${language}' was not found. Did you mean:\n${bestMatchLanguages
.slice(0, limit)
.map(lang => ` - ${lang}`)
.join("\n")}`
);
return this.handleError(error, 1);
}
}
return Promise.resolve();
}
}

/**
Expand Down
56 changes: 55 additions & 1 deletion test/commands/BeautifyCommand.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ describe("BeautifyCommand", () => {
args: [],
configFile: "test/.unibeautifyrc.yml",
filePath: "test/fixtures/test1.js",
language: "javascript",
language: "thisIsntALanguage",
})
.then(thenCb)
.catch(catchCb)
Expand All @@ -232,6 +232,60 @@ describe("BeautifyCommand", () => {
expect(json).toMatchSnapshot("json");
});
});
test("should throw an error suggesting JavaScript for language", () => {
const command = new CustomCommand();
const thenCb = jest.fn();
const catchCb = jest.fn();
return command
.beautify({
args: [],
configFile: "test/.unibeautifyrc.yml",
filePath: "test/fixtures/test1.js",
language: "javascript",
})
.then(thenCb)
.catch(catchCb)
.then(() => {
expect(thenCb).not.toBeCalled();
expect(catchCb).toHaveBeenCalled();
expect(catchCb.mock.calls).toHaveLength(1);
expect(catchCb.mock.calls[0]).toHaveLength(1);
expect(catchCb).toHaveProperty(
["mock", "calls", 0, 0, "message"],
"Language 'javascript' was not found. Did you mean:\n - JavaScript"
);
const json = command.toJSON();
expect(json.exitCode).toBe(1);
expect(json).toMatchSnapshot("json");
});
});
test("should throw an error suggesting C, D and E for language", () => {
const command = new CustomCommand();
const thenCb = jest.fn();
const catchCb = jest.fn();
return command
.beautify({
args: [],
configFile: "test/.unibeautifyrc.yml",
filePath: "test/fixtures/test1.js",
language: "a",
})
.then(thenCb)
.catch(catchCb)
.then(() => {
expect(thenCb).not.toBeCalled();
expect(catchCb).toHaveBeenCalled();
expect(catchCb.mock.calls).toHaveLength(1);
expect(catchCb.mock.calls[0]).toHaveLength(1);
expect(catchCb).toHaveProperty(
["mock", "calls", 0, 0, "message"],
"Language 'a' was not found. Did you mean:\n - C\n - D\n - E"
);
const json = command.toJSON();
expect(json.exitCode).toBe(1);
expect(json).toMatchSnapshot("json");
});
});
test("should throw an error with invalid json", () => {
const command = new CustomCommand();
const thenCb = jest.fn();
Expand Down
22 changes: 22 additions & 0 deletions test/commands/__snapshots__/BeautifyCommand.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,28 @@ Object {
}
`;

exports[`BeautifyCommand Errors should throw an error suggesting C, D and E for language: json 1`] = `
Object {
"exitCode": 1,
"stderr": "Language 'a' was not found. Did you mean:
- C
- D
- E
",
"stdout": "",
}
`;

exports[`BeautifyCommand Errors should throw an error suggesting JavaScript for language: json 1`] = `
Object {
"exitCode": 1,
"stderr": "Language 'javascript' was not found. Did you mean:
- JavaScript
",
"stdout": "",
}
`;

exports[`BeautifyCommand Errors should throw an error with invalid json: json 1`] = `
Object {
"exitCode": 2,
Expand Down