2021-05-04 17:04:14 +02:00
|
|
|
import {promises as fs} from "fs";
|
2021-03-24 21:41:13 +01:00
|
|
|
import path from "path";
|
|
|
|
|
2020-04-22 15:52:17 +02:00
|
|
|
export async function sleep(ms: number): Promise<void> {
|
|
|
|
return await new Promise(resolve => {
|
|
|
|
setTimeout(() => resolve(), ms);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export abstract class WrappingError extends Error {
|
|
|
|
public readonly cause?: Error;
|
|
|
|
|
|
|
|
protected constructor(message: string, cause?: Error) {
|
|
|
|
super(message);
|
|
|
|
this.cause = cause;
|
|
|
|
|
|
|
|
if (cause !== undefined) {
|
|
|
|
this.stack = (this.stack || '') + `\n> Caused by: ${cause.stack}`;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
public get name(): string {
|
2020-04-22 15:52:17 +02:00
|
|
|
return this.constructor.name;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
export type Type<T> = { new(...args: never[]): T };
|
2020-07-24 15:40:10 +02:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
export function bufferToUuid(buffer: Buffer): string {
|
2020-07-24 15:40:10 +02:00
|
|
|
const chars = buffer.toString('hex');
|
|
|
|
let out = '';
|
|
|
|
let i = 0;
|
|
|
|
for (const l of [8, 4, 4, 4, 12]) {
|
|
|
|
if (i > 0) out += '-';
|
|
|
|
out += chars.substr(i, l);
|
|
|
|
i += l;
|
|
|
|
}
|
|
|
|
return out;
|
|
|
|
}
|
2020-07-26 11:37:01 +02:00
|
|
|
|
2020-09-25 23:42:15 +02:00
|
|
|
export function getMethods<T extends { [p: string]: unknown }>(obj: T): string[] {
|
|
|
|
const properties = new Set<string>();
|
|
|
|
let currentObj: T | unknown = obj;
|
2020-07-26 11:37:01 +02:00
|
|
|
do {
|
2020-09-25 23:42:15 +02:00
|
|
|
Object.getOwnPropertyNames(currentObj).map(item => properties.add(item));
|
|
|
|
currentObj = Object.getPrototypeOf(currentObj);
|
|
|
|
} while (currentObj);
|
|
|
|
return [...properties.keys()].filter(item => typeof obj[item] === 'function');
|
2020-07-26 11:37:01 +02:00
|
|
|
}
|
2021-03-24 21:41:13 +01:00
|
|
|
|
2021-05-04 17:04:14 +02:00
|
|
|
export async function listFilesRecursively(dir: string): Promise<string[]> {
|
|
|
|
const localFiles = await fs.readdir(dir);
|
|
|
|
const files: string[] = [];
|
|
|
|
for (const file of localFiles.map(file => path.join(dir, file))) {
|
|
|
|
const stat = await fs.stat(file);
|
2021-03-24 21:41:13 +01:00
|
|
|
|
2021-05-04 17:04:14 +02:00
|
|
|
if (stat.isDirectory()) {
|
|
|
|
files.push(...await listFilesRecursively(file));
|
|
|
|
} else {
|
|
|
|
files.push(file);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return files;
|
|
|
|
}
|
2021-03-24 21:41:13 +01:00
|
|
|
|
|
|
|
|
2021-05-04 17:04:14 +02:00
|
|
|
export async function doesFileExist(file: string): Promise<boolean> {
|
|
|
|
try {
|
|
|
|
await fs.stat(file);
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'ENOENT') {
|
|
|
|
return false;
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
2021-03-24 21:41:13 +01:00
|
|
|
}
|