UNPKG

2.33 kBPlain TextView Raw
1import treeKill from 'tree-kill';
2import { StrykerError, KnownKeys } from '@stryker-mutator/util';
3import { WarningOptions } from '@stryker-mutator/api/core';
4
5export const objectUtils = {
6 /**
7 * Calls a defined callback function on each element of a map, and returns an array that contains the results.
8 *
9 * @param subject The map to act on
10 * @param callbackFn The callback fn
11 * @returns
12 */
13 map<K, V, R>(subject: Map<K, V>, callbackFn: (value: V, key: K) => R): R[] {
14 const results: R[] = [];
15 subject.forEach((value, key) => results.push(callbackFn(value, key)));
16 return results;
17 },
18
19 /**
20 * A wrapper around `process.env` (for testability)
21 */
22 getEnvironmentVariable(nameEnvironmentVariable: string): string | undefined {
23 return process.env[nameEnvironmentVariable];
24 },
25
26 undefinedEmptyString(str: string | undefined): string | undefined {
27 if (str) {
28 return str;
29 }
30 return undefined;
31 },
32
33 getEnvironmentVariableOrThrow(name: string): string {
34 const value = this.getEnvironmentVariable(name);
35 if (value === undefined) {
36 throw new StrykerError(`Missing environment variable "${name}"`);
37 } else {
38 return value;
39 }
40 },
41
42 isWarningEnabled(warningType: KnownKeys<WarningOptions>, warningOptions: WarningOptions | boolean): boolean {
43 if (typeof warningOptions === 'boolean') {
44 return warningOptions;
45 } else {
46 return !!warningOptions[warningType];
47 }
48 },
49
50 /**
51 * A wrapper around `process.exitCode = n` (for testability)
52 */
53 setExitCode(n: number): void {
54 process.exitCode = n;
55 },
56
57 kill(pid: number | undefined): Promise<void> {
58 return new Promise((res, rej) => {
59 treeKill(pid!, 'SIGKILL', (err?: Error & { code?: number }) => {
60 if (err && !canIgnore(err.code)) {
61 rej(err);
62 } else {
63 res();
64 }
65 });
66
67 function canIgnore(code: number | undefined) {
68 // https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes--0-499-
69 // these error codes mean the program is _already_ closed.
70 return code === 255 || code === 128;
71 }
72 });
73 },
74
75 /**
76 * Creates a random integer number.
77 * @returns A random integer.
78 */
79 random(): number {
80 return Math.ceil(Math.random() * 10000000);
81 },
82};
83
\No newline at end of file