-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsarifLoader.js
More file actions
84 lines (75 loc) · 2.14 KB
/
sarifLoader.js
File metadata and controls
84 lines (75 loc) · 2.14 KB
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
"use strict";
const fs = require('fs').promises;
const _glob = require('glob');
const path = require('path');
const glob = _glob.globSync;
const logger = require('./logger');
const regex = new RegExp(/\.sarif$/, 'i');
async function getPathType(path) {
try {
const fileStat = await fs.stat(path);
if (fileStat.isDirectory()) {
return 'directory';
}
else if (fileStat.isFile()) {
return 'file';
}
else {
return 'glob';
}
}
catch(e) {
console.error('Error', e);
// must be glob path
return 'glob';
}
}
async function getDirectoryFiles(inDirPath) {
const dirents = await fs.readdir(inDirPath, { withFileTypes: true });
const files = await Promise.all(dirents.map((dirent) => {
const direntPath = path.resolve(inDirPath, dirent.name);
return dirent.isDirectory() ? getDirectoryFiles(direntPath) : direntPath;
}));
return files.flat(100);
}
async function loadFile(inFilePath) {
logger.debug(`Loading file: ${inFilePath}`);
const sarifText = await fs.readFile(inFilePath, 'utf-8');
const sarif = JSON.parse(sarifText);
return sarif;
}
async function load(inFilePath) {
try {
const fileStat = await fs.stat(inFilePath);
if (fileStat.isDirectory()) {
const files = await getDirectoryFiles(inFilePath);
const result = await Promise.all(files.filter(file => {
return regex.test(file);
}).map(async (file) => {
return loadFile(file);
}));
return result;
}
else if (fileStat.isFile()) {
return [
await loadFile(inFilePath)
];
}
else {
throw new Error();
}
}
catch(e) {
console.error('Error', e);
// else assume glob or wildcard expression
const globFiles = await glob(inFilePath);
const result = await Promise.all(globFiles.map(async (file) => {
return loadFile(file);
}));
return result;
}
}
module.exports = {
getPathType,
load
};