51 lines
1.1 KiB
TypeScript
51 lines
1.1 KiB
TypeScript
|
import chalk from "chalk";
|
||
|
import fs from "fs";
|
||
|
import json5 from "json5";
|
||
|
|
||
|
export interface ErrorWithCode {
|
||
|
code: string;
|
||
|
}
|
||
|
|
||
|
export const convertCamelToUpperSnakeCase = (str: string) =>
|
||
|
str.replace(/[A-Z]/g, (letter) => `_${letter}`).toUpperCase();
|
||
|
|
||
|
export const getTime = () => {
|
||
|
const now = new Date(),
|
||
|
tzo = -now.getTimezoneOffset(),
|
||
|
dif = tzo >= 0 ? "+" : "-",
|
||
|
pad = (num: number) => {
|
||
|
const norm = Math.floor(Math.abs(num));
|
||
|
return `${norm < 10 ? "0" : ""}${norm}`;
|
||
|
};
|
||
|
return [
|
||
|
now.getFullYear(),
|
||
|
"-",
|
||
|
pad(now.getMonth() + 1),
|
||
|
"-",
|
||
|
pad(now.getDate()),
|
||
|
"T",
|
||
|
pad(now.getHours()),
|
||
|
":",
|
||
|
pad(now.getMinutes()),
|
||
|
":",
|
||
|
pad(now.getSeconds()),
|
||
|
dif,
|
||
|
pad(tzo / 60),
|
||
|
":",
|
||
|
pad(tzo % 60),
|
||
|
].join("");
|
||
|
};
|
||
|
|
||
|
export const log = (...msg: unknown[]) =>
|
||
|
console.log(`${chalk.grey(`${getTime()}:`)} ${msg}`);
|
||
|
|
||
|
export const readJsonIfExists = (filePath: string | URL) => {
|
||
|
try {
|
||
|
return json5.parse(fs.readFileSync(filePath, { encoding: "utf8" }));
|
||
|
} catch (err) {
|
||
|
// if no file, return empty object
|
||
|
if ((err as ErrorWithCode)?.code === "ENOENT") return {};
|
||
|
throw err;
|
||
|
}
|
||
|
};
|