/
InputFileResolver.ts
163 lines (148 loc) · 5.44 KB
/
InputFileResolver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import * as path from 'path';
import { fsAsPromised, isErrnoException } from '@stryker-mutator/util';
import { childProcessAsPromised } from '@stryker-mutator/util';
import { File, StrykerOptions } from 'stryker-api/core';
import { glob } from '../utils/fileUtils';
import StrictReporter from '../reporters/StrictReporter';
import { SourceFile } from 'stryker-api/report';
import { StrykerError } from '@stryker-mutator/util';
import InputFileCollection from './InputFileCollection';
import { normalizeWhiteSpaces, filterEmpty } from '../utils/objectUtils';
import { Config } from 'stryker-api/config';
import { tokens, commonTokens } from 'stryker-api/plugin';
import { coreTokens } from '../di';
import { Logger } from 'stryker-api/logging';
function toReportSourceFile(file: File): SourceFile {
return {
content: file.textContent,
path: file.name
};
}
const IGNORE_PATTERN_CHARACTER = '!';
export default class InputFileResolver {
private readonly mutatePatterns: ReadonlyArray<string>;
private readonly filePatterns: ReadonlyArray<string> | undefined;
public static inject = tokens(commonTokens.logger, commonTokens.options, coreTokens.reporter);
constructor(
private readonly log: Logger,
{ mutate, files }: StrykerOptions,
private readonly reporter: StrictReporter
) {
this.mutatePatterns = mutate || [];
if (files) {
this.filePatterns = files;
}
}
public async resolve(): Promise<InputFileCollection> {
const [inputFileNames, mutateFiles] = await Promise.all([
this.resolveInputFiles(),
this.resolveMutateFiles()
]);
const files: File[] = await this.readFiles(inputFileNames);
const inputFileCollection = new InputFileCollection(files, mutateFiles);
this.reportAllSourceFilesRead(files);
inputFileCollection.logFiles(this.log);
return inputFileCollection;
}
private resolveInputFiles() {
if (this.filePatterns) {
return this.expand(this.filePatterns);
} else {
return this.resolveFilesUsingGit();
}
}
private resolveMutateFiles() {
return this.expand(this.mutatePatterns, !shallowEquals(this.mutatePatterns, new Config().mutate));
function shallowEquals(arr1: ReadonlyArray<string>, arr2: ReadonlyArray<string>): boolean {
if (arr1.length !== arr2.length) {
return false;
} else {
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
}
}
/**
* Takes a list of globbing patterns and expands them into files.
* If a patterns starts with a `!`, it negates the pattern.
* @param patterns The patterns to expand into files
*/
private async expand(patterns: ReadonlyArray<string>, logAboutUselessPatterns = true): Promise<string[]> {
const fileSet = new Set<string>();
for (const pattern of patterns) {
if (pattern.startsWith(IGNORE_PATTERN_CHARACTER)) {
const files = await this.expandPattern(pattern.substr(1), logAboutUselessPatterns);
files.forEach(fileName => fileSet.delete(fileName));
} else {
const files = await this.expandPattern(pattern, logAboutUselessPatterns);
files.forEach(fileName => fileSet.add(fileName));
}
}
return Array.from(fileSet);
}
private async expandPattern(globbingExpression: string, logAboutUselessPatterns: boolean): Promise<string[]> {
const fileNames = (await glob(globbingExpression)).map(relativeFile => path.resolve(relativeFile));
if (!fileNames.length && logAboutUselessPatterns) {
this.log.warn(
`Globbing expression "${globbingExpression}" did not result in any files.`
);
}
return fileNames;
}
private async resolveFilesUsingGit(): Promise<string[]> {
try {
const { stdout } = await childProcessAsPromised.exec(
'git ls-files --others --exclude-standard --cached --exclude .stryker-tmp',
{ maxBuffer: 10 * 1000 * 1024 }
);
const fileNames = stdout.toString()
.split('\n')
.map(line => line.trim())
.filter(line => line) // remove empty lines
.map(relativeFileName => path.resolve(relativeFileName));
return fileNames;
} catch (error) {
throw new StrykerError(normalizeWhiteSpaces(
`Cannot determine input files. Either specify a \`files\`
array in your stryker configuration, or make sure "${process.cwd()}"
is located inside a git repository`),
error
);
}
}
private reportAllSourceFilesRead(allFiles: File[]) {
this.reporter.onAllSourceFilesRead(allFiles.map(toReportSourceFile));
}
private reportSourceFilesRead(textFile: File) {
this.reporter.onSourceFileRead(toReportSourceFile(textFile));
}
private readFiles(files: string[]): Promise<File[]> {
return Promise.all(files.map(fileName => this.readFile(fileName))).then(
filterEmpty
);
}
private readFile(fileName: string): Promise<File | null> {
return fsAsPromised
.readFile(fileName)
.then((content: Buffer) => new File(fileName, content))
.then((file: File) => {
this.reportSourceFilesRead(file);
return file;
})
.catch(error => {
if (
(isErrnoException(error) && error.code === 'ENOENT') ||
error.code === 'EISDIR'
) {
return null; // file is deleted or a directory. This can be a valid result of the git command
} else {
// Rethrow
throw error;
}
});
}
}