forked from neume-network/strategies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisc.mjs
63 lines (53 loc) · 1.62 KB
/
disc.mjs
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
// @format
import { constants, statSync } from "fs";
import { readdir, stat, appendFile, access } from "fs/promises";
import { resolve, dirname, basename } from "path";
import { fileURLToPath } from "url";
import logger from "./logger.mjs";
const log = logger("disc");
const __dirname = dirname(fileURLToPath(import.meta.url));
const strategyDir = "./strategies";
export async function fileExists(filePath) {
try {
await access(filePath);
return true;
} catch (e) {
return false;
}
}
export async function loadStrategies(pathTip, fileName) {
const strategyDir = resolve(__dirname, pathTip);
const strategies = await getdirdirs(strategyDir);
return await loadAll(strategies, fileName);
}
export async function loadAll(paths, filename) {
const pImports = paths.map(
async (path) => await import(resolve(path, filename))
);
const results = await Promise.allSettled(pImports);
return results
.filter((result, i) => {
if (result.status === "rejected") {
log(`Rejected loading strategy with reason: "${result.reason}"`);
return false;
} else {
return true;
}
})
.map(({ value }, i) => ({ module: value }));
}
export async function getdirdirs(path) {
const directories = await readdir(path);
return directories
.filter((file) => statSync(resolve(path, file)).isDirectory())
.map((file) => resolve(path, file));
}
export function toCSV(list) {
return list.map((entry) => Object.values(entry).join(",")).join("\n");
}
export function toJSON(list, expr) {
return list.map((entry) => {
const match = expr.exec(entry);
return match.groups;
});
}