multi-downloader-nx_mirror/modules/module.helper.ts
2025-10-11 00:18:55 +02:00

85 lines
2.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Helper functions
import readline from 'readline/promises';
import { stdin as input, stdout as output } from 'process';
import childProcess from 'child_process';
import { console } from './log';
export default class Helper {
static async question(q: string) {
const rl = readline.createInterface({ input, output });
const a = await rl.question(q);
rl.close();
return a;
}
static formatTime(t: number) {
const days = Math.floor(t / 86400);
const hours = Math.floor((t % 86400) / 3600);
const minutes = Math.floor(((t % 86400) % 3600) / 60);
const seconds = +(t % 60).toFixed(0);
const daysS = days > 0 ? `${days}d` : '';
const hoursS = daysS || hours ? `${daysS}${daysS && hours < 10 ? '0' : ''}${hours}h` : '';
const minutesS = minutes || hoursS ? `${hoursS}${hoursS && minutes < 10 ? '0' : ''}${minutes}m` : '';
const secondsS = `${minutesS}${minutesS && seconds < 10 ? '0' : ''}${seconds}s`;
return secondsS;
}
static cleanupFilename(n: string) {
/* eslint-disable no-useless-escape, no-control-regex */
// Smart Replacer
const rep: Record<string, string> = {
'/': '',
'\\': '',
':': '',
'*': '',
'?': '',
'"': "'",
'<': '',
'>': ''
};
n = n.replace(/[\/\\:\*\?"<>\|]/g, (ch) => rep[ch] || '_');
// Old Replacer
const controlRe = /[\x00-\x1f\x80-\x9f]/g;
const reservedRe = /^\.+$/;
const windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
const windowsTrailingRe = /[\. ]+$/;
return n.replace(controlRe, '_').replace(reservedRe, '_').replace(windowsReservedRe, '_').replace(windowsTrailingRe, '_');
}
static exec(
pname: string,
fpath: string,
pargs: string,
spc = false
):
| {
isOk: true;
}
| {
isOk: false;
err: Error & { code: number };
} {
pargs = pargs ? ' ' + pargs : '';
console.info(`\n> "${pname}"${pargs}${spc ? '\n' : ''}`);
try {
if (process.platform === 'win32') {
childProcess.execSync('& ' + fpath + pargs, { stdio: 'inherit', shell: 'powershell.exe', windowsHide: true });
} else {
childProcess.execSync(fpath + pargs, { stdio: 'inherit' });
}
return {
isOk: true
};
} catch (er) {
const err = er as Error & { status: number };
return {
isOk: false,
err: {
...err,
code: err.status
}
};
}
}
}