forked from CycloneDX/cdxgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
3136 lines (3049 loc) · 86.3 KB
/
utils.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const glob = require("glob");
const os = require("os");
const path = require("path");
const parsePackageJsonName = require("parse-packagejson-name");
const fs = require("fs");
const got = require("got");
const convert = require("xml-js");
const licenseMapping = require("./license-mapping.json");
const vendorAliases = require("./vendor-alias.json");
const spdxLicenses = require("./spdx-licenses.json");
const knownLicenses = require("./known-licenses.json");
const cheerio = require("cheerio");
const yaml = require("js-yaml");
const { spawnSync } = require("child_process");
const propertiesReader = require("properties-reader");
const semver = require("semver");
const StreamZip = require("node-stream-zip");
const ednDataLib = require("edn-data");
// Debug mode flag
const DEBUG_MODE =
process.env.SCAN_DEBUG_MODE === "debug" ||
process.env.SHIFTLEFT_LOGGING_LEVEL === "debug";
// Metadata cache
let metadata_cache = {};
const MAX_LICENSE_ID_LENGTH = 100;
/**
* Method to get files matching a pattern
*
* @param {string} dirPath Root directory for search
* @param {string} pattern Glob pattern (eg: *.gradle)
*/
const getAllFiles = function (dirPath, pattern) {
try {
return glob.sync(pattern, {
cwd: dirPath,
silent: true,
absolute: true,
nocase: true,
nodir: true,
dot: false,
follow: false,
ignore: [
"node_modules",
".hg",
".git",
"venv",
"docs",
"examples",
"site-packages",
],
});
} catch (err) {
console.error(err);
return [];
}
};
exports.getAllFiles = getAllFiles;
const toBase64 = (hexString) => {
return Buffer.from(hexString, "hex").toString("base64");
};
/**
* Performs a lookup + validation of the license specified in the
* package. If the license is a valid SPDX license ID, set the 'id'
* and url of the license object, otherwise, set the 'name' of the license
* object.
*/
function getLicenses(pkg, format = "xml") {
let license = pkg.license && (pkg.license.type || pkg.license);
if (license) {
if (!Array.isArray(license)) {
license = [license];
}
return license
.map((l) => {
let licenseContent = {};
if (typeof l === "string" || l instanceof String) {
if (
spdxLicenses.some((v) => {
return l === v;
})
) {
licenseContent.id = l;
licenseContent.url = "https://opensource.org/licenses/" + l;
} else if (l.startsWith("http")) {
if (!l.includes("opensource.org")) {
licenseContent.name = "CUSTOM";
}
if (l.includes("mit-license")) {
licenseContent.id = "MIT";
}
licenseContent.url = l;
} else {
licenseContent.name = l;
}
} else if (Object.keys(l).length) {
licenseContent = l;
} else {
return [];
}
if (!licenseContent.id) {
addLicenseText(pkg, l, licenseContent, format);
}
return licenseContent;
})
.map((l) => ({ license: l }));
}
return [];
}
exports.getLicenses = getLicenses;
/**
* Tries to find a file containing the license text based on commonly
* used naming and content types. If a candidate file is found, add
* the text to the license text object and stop.
*/
function addLicenseText(pkg, l, licenseContent, format = "xml") {
let licenseFilenames = [
"LICENSE",
"License",
"license",
"LICENCE",
"Licence",
"licence",
"NOTICE",
"Notice",
"notice",
];
let licenseContentTypes = {
"text/plain": "",
"text/txt": ".txt",
"text/markdown": ".md",
"text/xml": ".xml",
};
/* Loops over different name combinations starting from the license specified
naming (e.g., 'LICENSE.Apache-2.0') and proceeding towards more generic names. */
for (const licenseName of [`.${l}`, ""]) {
for (const licenseFilename of licenseFilenames) {
for (const [licenseContentType, fileExtension] of Object.entries(
licenseContentTypes
)) {
let licenseFilepath = `${pkg.realPath}/${licenseFilename}${licenseName}${fileExtension}`;
if (fs.existsSync(licenseFilepath)) {
licenseContent.text = readLicenseText(
licenseFilepath,
licenseContentType,
format
);
return;
}
}
}
}
}
/**
* Read the file from the given path to the license text object and includes
* content-type attribute, if not default. Returns the license text object.
*/
function readLicenseText(licenseFilepath, licenseContentType, format = "xml") {
let licenseText = fs.readFileSync(licenseFilepath, "utf8");
if (licenseText) {
if (format === "xml") {
let licenseContentText = { "#cdata": licenseText };
if (licenseContentType !== "text/plain") {
licenseContentText["@content-type"] = licenseContentType;
}
return licenseContentText;
} else {
let licenseContentText = { content: licenseText };
if (licenseContentType !== "text/plain") {
licenseContentText["contentType"] = licenseContentType;
}
return licenseContentText;
}
}
return null;
}
/**
* Method to retrieve metadata for npm packages by querying npmjs
*
* @param {Array} pkgList Package list
*/
const getNpmMetadata = async function (pkgList) {
const NPM_URL = "https://registry.npmjs.org/";
const cdepList = [];
for (const p of pkgList) {
try {
let key = p.name;
if (p.group && p.group !== "") {
let group = p.group;
if (!group.startsWith("@")) {
group = "@" + group;
}
key = group + "/" + p.name;
}
let body = {};
if (metadata_cache[key]) {
body = metadata_cache[key];
} else {
const res = await got.get(NPM_URL + key, {
responseType: "json",
});
body = res.body;
metadata_cache[key] = body;
}
p.description = body.description;
p.license = body.license;
if (body.repository && body.repository.url) {
p.repository = { url: body.repository.url };
}
if (body.homepage) {
p.homepage = { url: body.homepage };
}
cdepList.push(p);
} catch (err) {
cdepList.push(p);
if (DEBUG_MODE) {
console.error(err, p);
}
}
}
return cdepList;
};
exports.getNpmMetadata = getNpmMetadata;
const _getDepPkgList = async function (pkgList, pkg) {
if (pkg && pkg.dependencies) {
const pkgKeys = Object.keys(pkg.dependencies);
for (var k in pkgKeys) {
const name = pkgKeys[k];
pkgList.push({
name: name,
version: pkg.dependencies[name].version,
_integrity: pkg.dependencies[name].integrity,
});
// Include child dependencies
if (pkg.dependencies[name].dependencies) {
await _getDepPkgList(pkgList, pkg.dependencies[name]);
}
}
}
if (process.env.FETCH_LICENSE) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
/**
* Parse nodejs package json file
*
* @param {string} pkgJsonFile package.json file
*/
const parsePkgJson = async (pkgJsonFile) => {
const pkgList = [];
if (fs.existsSync(pkgJsonFile)) {
try {
const pkgData = JSON.parse(fs.readFileSync(pkgJsonFile, "utf8"));
const pkgIdentifier = parsePackageJsonName(pkgData.name);
pkgList.push({
name: pkgIdentifier.fullName || pkgData.name,
group: pkgIdentifier.scope || "",
version: pkgData.version,
});
} catch (err) {}
}
if (process.env.FETCH_LICENSE) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
exports.parsePkgJson = parsePkgJson;
/**
* Parse nodejs package lock file
*
* @param {string} pkgLockFile package-lock.json file
*/
const parsePkgLock = async (pkgLockFile) => {
const pkgList = [];
if (fs.existsSync(pkgLockFile)) {
const lockData = JSON.parse(fs.readFileSync(pkgLockFile, "utf8"));
return await _getDepPkgList(pkgList, lockData);
}
return pkgList;
};
exports.parsePkgLock = parsePkgLock;
/**
* Parse nodejs yarn lock file
*
* @param {string} yarnLockFile yarn.lock file
*/
const parseYarnLock = async function (yarnLockFile) {
const pkgList = [];
if (fs.existsSync(yarnLockFile)) {
const lockData = fs.readFileSync(yarnLockFile, "utf8");
let name = "";
let group = "";
let version = "";
let integrity = "";
lockData.split("\n").forEach((l) => {
if (
l === "\n" ||
l.startsWith("dependencies") ||
l.startsWith(" ") ||
l.startsWith("#")
) {
return;
}
if (!l.startsWith(" ")) {
const tmpA = l.replace(/["']/g, "").split("@");
// ignore possible leading empty strings
if (tmpA[0] === "") {
tmpA.shift();
}
if (tmpA.length >= 2) {
const fullName = tmpA[0];
if (fullName.indexOf("/") > -1) {
const parts = fullName.split("/");
group = parts[0];
name = parts[1];
} else {
name = fullName;
}
}
} else {
l = l.trim();
const parts = l.split(" ");
if (l.startsWith("version")) {
version = parts[1].replace(/"/g, "");
}
if (l.startsWith("integrity")) {
integrity = parts[1];
}
// checksum used by yarn 2/3 is hex encoded
if (l.startsWith("checksum")) {
integrity =
"sha512-" + Buffer.from(parts[1], "hex").toString("base64");
}
if (l.startsWith("resolved")) {
const tmpB = parts[1].split("#");
if (tmpB.length > 1) {
const digest = tmpB[1].replace(/"/g, "");
integrity = "sha256-" + digest;
}
}
}
if (name !== "" && version !== "" && integrity != "") {
pkgList.push({
group: group,
name: name,
version: version,
_integrity: integrity,
});
group = "";
name = "";
version = "";
integrity = "";
}
});
}
if (process.env.FETCH_LICENSE) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
exports.parseYarnLock = parseYarnLock;
/**
* Parse nodejs shrinkwrap deps file
*
* @param {string} swFile shrinkwrap-deps.json file
*/
const parseNodeShrinkwrap = async function (swFile) {
const pkgList = [];
if (fs.existsSync(swFile)) {
const lockData = JSON.parse(fs.readFileSync(swFile, "utf8"));
const pkgKeys = Object.keys(lockData);
for (var k in pkgKeys) {
const fullName = pkgKeys[k];
const integrity = lockData[fullName];
const parts = fullName.split("@");
if (parts && parts.length) {
let name = "";
let version = "";
let group = "";
if (parts.length === 2) {
name = parts[0];
version = parts[1];
} else if (parts.length === 3) {
if (parts[0] === "") {
let gnameparts = parts[1].split("/");
group = gnameparts[0];
name = gnameparts[1];
} else {
name = parts[0];
}
version = parts[2];
}
if (group !== "@types") {
pkgList.push({
group: group,
name: name,
version: version,
_integrity: integrity,
});
}
}
}
}
if (process.env.FETCH_LICENSE) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
exports.parseNodeShrinkwrap = parseNodeShrinkwrap;
/**
* Parse nodejs pnpm lock file
*
* @param {string} pnpmLock pnpm-lock.yaml file
*/
const parsePnpmLock = async function (pnpmLock) {
const pkgList = [];
if (fs.existsSync(pnpmLock)) {
const lockData = fs.readFileSync(pnpmLock, "utf8");
const yamlObj = yaml.load(lockData);
if (!yamlObj) {
return pkgList;
}
const packages = yamlObj.packages;
const pkgKeys = Object.keys(packages);
for (var k in pkgKeys) {
// Eg: @babel/code-frame/7.10.1
const fullName = pkgKeys[k].replace("/@", "@");
const parts = fullName.split("/");
const integrity = packages[pkgKeys[k]].resolution.integrity;
let scope = packages[pkgKeys[k]].dev === true ? "optional" : undefined;
if (parts && parts.length) {
let name = "";
let version = "";
let group = "";
if (parts.length === 2) {
name = parts[0];
version = parts[1];
} else if (parts.length === 3) {
group = parts[0];
name = parts[1];
version = parts[2];
}
if (group !== "@types" && name.indexOf("file:") !== 0) {
pkgList.push({
group: group,
name: name,
version: version,
scope,
_integrity: integrity,
});
}
}
}
}
if (process.env.FETCH_LICENSE) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
exports.parsePnpmLock = parsePnpmLock;
/**
* Parse bower json file
*
* @param {string} bowerJsonFile bower.json file
*/
const parseBowerJson = async (bowerJsonFile) => {
const pkgList = [];
if (fs.existsSync(bowerJsonFile)) {
try {
const pkgData = JSON.parse(fs.readFileSync(bowerJsonFile, "utf8"));
const pkgIdentifier = parsePackageJsonName(pkgData.name);
pkgList.push({
name: pkgIdentifier.fullName || pkgData.name,
group: pkgIdentifier.scope || "",
version: pkgData.version || "",
description: pkgData.description || "",
license: pkgData.license || "",
});
} catch (err) {}
}
if (process.env.FETCH_LICENSE) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
exports.parseBowerJson = parseBowerJson;
/**
* Parse minified js file
*
* @param {string} minJsFile min.js file
*/
const parseMinJs = async (minJsFile) => {
const pkgList = [];
if (fs.existsSync(minJsFile)) {
try {
const rawData = fs.readFileSync(minJsFile, { encoding: "utf-8" });
const tmpA = rawData.split("\n");
tmpA.forEach((l) => {
if ((l.startsWith("/*!") || l.startsWith(" * ")) && l.length < 500) {
let delimiter = " * ";
if (!l.includes(delimiter) && l.includes("/*!")) {
delimiter = "/*!";
}
if (!l.includes(delimiter) && l.includes(" - ")) {
delimiter = " - ";
}
const tmpPV = l.split(delimiter);
if (!tmpPV || tmpPV.length < 2) {
return;
}
// Eg: jQuery v3.6.0
const pkgNameVer = tmpPV[1]
.replace("/*!", "")
.replace(" * ", "")
.trim();
const tmpB = pkgNameVer.includes(" - ")
? pkgNameVer.split(" - ")
: pkgNameVer.split(" ");
if (tmpB && tmpB.length > 1) {
let name = tmpB[0].replace(/ /g, "-").trim();
if (
["copyright", "author", "licensed"].includes(name.toLowerCase())
) {
return;
}
const pkgIdentifier = parsePackageJsonName(name);
pkgList.push({
name: pkgIdentifier.fullName || pkgData.name,
group: pkgIdentifier.scope || "",
version: tmpB[1].replace(/^v/, "") || "",
});
return;
}
}
});
} catch (err) {}
}
if (process.env.FETCH_LICENSE) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
exports.parseMinJs = parseMinJs;
/**
* Parse pom file
*
* @param {string} pom file to parse
*/
const parsePom = function (pomFile) {
const deps = [];
const xmlData = fs.readFileSync(pomFile);
const project = convert.xml2js(xmlData, {
compact: true,
spaces: 4,
textKey: "_",
attributesKey: "$",
commentKey: "value",
}).project;
if (project && project.dependencies) {
let dependencies = project.dependencies.dependency;
// Convert to an array
if (dependencies && !Array.isArray(dependencies)) {
dependencies = [dependencies];
}
for (let adep of dependencies) {
const version = adep.version;
let versionStr = undefined;
if (version && version._ && version._.indexOf("$") == -1) {
versionStr = version._;
deps.push({
group: adep.groupId ? adep.groupId._ : "",
name: adep.artifactId ? adep.artifactId._ : "",
version: versionStr,
qualifiers: { type: "jar" },
});
}
}
}
return deps;
};
exports.parsePom = parsePom;
/**
* Parse maven tree output
* @param {string} rawOutput Raw string output
*/
const parseMavenTree = function (rawOutput) {
if (!rawOutput) {
return [];
}
const deps = [];
const keys_cache = {};
const tmpA = rawOutput.split("\n");
tmpA.forEach((l) => {
const tmpline = l.split(" ");
if (tmpline && tmpline.length) {
l = tmpline[tmpline.length - 1];
const pkgArr = l.split(":");
if (pkgArr && pkgArr.length > 2) {
let versionStr = pkgArr[pkgArr.length - 2];
if (pkgArr.length == 4) {
versionStr = pkgArr[pkgArr.length - 1];
}
const key = pkgArr[0] + "-" + pkgArr[1] + "-" + versionStr;
if (!keys_cache[key]) {
keys_cache[key] = key;
deps.push({
group: pkgArr[0],
name: pkgArr[1],
version: versionStr,
qualifiers: { type: "jar" },
});
}
}
}
});
return deps;
};
exports.parseMavenTree = parseMavenTree;
/**
* Parse gradle dependencies output
* @param {string} rawOutput Raw string output
*/
const parseGradleDep = function (rawOutput) {
if (typeof rawOutput === "string") {
const deps = [];
const keys_cache = {};
const tmpA = rawOutput.split("\n");
tmpA.forEach((l) => {
if (l.indexOf("--- ") >= 0) {
l = l.substr(l.indexOf("--- ") + 4, l.length).trim();
l = l.replace(" (*)", "");
const verArr = l.split(":");
if (verArr && verArr.length === 3) {
let versionStr = verArr[2];
if (versionStr.indexOf("->") >= 0) {
versionStr = versionStr
.substr(versionStr.indexOf("->") + 3, versionStr.length)
.trim();
}
versionStr = versionStr.split(" ")[0];
const key = verArr[0] + "-" + verArr[1] + "-" + versionStr;
// Filter duplicates
if (!keys_cache[key]) {
keys_cache[key] = key;
const group = verArr[0].trim();
if (group !== "project") {
deps.push({
group,
name: verArr[1].trim(),
version: versionStr,
qualifiers: { type: "jar" },
});
}
}
}
}
});
return deps;
}
return [];
};
exports.parseGradleDep = parseGradleDep;
/**
* Parse clojure cli dependencies output
* @param {string} rawOutput Raw string output
*/
const parseCljDep = function (rawOutput) {
if (typeof rawOutput === "string") {
const deps = [];
const keys_cache = {};
const tmpA = rawOutput.split("\n");
tmpA.forEach((l) => {
l = l.trim();
if (!l.startsWith("Downloading") || !l.startsWith("X ")) {
if (l.startsWith(". ")) {
l = l.replace(". ", "");
}
const tmpArr = l.split(" ");
if (tmpArr.length == 2) {
let group = path.dirname(tmpArr[0]);
if (group === ".") {
group = "";
}
const name = path.basename(tmpArr[0]);
const version = tmpArr[1];
const cacheKey = group + "-" + name + "-" + version;
if (!keys_cache[cacheKey]) {
keys_cache[cacheKey] = true;
deps.push({
group,
name,
version,
});
}
}
}
});
return deps;
}
return [];
};
exports.parseCljDep = parseCljDep;
/**
* Parse lein dependency tree output
* @param {string} rawOutput Raw string output
*/
const parseLeinDep = function (rawOutput) {
if (typeof rawOutput === "string") {
const deps = [];
const keys_cache = {};
const tmpA = rawOutput.split("\n");
if (rawOutput.includes("{[") && !rawOutput.startsWith("{[")) {
rawOutput = "{[" + rawOutput.split("{[")[1];
}
const ednData = ednDataLib.parseEDNString(rawOutput);
return parseLeinMap(ednData, keys_cache, deps);
}
return [];
};
exports.parseLeinDep = parseLeinDep;
const parseLeinMap = function (node, keys_cache, deps) {
if (node["map"]) {
for (let n of node["map"]) {
if (n.length === 2) {
const rootNode = n[0];
let psym = rootNode[0].sym;
let version = rootNode[1];
let group = path.dirname(psym);
if (group === ".") {
group = "";
}
let name = path.basename(psym);
let cacheKey = group + "-" + name + "-" + version;
if (!keys_cache[cacheKey]) {
keys_cache[cacheKey] = true;
deps.push({ group, name, version });
}
if (n[1]) {
parseLeinMap(n[1], keys_cache, deps);
}
}
}
}
return deps;
};
exports.parseLeinMap = parseLeinMap;
/**
* Parse gradle projects output
* @param {string} rawOutput Raw string output
*/
const parseGradleProjects = function (rawOutput) {
if (typeof rawOutput === "string") {
const projects = [];
const tmpA = rawOutput.split("\n");
tmpA.forEach((l) => {
if (l.startsWith("+--- Project") || l.startsWith("\\--- Project")) {
let projName = l
.replace("+--- Project ", "")
.replace("\\--- Project ", "")
.split(" ")[0];
projName = projName.replace(/'/g, "");
if (
!projName.startsWith(":test") &&
!projName.startsWith(":docs") &&
!projName.startsWith(":qa")
) {
projects.push(projName);
}
}
});
return projects;
}
return [];
};
exports.parseGradleProjects = parseGradleProjects;
/**
* Parse bazel skyframe state output
* @param {string} rawOutput Raw string output
*/
const parseBazelSkyframe = function (rawOutput) {
if (typeof rawOutput === "string") {
const deps = [];
const keys_cache = {};
const tmpA = rawOutput.split("\n");
tmpA.forEach((l) => {
if (l.indexOf("external/maven") >= 0) {
l = l.replace("arguments: ", "").replace(/\"/g, "");
// Skyframe could have duplicate entries
if (l.includes("@@maven//")) {
l = l.split(",")[0];
}
const mparts = l.split("external/maven/v1/");
if (mparts && mparts[mparts.length - 1].endsWith(".jar")) {
// Example
// https/jcenter.bintray.com/com/google/guava/failureaccess/1.0.1/failureaccess-1.0.1.jar
const jarPath = mparts[mparts.length - 1];
let jarPathParts = jarPath.split("/");
if (jarPathParts.length) {
// Remove the protocol, registry url and then file name
jarPathParts = jarPathParts.slice(2, -1);
// The last part would be the version
const version = jarPathParts[jarPathParts.length - 1];
// Last but one would be the name
const name = jarPathParts[jarPathParts.length - 2].toLowerCase();
// Rest would be the group
const group = jarPathParts.slice(0, -2).join(".").toLowerCase();
const key = `${group}:${name}:${version}`;
if (!keys_cache[key]) {
keys_cache[key] = true;
deps.push({
group,
name,
version,
qualifiers: { type: "jar" },
});
}
}
}
}
});
return deps;
}
return [];
};
exports.parseBazelSkyframe = parseBazelSkyframe;
/**
* Parse bazel BUILD file
* @param {string} rawOutput Raw string output
*/
const parseBazelBuild = function (rawOutput) {
if (typeof rawOutput === "string") {
const projs = [];
const keys_cache = {};
const tmpA = rawOutput.split("\n");
tmpA.forEach((l) => {
if (l.includes("name =")) {
const name = l
.split("name =")[1]
.replace(/[\","]/g, "")
.trim();
if (!name.includes("test")) {
projs.push(name);
}
}
});
return projs;
}
return [];
};
exports.parseBazelBuild = parseBazelBuild;
/**
* Parse dependencies in Key:Value format
*/
const parseKVDep = function (rawOutput) {
if (typeof rawOutput === "string") {
const deps = [];
rawOutput.split("\n").forEach((l) => {
const tmpA = l.split(":");
if (tmpA.length === 3) {
deps.push({
group: tmpA[0],
name: tmpA[1],
version: tmpA[2],
qualifiers: { type: "jar" },
});
} else if (tmpA.length === 2) {
deps.push({
group: "",
name: tmpA[0],
version: tmpA[1],
qualifiers: { type: "jar" },
});
}
});
return deps;
}
return [];
};
exports.parseKVDep = parseKVDep;
/**
* Method to find the spdx license id from name
*
* @param {string} name License full name
*/
const findLicenseId = function (name) {
for (let l of licenseMapping) {
if (l.names.includes(name)) {
return l.exp;
}
}
return name && (name.includes("\n") || name.length > MAX_LICENSE_ID_LENGTH)
? guessLicenseId(name)
: name;
};
exports.findLicenseId = findLicenseId;
/**
* Method to guess the spdx license id from license contents
*
* @param {string} name License file contents
*/
const guessLicenseId = function (content) {
content = content.replace(/\n/g, " ");
for (let l of licenseMapping) {
for (let j in l.names) {
if (content.toUpperCase().indexOf(l.names[j].toUpperCase()) > -1) {
return l.exp;
}
}
}
return undefined;
};
exports.guessLicenseId = guessLicenseId;
/**
* Method to retrieve metadata for maven packages by querying maven central
*
* @param {Array} pkgList Package list
*/
const getMvnMetadata = async function (pkgList) {
const MAVEN_CENTRAL_URL = "https://repo1.maven.org/maven2/";
const ANDROID_MAVEN = "https://maven.google.com/";
const JCENTER_MAVEN = "https://jcenter.bintray.com/";
const cdepList = [];
if (!pkgList || !pkgList.length) {
return pkgList;
}
if (DEBUG_MODE) {
console.log(`About to query maven for ${pkgList.length} packages`);
}
for (const p of pkgList) {
// If the package already has key metadata skip querying maven
if (p.group && p.name && p.version && !process.env.FETCH_LICENSE) {
cdepList.push(p);
continue;
}
let urlPrefix = MAVEN_CENTRAL_URL;