-
Notifications
You must be signed in to change notification settings - Fork 6
/
getLicense.ts
95 lines (79 loc) · 2.72 KB
/
getLicense.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
import { getMatchingLicense } from './getMatchingLicense';
import { getPackageJson } from '../../utils/getPackageJson';
import { LicenseCheckConfiguration } from './LicenseCheckConfiguration';
import { packageLicenses } from '../../../configuration/packageLicenses';
import parse from 'spdx-expression-parse';
import { error, isError, Result, value } from 'defekt';
import * as errors from '../../errors';
const getLicense = async function ({ absoluteDirectory, licenseCheckConfiguration }: {
absoluteDirectory: string;
licenseCheckConfiguration?: LicenseCheckConfiguration;
}): Promise<Result<string, errors.LicenseNotFound | errors.LicenseNotSupported>> {
const packageJsonResult = await getPackageJson({ absoluteDirectory });
if (packageJsonResult.hasError()) {
return error(new errors.LicenseNotFound());
}
const packageJson = packageJsonResult.value;
let licenseString = '';
// The `packageJson.licenses` field is not valid anymore, but unfortunately
// still in use. (https://docs.npmjs.com/cli/v7/configuring-npm/package-json#license)
if (packageJson.licenses) {
const licenses: string[] = [];
for (const license of packageJson.licenses) {
if (typeof license === 'object') {
licenses.push(license.type!);
} else {
licenses.push(license);
}
}
if (licenses.length === 1) {
licenseString = licenses[0];
} else {
licenseString = `(${licenses.join(' AND ')})`;
}
}
if (packageJson.license) {
// Somehow some packages use an object as their license but type-fest does
// not support this.
if (typeof packageJson.license === 'object' && (packageJson.license as any).type) {
licenseString = (packageJson.license as any).type;
} else {
licenseString = packageJson.license;
}
}
const packageName = packageJson.name;
const packageVersion = packageJson.version;
if (!packageName || !packageVersion) {
return error(new errors.LicenseNotFound());
}
let knownPackageLicense: string | undefined;
if (licenseCheckConfiguration) {
knownPackageLicense = getMatchingLicense({
licensesMap: licenseCheckConfiguration.knownPackageLicenses ?? {},
packageName,
packageVersion
});
}
if (!knownPackageLicense) {
knownPackageLicense = getMatchingLicense({
licensesMap: packageLicenses,
packageName,
packageVersion
});
}
if (knownPackageLicense) {
licenseString = knownPackageLicense;
}
try {
parse(licenseString);
} catch (ex: unknown) {
if (!isError(ex)) {
throw new errors.OperationInvalid();
}
return error(new errors.LicenseNotSupported({ cause: ex, data: { license: licenseString }}));
}
return value(licenseString);
};
export {
getLicense
};