-
Notifications
You must be signed in to change notification settings - Fork 17
/
LicenseIdentifier.ts
72 lines (66 loc) · 2.25 KB
/
LicenseIdentifier.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
// @ts-ignore
import * as validate from 'spdx-expression-validate'
import IAlertAggregator from './types/IAlertAggregator'
import IPackageJson from './types/IPackageJson'
import IPluginOptions from './types/IPluginOptions'
/**
* Identifies license type based on package.json and selects
* preferred license type if multiple are found
*
* @todo handle spdx OR case
* @todo handle license ambiguity via option (default to choosing the first)
*/
export default class LicenseIdentifier {
constructor(
private alertAggregator: IAlertAggregator,
private readonly preferredLicenses: string[] = []
) {}
public identifyLicense(
meta: IPackageJson,
options: Pick<
IPluginOptions,
'licenseOverrides' | 'unacceptableLicenseTest'
>
): string | null {
const id = `${meta.name}@${meta.version}`
let license: string
if (options.licenseOverrides[id]) {
license = options.licenseOverrides[id]
} else if (typeof meta.license === 'object') {
license = meta.license.type
} else if (meta.license) {
license = meta.license
} else if (Array.isArray(meta.licenses) && meta.licenses.length > 0) {
// handle deprecated `licenses` field
license =
this.findPreferredLicense(meta.licenses.map(l => l.type)) ||
meta.licenses[0].type
} else if (typeof meta.licenses === 'string') {
// handle invalid string values for deprecated `licenses` field
// unfortunately, these are rather common
license = meta.licenses
}
if (!license) {
this.alertAggregator.addError(`Could not find license info for ${id}`)
} else if (options.unacceptableLicenseTest(license)) {
this.alertAggregator.addError(
`Found unacceptable license "${license}" for ${id}`
)
} else if (!validate(license)) {
this.alertAggregator.addError(
`License "${license}" for ${id} is not a valid SPDX expression!`
)
}
return license || null
}
private findPreferredLicense(licenseTypes: string[]): string | null {
for (const preferredLicenseType of this.preferredLicenses) {
for (const licenseType of licenseTypes) {
if (preferredLicenseType === licenseType) {
return preferredLicenseType
}
}
}
return null
}
}