-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
381 lines (330 loc) · 13.2 KB
/
index.js
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/env node
// usage
var yargs = require('yargs')
.usage('Calculate the npm and bower modules used in this project and generate a third-party attribution (credits) text.',
{
outputDir: {
alias: 'o',
default: './oss-attribution'
},
baseDir: {
alias: 'b',
default: process.cwd(),
}
})
.array('baseDir')
.example('$0 -o ./tpn', 'run the tool and output text and backing json to ${projectRoot}/tpn directory.')
.example('$0 -b ./some/path/to/projectDir', 'run the tool for Bower/NPM projects in another directory.')
.example('$0 -o tpn -b ./some/path/to/projectDir', 'run the tool in some other directory and dump the output in a directory called "tpn" there.');
if (yargs.argv.help) {
yargs.showHelp();
process.exit(1);
}
// dependencies
var bluebird = require('bluebird');
var _ = require('lodash');
var npmchecker = require('license-checker');
var bower = require('bower');
var path = require('path');
var jetpack = require('fs-jetpack');
var cp = require('child_process');
var os = require('os');
var taim = require('taim');
// const
var licenseCheckerCustomFormat = {
name: '',
version: '',
description: '',
repository: '',
publisher: '',
email: '',
url: '',
licenses: '',
licenseFile: '',
licenseModified: false
}
/**
* Helpers
*/
function getAttributionForAuthor(a) {
return _.isString(a) ? a : a.name + ((a.email || a.homepage || a.url) ? ` <${a.email || a.homepage || a.url}>` : '');
}
function getNpmLicenses() {
var npmDirs;
if (!Array.isArray(options.baseDir)) {
npmDirs = [options.baseDir];
} else {
npmDirs = options.baseDir;
}
// first - check that this is even an NPM project
for (var i = 0; i < npmDirs.length; i++) {
if (!jetpack.exists(path.join(npmDirs[i], 'package.json'))) {
console.log('directory at "' + npmDirs[i] + '" does not look like an NPM project, skipping NPM checks for path ' + npmDirs[i]);
return [];
}
}
console.log('Looking at directories: ' + npmDirs)
var res = []
var checkers = [];
for (var i = 0; i < npmDirs.length; i++) {
checkers.push(
bluebird.fromCallback((cb) => {
var dir = npmDirs[i];
return npmchecker.init({
start: npmDirs[i],
production: true,
customFormat: licenseCheckerCustomFormat
}, function (err, json) {
if (err) {
//Handle error
console.error(err);
} else {
Object.getOwnPropertyNames(json).forEach(k => {
json[k]['dir'] = dir;
})
}
cb(err, json);
});
})
);
}
if (checkers.length === 0) {
return [];
}
return bluebird.all(checkers)
.then((raw_result) => {
// the result is passed in as an array, one element per npmDir passed in
// de-dupe the entries and merge it into a single object
var merged = {};
for (var i = 0; i < raw_result.length; i++) {
merged = Object.assign(raw_result[i], merged);
}
return merged;
}).then((result) => {
// we want to exclude the top-level project from being included
var dir = result[Object.keys(result)[0]]['dir'];
var topLevelProjectInfo = jetpack.read(path.join(dir, 'package.json'), 'json');
var keys = Object.getOwnPropertyNames(result).filter((k) => {
return k !== `${topLevelProjectInfo.name}@${topLevelProjectInfo.version}`;
});
return bluebird.map(keys, (key) => {
console.log('processing', key);
var package = result[key];
var defaultPackagePath = `${package['dir']}/node_modules/${package.name}/package.json`;
var itemAtPath = jetpack.exists(defaultPackagePath);
var packagePath = [defaultPackagePath];
if (itemAtPath !== 'file') {
packagePath = jetpack.find(package['dir'], {
matching: `**/node_modules/${package.name}/package.json`
});
}
var packageJson = "";
if (packagePath && packagePath[0]) {
packageJson = jetpack.read(packagePath[0], 'json');
} else {
return Promise.reject(`${package.name}: unable to locate package.json`);
}
console.log('processing', packageJson.name, 'for authors and licenseText');
var props = {};
props.authors =
(packageJson.author && getAttributionForAuthor(packageJson.author)) ||
(packageJson.contributors && packageJson.contributors
.map(c => {
return getAttributionForAuthor(c);
}).join(', ')) ||
(packageJson.maintainers && packageJson.maintainers
.map(m => {
return getAttributionForAuthor(m);
}).join(', '));
var licenseFile = package.licenseFile;
try {
if (licenseFile && jetpack.exists(licenseFile) && path.basename(licenseFile).match(/license/i)) {
props.licenseText = jetpack.read(licenseFile);
} else {
props.licenseText = '';
}
} catch (e) {
console.warn(e);
return {
authors: '',
licenseText: ''
};
}
return {
ignore: false,
name: package.name,
version: package.version,
authors: props.authors,
url: package.repository,
license: package.licenses,
licenseText: props.licenseText
};
}, {
concurrency: os.cpus().length
});
});
}
/**
* TL;DR - normalizing the output format for NPM & Bower license info
*
* The output from license-checker gives us what we need:
* - component name
* - version
* - authors (note: not returned by license-checker, we have to apply our heuristic)
* - url
* - license(s)
* - license contents OR license snippet (in case of license embedded in markdown)
*
* Where we calculate the license information manually for Bower components,
* we'll return an object with these properties.
*/
function getBowerLicenses() {
// first - check that this is even a bower project
var baseDir;
if (Array.isArray(options.baseDir)) {
baseDir = options.baseDir[0];
if (options.baseDir.length > 1) {
console.warn("Checking multiple directories is not yet supported for Bower projects.\n" +
"Checking only the first directory: " + baseDir);
}
}
if (!jetpack.exists(path.join(baseDir, 'bower.json'))) {
console.log('this does not look like a Bower project, skipping Bower checks.');
return [];
}
bower.config.cwd = baseDir;
var bowerComponentsDir = path.join(bower.config.cwd, bower.config.directory);
return jetpack.inspectTreeAsync(bowerComponentsDir, { relativePath: true })
.then((result) => {
/**
* for each component, try to calculate the license from the NPM package info
* if it is a available because license-checker more closely aligns with our
* objective.
*/
return bluebird.map(result.children, (component) => {
var absPath = path.join(bowerComponentsDir, component.relativePath);
// npm license check didn't work
// try to get the license and package info from .bower.json first
// because it has more metadata than the plain bower.json
var package = '';
try {
package = jetpack.read(path.join(absPath, '.bower.json'), 'json');
} catch (e) {
package = jetpack.read(path.join(absPath, 'bower.json'), 'json');
}
console.log('processing', package.name);
// assumptions here based on https://github.com/bower/spec/blob/master/json.md
// extract necessary properties as described in TL;DR above
var url = package["_source"] || (package.repository && package.repository.url) ||
package.url || package.homepage;
var authors = '';
if (package.authors) {
authors = _.map(package.authors, a => {
return getAttributionForAuthor(a);
}).join(', ');
} else {
// extrapolate author from url if it's a github repository
var githubMatch = url.match(/github\.com\/.*\//);
if (githubMatch) {
authors = githubMatch[0]
.replace('github.com', '')
.replace(/\//g, '');
}
}
// normalize the license object
package.license = package.license || package.licenses;
var licenses = package.license && _.isString(package.license)
? package.license
: _.isArray(package.license)
? package.license.join(',')
: package.licenses;
// find the license file if it exists
var licensePath = _.find(component.children, c => {
return /licen[cs]e/i.test(c.name);
});
var licenseText = null;
if (licensePath) {
licenseText = jetpack.read(path.join(bowerComponentsDir, licensePath.relativePath));
}
return {
ignore: false,
name: package.name,
version: package.version || package['_release'],
authors: authors,
url: url,
license: licenses,
licenseText: licenseText
};
}, {
concurrency: os.cpus().length
});
});
}
/***********************
*
* MAIN
*
***********************/
// sanitize inputs
var options = {
baseDir: [],
outputDir: path.resolve(yargs.argv.outputDir)
};
for (var i = 0; i < yargs.argv.baseDir.length; i++) {
options.baseDir.push(path.resolve(yargs.argv.baseDir[i]));
}
taim('Total Processing', bluebird.all([
taim('Npm Licenses', getNpmLicenses()),
getBowerLicenses()
]))
.catch((err) => {
console.log(err);
process.exit(1);
})
.spread((npmOutput, bowerOutput) => {
var o = {};
npmOutput = npmOutput || {};
bowerOutput = bowerOutput || {};
_.concat(npmOutput, bowerOutput).forEach((v) => {
o[v.name] = v;
});
var userOverridesPath = path.join(options.outputDir, 'overrides.json');
if (jetpack.exists(userOverridesPath)) {
var userOverrides = jetpack.read(userOverridesPath, 'json');
console.log('using overrides:', userOverrides);
// foreach override, loop through the properties and assign them to the base object.
o = _.defaultsDeep(userOverrides, o);
}
return o;
})
.catch(e => {
console.error('ERROR processing overrides', e);
process.exit(1);
})
.then((licenseInfos) => {
var attributionSequence = _(licenseInfos).filter(licenseInfo => {
return !licenseInfo.ignore && licenseInfo.name != undefined;
}).sortBy(licenseInfo => {
return licenseInfo.name.toLowerCase();
}).map(licenseInfo => {
return [licenseInfo.name,`${licenseInfo.version} <${licenseInfo.url}>`,
licenseInfo.licenseText || `license: ${licenseInfo.license}${os.EOL}authors: ${licenseInfo.authors}`].join(os.EOL);
}).value();
var attribution = attributionSequence.join(`${os.EOL}${os.EOL}******************************${os.EOL}${os.EOL}`);
var headerPath = path.join(options.outputDir, 'header.txt');
if (jetpack.exists(headerPath)) {
var template = jetpack.read(headerPath);
console.log('using template', template);
attribution = template + os.EOL + os.EOL + attribution;
}
jetpack.write(path.join(options.outputDir, 'licenseInfos.json'), JSON.stringify(licenseInfos));
return jetpack.write(path.join(options.outputDir, 'attribution.txt'), attribution);
})
.catch(e => {
console.error('ERROR writing attribution file', e);
process.exit(1);
})
.then(() => {
console.log('done');
process.exit();
});