1 | import semver from 'semver';
|
2 |
|
3 | guardMinimalNodeVersion();
|
4 |
|
5 | import { Command } from 'commander';
|
6 | import { MutantResult, DashboardOptions, ALL_REPORT_TYPES, PartialStrykerOptions } from '@stryker-mutator/api/core';
|
7 |
|
8 | import { initializerFactory } from './initializer/index.js';
|
9 | import { LogConfigurator } from './logging/index.js';
|
10 | import { Stryker } from './stryker.js';
|
11 | import { defaultOptions } from './config/index.js';
|
12 | import { strykerEngines, strykerVersion } from './stryker-package.js';
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | function deepOption<T extends string, R>(object: { [K in T]?: R }, key: T) {
|
20 | return (value: R) => {
|
21 | object[key] = value;
|
22 | return undefined;
|
23 | };
|
24 | }
|
25 |
|
26 | const list = createSplitter(',');
|
27 |
|
28 | function createSplitter(sep: string) {
|
29 | return (val: string) => val.split(sep).filter(Boolean);
|
30 | }
|
31 |
|
32 | function parseBoolean(val: string) {
|
33 | const v = val.toLocaleLowerCase();
|
34 | return v !== 'false' && v !== '0';
|
35 | }
|
36 |
|
37 | function parseCleanDirOption(val: string) {
|
38 | const v = val.toLocaleLowerCase();
|
39 | return v === 'always' ? v : v !== 'false' && v !== '0';
|
40 | }
|
41 |
|
42 | export class StrykerCli {
|
43 | private command = '';
|
44 | private strykerConfig: string | null = null;
|
45 |
|
46 | constructor(
|
47 | private readonly argv: string[],
|
48 | private readonly program: Command = new Command(),
|
49 | private readonly runMutationTest = async (options: PartialStrykerOptions) => new Stryker(options).runMutationTest(),
|
50 | ) {}
|
51 |
|
52 | public run(): void {
|
53 | const dashboard: Partial<DashboardOptions> = {};
|
54 | this.program
|
55 |
|
56 | .version(strykerVersion)
|
57 | .usage('<command> [options] [configFile]')
|
58 | .description(
|
59 | `Possible commands:
|
60 | run: Run mutation testing
|
61 | init: Initialize Stryker for your project
|
62 |
|
63 | Optional location to a JSON or JavaScript config file as the last argument. If it's a JavaScript file, that file should export the config directly.`,
|
64 | )
|
65 | .arguments('<command> [configFile]')
|
66 | .action((cmd: string, config: string) => {
|
67 | this.command = cmd;
|
68 | this.strykerConfig = config;
|
69 | })
|
70 | .option(
|
71 | '-f, --files <allFiles>',
|
72 | '[DEPRECATED, you probably want to use `--mutate` or less likely `--ignorePatterns` instead] A comma separated list of patterns used for selecting ALL files needed to run the tests. That are NOT ONLY the files you want to actually mutate (which must be selected with `--mutate`), but instead also the other files you need too, like the files containing the tests, configuration files and such. Note: This option will have NO effect when using the --inPlace option. For a more detailed way of selecting input files, please use a configFile. Example: src/**/*.js,!src/index.js,a.js,test/**/*.js.',
|
73 | list,
|
74 | )
|
75 | .option(
|
76 | '--ignorePatterns <filesToIgnore>',
|
77 | 'A comma separated list of patterns used for specifying which files need to be ignored. This should only be used in cases where you experience a slow Stryker startup, because too many (or too large) files are copied to the sandbox that are not needed to run the tests. For example, image or movie directories. Note: This option will have NO effect when using the `--inPlace` option. The directories `node_modules`, `.git` and some others are always ignored. Example: `--ignorePatterns dist`. These patterns are ALWAYS ignored: [`node_modules`, `.git`, `/reports`, `*.tsbuildinfo`, `/stryker.log`, `.stryker-tmp`]. Because Stryker always ignores these, you should rarely have to adjust the `ignorePatterns` setting at all. This is useful to speed up Stryker by ignoring big directories/files you might have in your repo that has nothing to do with your code. For example, 1.5GB of movie/image files. Specify the patterns to all files or directories that are not used to run your tests and thus should NOT be copied to the sandbox directory for mutation testing. Each patterns in this array should be a [glob pattern](#usage-of-globbing-expressions-on-options). If a glob pattern starts with `/`, the pattern is relative to the current working directory. For example, `/foo.js` matches to `foo.js` but not `subdir/foo.js`. However to SELECT specific files TO BE mutated, you better use `--mutate`.',
|
78 | list,
|
79 | )
|
80 | .option('--ignoreStatic', 'Ignore static mutants. Static mutants are mutants which are only executed during the loading of a file.')
|
81 | .option(
|
82 | '--incremental',
|
83 | "Enable 'incremental mode'. Stryker will store results in a file and use that file to speed up the next --incremental run",
|
84 | )
|
85 | .option('--allowEmpty', 'Allows stryker to exit without any errors in cases where no tests are found ')
|
86 | .option('--incrementalFile <file>', 'Specify the file to use for incremental mode.')
|
87 | .option(
|
88 | '--force',
|
89 | 'Run all mutants, even if --incremental is provided and an incremental file exists. Can be used to force a rebuild of the incremental file.',
|
90 | )
|
91 | .option(
|
92 | '-m, --mutate <filesToMutate>',
|
93 | 'With `mutate` you configure the subset of files or just one specific file to be mutated. These should be your _production code files_, and definitely not your test files.\n(Whereas with `ignorePatterns` you prevent non-relevant files from being copied to the sandbox directory in the first place)\nThe default will try to guess your production code files based on sane defaults. It reads like this:\n- Include all js-like files inside the `src` or `lib` dir\n- Except files inside `__tests__` directories and file names ending with `test` or `spec`.\nIf the defaults are not sufficient for you, for example in a angular project you might want to\n **exclude** not only the `*.spec.ts` files but other files too, just like the default already does.\nIt is possible to specify exactly which code blocks to mutate by means of a _mutation range_. This can be done postfixing your file with `:startLine[:startColumn]-endLine[:endColumn]`. Example: src/index.js:1:3-1:5',
|
94 | list,
|
95 | )
|
96 | .option(
|
97 | '-b, --buildCommand <command>',
|
98 | 'Configure a build command to run after mutating the code, but before mutants are tested. This is generally used to transpile your code before testing.' +
|
99 | " Only configure this if your test runner doesn't take care of this already and you're not using just-in-time transpiler like `babel/register` or `ts-node`.",
|
100 | )
|
101 | .option(
|
102 | '--dryRunOnly',
|
103 | 'Execute the initial test run only, without doing actual mutation testing. Doing a dry run only can be used to test that StrykerJS can run your test setup, for example, in CI pipelines.',
|
104 | )
|
105 | .option(
|
106 | '--checkers <listOfCheckersOrEmptyString>',
|
107 | 'A comma separated list of checkers to use, for example --checkers typescript',
|
108 | createSplitter(','),
|
109 | )
|
110 | .option('--checkerNodeArgs <listOfNodeArgs>', 'A list of node args to be passed to checker child processes.', createSplitter(' '))
|
111 | .option(
|
112 | '--coverageAnalysis <perTest|all|off>',
|
113 | `The coverage analysis strategy you want to use. Default value: "${defaultOptions.coverageAnalysis}"`,
|
114 | )
|
115 | .option('--testRunner <name>', 'The name of the test runner you want to use')
|
116 | .option(
|
117 | '--testRunnerNodeArgs <listOfNodeArgs>',
|
118 | 'A comma separated list of node args to be passed to test runner child processes.',
|
119 | createSplitter(' '),
|
120 | )
|
121 | .option('--reporters <name>', 'A comma separated list of the names of the reporter(s) you want to use', list)
|
122 | .option('--plugins <listOfPlugins>', 'A list of plugins you want stryker to load (`require`).', list)
|
123 | .option(
|
124 | '--appendPlugins <listOfPlugins>',
|
125 | 'A list of additional plugins you want Stryker to load (`require`) without overwriting the (default) `plugins`.',
|
126 | list,
|
127 | )
|
128 | .option('--timeoutMS <number>', 'Tweak the absolute timeout used to wait for a test runner to complete', parseInt)
|
129 | .option('--timeoutFactor <number>', 'Tweak the standard deviation relative to the normal test run of a mutated test', parseFloat)
|
130 | .option('--dryRunTimeoutMinutes <number>', 'Configure an absolute timeout for the initial test run. (It can take a while.)', parseFloat)
|
131 | .option('--maxConcurrentTestRunners <n>', 'Set the number of max concurrent test runner to spawn (default: cpuCount)', parseInt)
|
132 | .option(
|
133 | '-c, --concurrency <n>',
|
134 | 'Set the concurrency of workers. Stryker will always run checkers and test runners in parallel by creating worker processes (default: cpuCount - 1)',
|
135 | parseInt,
|
136 | )
|
137 | .option('--disableBail', 'Force the test runner to keep running tests, even when a mutant is already killed.')
|
138 | .option(
|
139 | '--maxTestRunnerReuse <n>',
|
140 | 'Restart each test runner worker process after `n` runs. Not recommended unless you are experiencing memory leaks that you are unable to resolve. Configuring `0` here means infinite reuse.',
|
141 | parseInt,
|
142 | )
|
143 | .option(
|
144 | '--logLevel <level>',
|
145 | `Set the log level for the console. Possible values: fatal, error, warn, info, debug, trace and off. Default is "${defaultOptions.logLevel}"`,
|
146 | )
|
147 | .option(
|
148 | '--fileLogLevel <level>',
|
149 | `Set the log4js log level for the "stryker.log" file. Possible values: fatal, error, warn, info, debug, trace and off. Default is "${defaultOptions.fileLogLevel}"`,
|
150 | )
|
151 | .option('--allowConsoleColors <true/false>', 'Indicates whether or not Stryker should use colors in console.', parseBoolean)
|
152 | .option(
|
153 | '--dashboard.project <name>',
|
154 | 'Indicates which project name to use if the "dashboard" reporter is enabled. Defaults to the git url configured in the environment of your CI server.',
|
155 | deepOption(dashboard, 'project'),
|
156 | )
|
157 | .option(
|
158 | '--dashboard.version <version>',
|
159 | 'Indicates which version to use if the "dashboard" reporter is enabled. Defaults to the branch name or tag name configured in the environment of your CI server.',
|
160 | deepOption(dashboard, 'version'),
|
161 | )
|
162 | .option(
|
163 | '--dashboard.module <name>',
|
164 | 'Indicates which module name to use if the "dashboard" reporter is enabled.',
|
165 | deepOption(dashboard, 'module'),
|
166 | )
|
167 | .option(
|
168 | '--dashboard.baseUrl <url>',
|
169 | `Indicates which baseUrl to use when reporting to the stryker dashboard. Default: "${defaultOptions.dashboard.baseUrl}"`,
|
170 | deepOption(dashboard, 'baseUrl'),
|
171 | )
|
172 | .option(
|
173 | `--dashboard.reportType <${ALL_REPORT_TYPES.join('|')}>`,
|
174 | `Send a full report (inc. source code and mutant results) or only the mutation score. Default: ${defaultOptions.dashboard.reportType}`,
|
175 | deepOption(dashboard, 'reportType'),
|
176 | )
|
177 | .option(
|
178 | '--inPlace',
|
179 | 'Determines whether or not Stryker should mutate your files in place. Note: mutating your files in place is generally not needed for mutation testing, unless you have a dependency in your project that is really dependent on the file locations (like "app-root-path" for example).\nWhen `true`, Stryker will override your files, but it will keep a copy of the originals in the temp directory (using `tempDirName`) and it will place the originals back after it is done. Also with `true` the `ignorePatterns` has no effect any more.\nWhen `false` (default) Stryker will work in the copy of your code inside the temp directory.',
|
180 | )
|
181 | .option(
|
182 | '--tempDirName <name>',
|
183 | 'Set the name of the directory that is used by Stryker as a working directory. This directory will be cleaned after a successful run',
|
184 | )
|
185 | .option(
|
186 | '--cleanTempDir <true | false | always>',
|
187 | `Choose whether or not to clean the temp dir (which is "${defaultOptions.tempDirName}" inside the current working directory by default) after a run.\n - false: Never delete the temp dir;\n - true: Delete the tmp dir after a successful run;\n - always: Always delete the temp dir, regardless of whether the run was successful.`,
|
188 | parseCleanDirOption,
|
189 | )
|
190 | .showSuggestionAfterError()
|
191 | .parse(this.argv);
|
192 |
|
193 |
|
194 | const options: PartialStrykerOptions = this.program.opts();
|
195 | LogConfigurator.configureMainProcess(options.logLevel);
|
196 |
|
197 |
|
198 | delete options.version;
|
199 | Object.keys(options)
|
200 | .filter((key) => key.startsWith('dashboard.'))
|
201 | .forEach((key) => delete options[key]);
|
202 |
|
203 | if (this.strykerConfig) {
|
204 | options.configFile = this.strykerConfig;
|
205 | }
|
206 | if (Object.keys(dashboard).length > 0) {
|
207 | options.dashboard = dashboard;
|
208 | }
|
209 |
|
210 | const commands = {
|
211 | init: () => initializerFactory().initialize(),
|
212 | run: () => this.runMutationTest(options),
|
213 | };
|
214 |
|
215 | if (Object.keys(commands).includes(this.command)) {
|
216 | const promise: Promise<MutantResult[] | void> = commands[this.command as keyof typeof commands]();
|
217 | promise.catch(() => {
|
218 | process.exitCode = 1;
|
219 | });
|
220 | } else {
|
221 | console.error('Unknown command: "%s", supported commands: [%s], or use `stryker --help`.', this.command, Object.keys(commands));
|
222 | }
|
223 | }
|
224 | }
|
225 |
|
226 | export function guardMinimalNodeVersion(processVersion = process.version): void {
|
227 | if (!semver.satisfies(processVersion, strykerEngines.node)) {
|
228 | throw new Error(
|
229 | `Node.js version ${processVersion} detected. StrykerJS requires version to match ${strykerEngines.node}. Please update your Node.js version or visit https://nodejs.org/ for additional instructions`,
|
230 | );
|
231 | }
|
232 | }
|