Commit 0b02a31c authored by David Sveningsson's avatar David Sveningsson Committed by David Sveningsson
Browse files

feat: support loading custom formatters

parent 81bef6e7
Pipeline #130680691 passed with stages
in 9 minutes and 39 seconds
......@@ -44,6 +44,8 @@ Possible formats are:
Multiples formatters can be set with a comma-separated list: `--formatter stylish,checkstyle`.
Output can be redirected to a file using `name=path`: `--formatter checkstyle=result.xml`.
Custom formatters can be used by specifying a package name: `--formater my-custom-formatter`.
html-validate --formatter stylish file.html
### `--max-warnings`
......
......@@ -4,6 +4,7 @@ import { CLI } from "./cli";
/* all mocked formatters must return empty string */
const textFormatter = jest.fn((report: Report) => ""); // eslint-disable-line @typescript-eslint/no-unused-vars
const jsonFormatter = jest.fn((report: Report) => ""); // eslint-disable-line @typescript-eslint/no-unused-vars
const customFormatter = jest.fn((report: Report) => ""); // eslint-disable-line @typescript-eslint/no-unused-vars
jest.mock("../formatters/text", () => {
return (report: Report) => textFormatter(report);
......@@ -13,6 +14,14 @@ jest.mock("../formatters/json", () => {
return (report: Report) => jsonFormatter(report);
});
jest.mock(
"custom-formatter",
() => {
return (report: Report) => customFormatter(report);
},
{ virtual: true }
);
const fs = {
existsSync: jest.fn().mockReturnValue(true),
mkdirSync: jest.fn(),
......@@ -74,6 +83,13 @@ describe("cli/formatters", () => {
expect(jsonFormatter).toHaveBeenCalledWith(report.results);
});
it("should call custom formatter", () => {
expect.assertions(1);
const wrapped = cli.getFormatter("custom-formatter");
wrapped(report);
expect(customFormatter).toHaveBeenCalledWith(report.results);
});
it("should redirect output to file", () => {
expect.assertions(2);
const wrapped = cli.getFormatter("text=foo.txt");
......
......@@ -27,10 +27,16 @@ function wrap(
function loadFormatter(name: string): Formatter {
const fn = formatterFactory(name);
if (!fn) {
throw new UserError(`No formatter named "${name}"`);
if (fn) {
return fn;
}
try {
/* eslint-disable-next-line import/no-dynamic-require */
return require(name);
} catch (error) {
throw new UserError(`No formatter named "${name}"`, error);
}
return fn;
}
export function getFormatter(formatters: string): (report: Report) => string {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment