@approval-tests/approvals 7.5.12 → 7.5.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/lib/Logs/LogUtils.js +5 -3
  2. package/package.json +10 -4
  3. package/bin/index.ts +0 -108
  4. package/lib/AUtils.ts +0 -178
  5. package/lib/Approvals.ts +0 -321
  6. package/lib/Core/Namer.ts +0 -14
  7. package/lib/Core/Options.ts +0 -94
  8. package/lib/Core/Reporter.ts +0 -13
  9. package/lib/Core/Writer.ts +0 -5
  10. package/lib/FileApprover.ts +0 -116
  11. package/lib/FinalMessages.ts +0 -16
  12. package/lib/Logs/ApprovedFileLog.ts +0 -38
  13. package/lib/Logs/FailedFileLog.ts +0 -36
  14. package/lib/Logs/LogUtils.ts +0 -44
  15. package/lib/ManualNamer.ts +0 -12
  16. package/lib/Namer.ts +0 -28
  17. package/lib/Providers/BeforeEachVerifierBase.ts +0 -68
  18. package/lib/Providers/Jest/CombinationApprovals.ts +0 -161
  19. package/lib/Providers/Jest/JestApprovals.ts +0 -50
  20. package/lib/Providers/Jest/JestNamer.ts +0 -15
  21. package/lib/Providers/Jest/JestReporter.ts +0 -25
  22. package/lib/Providers/Jest/JestSetup.ts +0 -40
  23. package/lib/Providers/Mocha/MochaApprovals.ts +0 -74
  24. package/lib/Providers/Mocha/MochaNamer.ts +0 -84
  25. package/lib/Providers/OptionalFramework.ts +0 -11
  26. package/lib/Providers/Vitest/VitestApprovals.ts +0 -39
  27. package/lib/Providers/Vitest/VitestNamer.ts +0 -27
  28. package/lib/Providers/Vitest/VitestReporter.ts +0 -25
  29. package/lib/Reporting/DiffReporterAggregate.ts +0 -36
  30. package/lib/Reporting/GenericDiffReporterBase.ts +0 -154
  31. package/lib/Reporting/ReportByOpeningTheReceivedFile.ts +0 -22
  32. package/lib/Reporting/ReportLaunchingCircuitBreaker.ts +0 -40
  33. package/lib/Reporting/ReporterFactory.ts +0 -85
  34. package/lib/Reporting/Reporters/beyondcompareReporter.ts +0 -30
  35. package/lib/Reporting/Reporters/codiumReporter.ts +0 -26
  36. package/lib/Reporting/Reporters/copycommandReporter.ts +0 -46
  37. package/lib/Reporting/Reporters/diffmergeReporter.ts +0 -25
  38. package/lib/Reporting/Reporters/donothingReporter.ts +0 -13
  39. package/lib/Reporting/Reporters/gitdiffReporter.ts +0 -28
  40. package/lib/Reporting/Reporters/icdiffReporter.ts +0 -10
  41. package/lib/Reporting/Reporters/kdiff3Reporter.ts +0 -10
  42. package/lib/Reporting/Reporters/kompareReporter.ts +0 -10
  43. package/lib/Reporting/Reporters/meldReporter.ts +0 -10
  44. package/lib/Reporting/Reporters/multiReporter.ts +0 -55
  45. package/lib/Reporting/Reporters/nodediffReporter.ts +0 -61
  46. package/lib/Reporting/Reporters/opendiffReporter.ts +0 -10
  47. package/lib/Reporting/Reporters/p4mergeReporter.ts +0 -39
  48. package/lib/Reporting/Reporters/tortoisemergeReporter.ts +0 -25
  49. package/lib/Reporting/Reporters/vimdiffReporter.ts +0 -25
  50. package/lib/Reporting/Reporters/visualstudioReporter.ts +0 -48
  51. package/lib/Reporting/Reporters/vscodeReporter.ts +0 -26
  52. package/lib/Scrubbers/DateScrubber.ts +0 -83
  53. package/lib/Scrubbers/Scrubbers.ts +0 -106
  54. package/lib/StringWriter.ts +0 -73
  55. package/lib/Utilities/ConsoleUtils.ts +0 -15
  56. package/lib/Utilities/JestUtils.ts +0 -5
  57. package/lib/Utilities/Logger/LoggingInstance.ts +0 -247
  58. package/lib/Utilities/Logger/SimpleLogger.ts +0 -83
  59. package/lib/Utilities/Logger/SimpleLoggerApprovals.ts +0 -15
  60. package/lib/Utilities/Logger/StringWrapper.ts +0 -12
  61. package/lib/Utilities/Logger/Wrapper.ts +0 -27
  62. package/lib/Utilities/Printers.ts +0 -77
  63. package/lib/Utilities/StringUtils.ts +0 -8
  64. package/lib/Writers/BinaryWriter.ts +0 -42
  65. package/lib/config.ts +0 -95
  66. package/lib/osTools.ts +0 -11
  67. package/lib/postRunCleanup.ts +0 -63
@@ -1,15 +0,0 @@
1
- import path from "path";
2
- import { Namer } from "../../Namer";
3
- import { convertToFilename } from "../../Core/Namer";
4
-
5
- export function getJestNamer(): Namer {
6
- const { expect } = require("@jest/globals") as typeof import("@jest/globals");
7
- const state = expect.getState();
8
- const file = path.parse(state.testPath as string);
9
- const testPath = file.dir;
10
- const testFileName = file.name;
11
- const testName = convertToFilename(
12
- `${testFileName}.${state.currentTestName}`,
13
- );
14
- return new Namer(testPath, testName);
15
- }
@@ -1,25 +0,0 @@
1
- import { isFrameworkAvailable } from "../OptionalFramework";
2
- import fs from "fs";
3
- import { Config } from "../../config";
4
- import { Reporter } from "../../Core/Reporter";
5
-
6
- export class JestReporter implements Reporter {
7
- name: string = "JestReporter";
8
-
9
- canReportOn(_fileName: string) {
10
- return isFrameworkAvailable("jest");
11
- }
12
-
13
- report(
14
- approvedFilePath: string,
15
- receivedFilePath: string,
16
- _: Partial<Config>,
17
- ) {
18
- if (!isFrameworkAvailable("jest")) return;
19
- const { expect } =
20
- require("@jest/globals") as typeof import("@jest/globals");
21
- const approvedText = fs.readFileSync(approvedFilePath).toString();
22
- const receivedText = fs.readFileSync(receivedFilePath).toString();
23
- expect(receivedText).toBe(approvedText);
24
- }
25
- }
@@ -1,40 +0,0 @@
1
- import { ApprovedFileLog } from "../../Logs/ApprovedFileLog";
2
- import { FailedFileLog } from "../../Logs/FailedFileLog";
3
- import fs from "fs";
4
- import { LogUtils } from "../../Logs/LogUtils";
5
-
6
- export let jestInitializingRun = false;
7
-
8
- export function initializeGlobalsForJest() {
9
- ApprovedFileLog.forceClearLogFile();
10
- FailedFileLog.forceClearFileLog();
11
- jestInitializingRun = true;
12
- }
13
-
14
- export function helpUserSetupJest(fileToCheck: string) {
15
- LogUtils.ensureTempDirectoryExists();
16
- // Check if the file exists
17
- if (fs.existsSync(fileToCheck)) {
18
- // Get the date that fileToCheck was created
19
- const fileStats = fs.statSync(fileToCheck);
20
- const fileCreationDate = fileStats.birthtime;
21
-
22
- // Check if the date was in the last 24 hours
23
- const currentDate = new Date();
24
- const twentyFourHoursAgo = new Date(
25
- currentDate.getTime() - 24 * 60 * 60 * 1000,
26
- );
27
- const isFileRecent = fileCreationDate > twentyFourHoursAgo;
28
-
29
- if (isFileRecent) {
30
- return;
31
- }
32
- }
33
- const helpMessage = `
34
- **********************************************
35
- Jest needs to be set up for logging.
36
- More information at https://github.com/approvals/Approvals.NodeJS/blob/master/docs/how_tos/InitializeJestForLogging.md
37
- **********************************************
38
- `;
39
- console.log(helpMessage);
40
- }
@@ -1,74 +0,0 @@
1
- import { printArray, printJson } from "../../Utilities/Printers";
2
- /* ^^^ If the above line is failing, please add
3
- # 1. Jest Config
4
- ```
5
- "transformIgnorePatterns": ["node_modules/@3ds"]
6
- ```
7
-
8
- # 2. tsconfig.json
9
- ```
10
- "esModuleInterop": true
11
- ```
12
- */
13
- import { Options } from "../../Core/Options";
14
- import { getMochaNamer } from "./MochaNamer";
15
- import { isFrameworkAvailable } from "../OptionalFramework";
16
-
17
- import StringWriter from "../../StringWriter";
18
-
19
- import * as approvals from "../../Approvals";
20
- import { Namer } from "../../Core/Namer";
21
-
22
- let mochaTest: any = null;
23
-
24
- export function it2(label: string, test: () => void): void {
25
- if (!isFrameworkAvailable("mocha")) return;
26
- const mocha = require("mocha") as typeof import("mocha");
27
- mocha.it(label, function (this: any) {
28
- mochaTest = this;
29
- console.log("Mocha Test: ", mochaTest.test.name);
30
- test();
31
- });
32
- }
33
-
34
- let namer: Namer;
35
-
36
- export function setNamer(that: any): void {
37
- if (!isFrameworkAvailable("mocha")) return;
38
- namer = getMochaNamer(that.currentTest);
39
- }
40
-
41
- export function getNamer(): Namer {
42
- return namer;
43
- }
44
-
45
- export function verify(sut: any, options?: Options): void {
46
- if (!isFrameworkAvailable("mocha")) return;
47
- options = options || new Options();
48
- options = options.withNamer(getNamer());
49
- const config = options.getConfig(approvals.getConfig());
50
- const scrubbed = options.scrub(`${sut}`);
51
- const writer = new StringWriter(
52
- config,
53
- scrubbed,
54
- options.forFile().getFileExtension(),
55
- );
56
- approvals.verifyWithControl(namer, writer, null, config);
57
- }
58
-
59
- export function verifyAsJson(data: any, options?: Options): void {
60
- const text = printJson(data);
61
- options = options || new Options();
62
- options = options.forFile().withFileExtension(".json");
63
- verify(text, options);
64
- }
65
-
66
- export function verifyAll<T>(
67
- header: string,
68
- list: T[],
69
- formatter?: (element: T) => string,
70
- options?: Options,
71
- ): void {
72
- const text = printArray(header, list, formatter);
73
- verify(text, options);
74
- }
@@ -1,84 +0,0 @@
1
- import path from "path";
2
- import { Namer } from "../../Namer";
3
- import type { Runnable, Suite } from "mocha";
4
- import { convertToFilename } from "../../Core/Namer";
5
-
6
- export class MochaNamer extends Namer {
7
- // @ts-ignore errors if Mocha is not used
8
- private ctx: Mocha.Runnable;
9
-
10
- // @ts-ignore errors if Mocha is not used
11
- constructor(mochaTest: Mocha.Context, overrideBasePath?: string) {
12
- if (!mochaTest || !mochaTest.test) {
13
- throw new Error("Mocha test context was not supplied");
14
- }
15
-
16
- super("", "");
17
-
18
- this.ctx = mochaTest.test;
19
- this.basePath = overrideBasePath || path.dirname(this.ctx.file!);
20
- }
21
-
22
- getFullTestName(testContext: Runnable): string {
23
- let test = testContext;
24
-
25
- let parentStack: (Runnable | Suite)[] = [];
26
- let currParent: Runnable | undefined | Suite = test;
27
- while (currParent && currParent.parent) {
28
- parentStack.push(currParent);
29
- currParent = currParent.parent;
30
- }
31
-
32
- let newTitle = "";
33
- let parentStackReversed = parentStack.reverse();
34
- parentStackReversed.forEach((item, index) => {
35
- if (index !== 0) {
36
- newTitle += ".";
37
- }
38
-
39
- newTitle += item.title
40
- .split(" ")
41
- .join("_")
42
- .replace(/[^\w\s]/gi, "_");
43
- });
44
-
45
- return newTitle;
46
- }
47
-
48
- pathCreator(type: string, ext: string): string {
49
- if (!this.name) {
50
- if (!this.ctx) {
51
- throw new Error("ctx was not defined.");
52
- }
53
- this.name = this.getFullTestName(this.ctx);
54
- }
55
-
56
- return super.pathCreator(type, ext);
57
- }
58
- }
59
-
60
- function getTitleChain(test: any, pieces: string[] = []): string[] {
61
- if (test.title && test.title.length > 0) {
62
- pieces.unshift(test.title);
63
- }
64
- if (test.parent) {
65
- return getTitleChain(test.parent, pieces);
66
- }
67
- return pieces;
68
- }
69
-
70
- export function getMochaNamer(test: any): Namer {
71
- if (!test || !test.file || !test.title) {
72
- throw new Error(
73
- `Test context is missing required properties.\ntitle:${test.title}\nfile:${test.file}`,
74
- );
75
- }
76
-
77
- const file = path.parse(test.file);
78
- const testPath = file.dir;
79
- const testFileName = file.name;
80
- const pieces: string[] = getTitleChain(test);
81
- const testName = convertToFilename(`${testFileName}.${pieces.join(".")}`);
82
-
83
- return new Namer(testPath, testName);
84
- }
@@ -1,11 +0,0 @@
1
- export function isFrameworkAvailable(framework: string): boolean {
2
- try {
3
- require.resolve(framework);
4
- return true;
5
- } catch (error) {
6
- if ((error as NodeJS.ErrnoException).code !== "MODULE_NOT_FOUND") {
7
- throw error;
8
- }
9
- return false;
10
- }
11
- }
@@ -1,39 +0,0 @@
1
- import { printArray, printJson } from "../../Utilities/Printers";
2
- import { Options } from "../../Core/Options";
3
- import { getVitestNamer } from "./VitestNamer";
4
-
5
- import { StringWriter } from "../../StringWriter";
6
- import * as approvals from "../../Approvals";
7
- import { isFrameworkAvailable } from "../OptionalFramework";
8
-
9
- export function verify(sut: any, options?: Options): void {
10
- if (!isFrameworkAvailable("vitest")) return;
11
- options = options || new Options();
12
- options = options.withNamer(getVitestNamer());
13
- const config = options.getConfig(approvals.getConfig());
14
- const scrubbed = options.scrub(`${sut}`);
15
- const writer = new StringWriter(
16
- config,
17
- scrubbed,
18
- options.forFile().getFileExtension(),
19
- );
20
- let namer = options.getNamer();
21
- approvals.verifyWithControl(namer, writer, null, config);
22
- }
23
-
24
- export function verifyAsJson(data: any, options?: Options): void {
25
- const text = printJson(data);
26
- options = options || new Options();
27
- options = options.forFile().withFileExtension(".json");
28
- verify(text, options);
29
- }
30
-
31
- export function verifyAll<T>(
32
- header: string,
33
- list: T[],
34
- formatter?: (element: T) => string,
35
- options?: Options,
36
- ): void {
37
- const text = printArray(header, list, formatter);
38
- verify(text, options);
39
- }
@@ -1,27 +0,0 @@
1
- import path from "path";
2
- import { Namer } from "../../Namer";
3
- import { convertToFilename } from "../../Core/Namer";
4
- import { StringUtils } from "../../Utilities/StringUtils";
5
-
6
- interface VitestExpectState {
7
- testPath?: string;
8
- currentTestName?: string;
9
- }
10
-
11
- declare const expect: { getState(): VitestExpectState };
12
-
13
- export function getVitestNamer(): Namer {
14
- const state = expect.getState();
15
- const file = path.parse(state.testPath as string);
16
- const testPath = file.dir;
17
- const testFileName = file.name;
18
- const currentTestNameWithoutSeparators = StringUtils.replaceAll(
19
- state.currentTestName ?? "",
20
- " > ",
21
- " ",
22
- );
23
- const testName = convertToFilename(
24
- `${testFileName}.${currentTestNameWithoutSeparators}`,
25
- );
26
- return new Namer(testPath, testName);
27
- }
@@ -1,25 +0,0 @@
1
- import fs from "fs";
2
- import { Config } from "../../config";
3
- import { Reporter } from "../../Core/Reporter";
4
- import { isFrameworkAvailable } from "../OptionalFramework";
5
-
6
- declare const expect: (actual: unknown) => { toBe(expected: unknown): void };
7
-
8
- export class VitestReporter implements Reporter {
9
- name: string = "VitestReporter";
10
-
11
- canReportOn(_fileName: string) {
12
- return isFrameworkAvailable("vitest");
13
- }
14
-
15
- report(
16
- approvedFilePath: string,
17
- receivedFilePath: string,
18
- _: Partial<Config>,
19
- ) {
20
- if (!isFrameworkAvailable("vitest")) return;
21
- const approvedText = fs.readFileSync(approvedFilePath).toString();
22
- const receivedText = fs.readFileSync(receivedFilePath).toString();
23
- expect(receivedText).toBe(approvedText);
24
- }
25
- }
@@ -1,36 +0,0 @@
1
- import { Reporter } from "../Core/Reporter";
2
-
3
- class DiffReporterAggregate implements Reporter {
4
- private reporters: Reporter[];
5
- public name: string;
6
-
7
- constructor(reporters: Reporter[]) {
8
- this.reporters = reporters;
9
- this.name = `DiffReporterAggregate [${reporters.map((item) => item.name).join(", ")}]`;
10
- }
11
-
12
- getReporter(file: string): Reporter | null {
13
- for (const reporter of this.reporters) {
14
- if (reporter.canReportOn(file)) {
15
- return reporter;
16
- }
17
- }
18
- return null;
19
- }
20
-
21
- canReportOn(file: string): boolean {
22
- return !!this.getReporter(file);
23
- }
24
-
25
- report(approved: string, received: string, options?: any): void {
26
- const reporter = this.getReporter(received);
27
-
28
- if (reporter) {
29
- reporter.report(approved, received, options);
30
- } else {
31
- throw new Error("No reporter found!");
32
- }
33
- }
34
- }
35
-
36
- export = DiffReporterAggregate;
@@ -1,154 +0,0 @@
1
- import * as childProcess from "child_process";
2
- import * as fs from "fs";
3
- import * as autils from "../AUtils";
4
- import reportingLaunchingCircuitBreaker from "./ReportLaunchingCircuitBreaker";
5
- import { ChildProcessWithoutNullStreams } from "child_process";
6
- import { Reporter } from "../Core/Reporter";
7
- import { Config } from "../config";
8
-
9
- export class GenericDiffReporterBase implements Reporter {
10
- name: string;
11
- public exePath: string = "";
12
- private _reporterFileLookedUp: boolean;
13
- public setCommandArgs: (approved: string, received: string) => string[] = (
14
- a: string,
15
- r: string,
16
- ) => [r, a];
17
- public modifyCommandOptions: (commandOptions: any) => any = (c) => c;
18
- private _reporterFileLookedUpAndFound: boolean;
19
-
20
- constructor(name: string) {
21
- if (!name) {
22
- throw new Error("Argument name missing");
23
- }
24
-
25
- this.name = name;
26
- this._reporterFileLookedUp = false;
27
- this._reporterFileLookedUpAndFound = false;
28
- }
29
-
30
- isReporterAvailable(): boolean {
31
- if (this._reporterFileLookedUp) {
32
- return this._reporterFileLookedUpAndFound;
33
- }
34
-
35
- this._reporterFileLookedUp = true;
36
-
37
- if (!fs.existsSync(this.exePath)) {
38
- return false;
39
- }
40
- this._reporterFileLookedUpAndFound = true;
41
- return true;
42
- }
43
-
44
- canImageDiff(): boolean {
45
- return false;
46
- }
47
-
48
- canReportOn(fileName: string): boolean {
49
- if (!this.isReporterAvailable()) {
50
- return false;
51
- }
52
-
53
- autils.assertFileExists(fileName);
54
-
55
- if (this.canImageDiff()) {
56
- return true;
57
- }
58
-
59
- const isBinary = autils.isBinaryFile(fileName);
60
- return !isBinary;
61
- }
62
-
63
- spawn(
64
- exe: string,
65
- args: string[],
66
- cmdOptions?: any,
67
- ): ChildProcessWithoutNullStreams {
68
- const process = childProcess.spawn(exe, args, cmdOptions);
69
-
70
- let stdout = "";
71
- let stderr = "";
72
-
73
- process.stdout.on("data", (data) => {
74
- stdout += data;
75
- });
76
- process.stderr.on("data", (data) => {
77
- stderr += data;
78
- });
79
-
80
- process.on("close", () => {
81
- if (stdout) {
82
- console.log(
83
- "\n============\nstdout:\n============\n" +
84
- stdout +
85
- "\n============\n",
86
- );
87
- }
88
- if (stderr) {
89
- console.log(
90
- "\n============\nstderr:\n============\n" +
91
- stderr +
92
- "\n============\n",
93
- );
94
- }
95
- });
96
-
97
- return process;
98
- }
99
-
100
- spawnSync(exe: string, args: string[], cmdOptions?: any): void {
101
- const result = childProcess.spawnSync(exe, args, cmdOptions);
102
-
103
- const stdout = result.stdout.toString();
104
- const stderr = result.stderr.toString();
105
-
106
- if (stdout) {
107
- console.log(
108
- "\n============\nstdout:\n============\n" + stdout + "\n============\n",
109
- );
110
- }
111
- if (stderr) {
112
- console.log(
113
- "\n============\nstderr:\n============\n" + stderr + "\n============\n",
114
- );
115
- }
116
- }
117
-
118
- report(
119
- approved: string,
120
- received: string,
121
- options: Partial<Config> = {},
122
- ): void {
123
- if (!options.blockUntilReporterExits) {
124
- if (reportingLaunchingCircuitBreaker.check(approved, received, options)) {
125
- return;
126
- }
127
- }
128
-
129
- const spawnMethod = options.blockUntilReporterExits
130
- ? this.spawnSync.bind(this)
131
- : this.spawn.bind(this);
132
- autils.createEmptyFileIfNotExists(approved);
133
-
134
- const { cmdOptions, args } = this.getCommandArguments(
135
- approved,
136
- received,
137
- options,
138
- );
139
-
140
- console.log("CMD: ", this.exePath, args.join(" "));
141
-
142
- spawnMethod(this.exePath, args, cmdOptions);
143
- }
144
-
145
- getCommandArguments(
146
- approved: string,
147
- received: string,
148
- options: Partial<Config> = {},
149
- ) {
150
- const cmdOptions = this.modifyCommandOptions(options.cmdOptionOverrides);
151
- const args = options.cmdArgs || this.setCommandArgs(approved, received);
152
- return { cmdOptions, args };
153
- }
154
- }
@@ -1,22 +0,0 @@
1
- import { exec } from "child_process";
2
- import { Reporter } from "../Core/Reporter";
3
- import { Config } from "../config";
4
- import { platform } from "../osTools";
5
-
6
- export class ReportByOpeningTheReceivedFile implements Reporter {
7
- name: string = "ReportByOpeningTheReceivedFile";
8
-
9
- canReportOn(_fileName: string): boolean {
10
- return true;
11
- }
12
-
13
- report(
14
- _approvedFileName: string,
15
- receivedFileName: string,
16
- _options?: Partial<Config>,
17
- ): void {
18
- const openCommand = platform.isWindows ? "start" : "open";
19
- const shell = `${openCommand} "${receivedFileName}"`;
20
- exec(shell);
21
- }
22
- }
@@ -1,40 +0,0 @@
1
- import { FinalMessages } from "../FinalMessages";
2
- import NodeDiffReporter from "./Reporters/nodediffReporter";
3
-
4
- let maxLaunch = 10;
5
- let currentCount = 0;
6
- let reroutedCount = 0;
7
-
8
- export class ReportLaunchingCircuitBreaker {
9
- static setMaxLaunch(value: number): void {
10
- maxLaunch = value;
11
- }
12
-
13
- static get currentCount(): number {
14
- return currentCount;
15
- }
16
-
17
- static notifyLaunched(): void {
18
- currentCount++;
19
- }
20
-
21
- static isLimitExceeded(): boolean {
22
- return maxLaunch <= currentCount;
23
- }
24
-
25
- static check(approved: string, received: string, options: any): boolean {
26
- if (this.isLimitExceeded()) {
27
- reroutedCount++;
28
- FinalMessages.addKeyMessage(
29
- "maxLaunches",
30
- `config.maxLaunches (${maxLaunch}) exceeded: ${reroutedCount} diff(s) shown in console above...`,
31
- );
32
- new NodeDiffReporter().report(approved, received, options);
33
- return true;
34
- }
35
- this.notifyLaunched();
36
- return false;
37
- }
38
- }
39
-
40
- export default ReportLaunchingCircuitBreaker;
@@ -1,85 +0,0 @@
1
- import DiffReporterAggregate from "./DiffReporterAggregate";
2
- import { readdirSync } from "fs";
3
- import { Reporter } from "../Core/Reporter";
4
-
5
- export type ReporterLoader = () => Reporter[];
6
-
7
- export class ReporterFactory {
8
- static loadReporter(name: string | (string | Reporter)[]): Reporter {
9
- if (Array.isArray(name)) {
10
- const reporters = ReporterFactory.loadAllReporters(name);
11
- return new DiffReporterAggregate(reporters);
12
- }
13
-
14
- name = name.toLowerCase();
15
-
16
- try {
17
- const ReporterCtor = require(`./Reporters/${name}Reporter`);
18
- if (!ReporterCtor.default) {
19
- return new ReporterCtor();
20
- }
21
- return new ReporterCtor.default();
22
- } catch (e) {
23
- const allFiles = readdirSync(__dirname);
24
- const availableReporters = allFiles
25
- .map((item) => item.replace("Reporter.js", ""))
26
- .join(", ");
27
- throw new Error(
28
- `Error loading reporter or reporter not found [${name}]. Try one of the following [${availableReporters}]. Original Error: ${e}`,
29
- );
30
- }
31
- }
32
-
33
- static throwUnknownReporterError(reporter: unknown): never {
34
- throw new Error(
35
- `Unknown reporter: typeof= [${typeof reporter}]. Reporters are either a string like "gitdiff" or an object that conforms to the custom reporter interface.`,
36
- );
37
- }
38
-
39
- static assertValidReporter(
40
- reporter: Partial<Reporter>,
41
- ): reporter is Reporter {
42
- if (typeof reporter.name !== "string") {
43
- console.error("invalid reporter", reporter);
44
- throw new Error(
45
- "A valid reporter should have a 'name' property. EX: { name: \"my-custom-reporter\" }",
46
- );
47
- }
48
-
49
- if (typeof reporter.canReportOn !== "function") {
50
- console.error("invalid reporter", reporter);
51
- throw new Error(
52
- "A valid reporter should have a '{ canReportOn: function(fileName) { return true; // Example } ' function",
53
- );
54
- }
55
-
56
- if (typeof reporter.report !== "function") {
57
- console.error("invalid reporter", reporter);
58
- throw new Error(
59
- "A valid reporter should have a ' { report: function (approvedFilePath, receivedFilePath) {...} }' function",
60
- );
61
- }
62
-
63
- return true;
64
- }
65
-
66
- static loadAllReporters(reporters: (string | Reporter)[]): Reporter[] {
67
- const reporterInstances: Reporter[] = [];
68
-
69
- reporters.forEach((reporter) => {
70
- if (typeof reporter === "object") {
71
- ReporterFactory.assertValidReporter(reporter);
72
- reporterInstances.push(reporter as Reporter);
73
- } else if (typeof reporter === "string") {
74
- const reporterInstance = ReporterFactory.loadReporter(
75
- reporter,
76
- ) as Reporter;
77
- reporterInstances.push(reporterInstance);
78
- } else {
79
- ReporterFactory.throwUnknownReporterError(reporter);
80
- }
81
- });
82
-
83
- return reporterInstances;
84
- }
85
- }