-
Notifications
You must be signed in to change notification settings - Fork 53
/
LicenseTextReader.ts
96 lines (84 loc) · 2.77 KB
/
LicenseTextReader.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
import { LicenseTextOverrides } from './LicenseTextOverrides';
import { FileSystem } from './FileSystem';
import { Module } from './Module';
import { LicenseFileOverrides } from './LicenseFilesOverrides';
import { WebpackCompilation } from './WebpackCompilation';
import { Logger } from './Logger';
class LicenseTextReader {
constructor(
private logger: Logger,
private fileSystem: FileSystem,
private fileOverrides: LicenseFileOverrides,
private textOverrides: LicenseTextOverrides,
private templateDir: string | undefined,
private handleMissingLicenseText: ((
packageName: string,
licenseType: string | null
) => string | null)
) {}
readLicense(
compilation: WebpackCompilation,
module: Module,
licenseType: string | null
): string | null {
if (this.textOverrides[module.name]) {
return this.textOverrides[module.name];
}
if (this.fileOverrides[module.name]) {
return this.readText(module.directory, this.fileOverrides[module.name]);
}
if (licenseType && licenseType.indexOf('SEE LICENSE IN ') === 0) {
const filename = licenseType.split(' ')[3];
return this.fileSystem.isFileInDirectory(filename, module.directory)
? this.readText(module.directory, filename)
: null;
}
const pathsInModuleDirectory: string[] = this.fileSystem.listPaths(
module.directory
);
const guessedLicenseFilename = this.guessLicenseFilename(
pathsInModuleDirectory,
module.directory
);
if (guessedLicenseFilename !== null) {
return this.readText(module.directory, guessedLicenseFilename);
}
if (this.templateDir) {
const templateFilename = `${licenseType}.txt`;
if (
this.fileSystem.isFileInDirectory(templateFilename, this.templateDir)
) {
return this.fileSystem
.readFileAsUtf8(
this.fileSystem.join(this.templateDir, templateFilename)
)
.replace(/\r\n/g, '\n');
}
}
this.logger.warn(
compilation,
`could not find any license file for ${
module.name
}. Use the licenseTextOverrides option to add the license text if desired.`
);
return this.handleMissingLicenseText(module.name, licenseType);
}
readText(directory: string, filename: string): string {
return this.fileSystem
.readFileAsUtf8(this.fileSystem.join(directory, filename))
.replace(/\r\n/g, '\n');
}
private guessLicenseFilename(
paths: string[],
modulePath: string
): string | null {
for (const path of paths) {
const filePath = this.fileSystem.join(modulePath, path);
if (/^licen[cs]e/i.test(path) && !this.fileSystem.isDirectory(filePath)) {
return path;
}
}
return null;
}
}
export { LicenseTextReader };