misc.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { dirname } from 'node:path';
  2. import fs from 'node:fs';
  3. import type { PathLike } from 'node:fs';
  4. import fsp from 'node:fs/promises';
  5. export type MaybePromise<T> = T | Promise<T>;
  6. export function fastStringCompare(a: string, b: string) {
  7. const lenA = a.length;
  8. const lenB = b.length;
  9. const minLen = lenA < lenB ? lenA : lenB;
  10. for (let i = 0; i < minLen; ++i) {
  11. const ca = a.charCodeAt(i);
  12. const cb = b.charCodeAt(i);
  13. if (ca > cb) return 1;
  14. if (ca < cb) return -1;
  15. }
  16. if (lenA === lenB) {
  17. return 0;
  18. }
  19. return lenA > lenB ? 1 : -1;
  20. };
  21. interface Write {
  22. (
  23. destination: string,
  24. input: NodeJS.TypedArray | string,
  25. ): Promise<void>
  26. }
  27. export type VoidOrVoidArray = void | VoidOrVoidArray[];
  28. export function mkdirp(dir: string) {
  29. if (fs.existsSync(dir)) {
  30. return;
  31. }
  32. return fsp.mkdir(dir, { recursive: true });
  33. }
  34. export const writeFile: Write = async (destination: string, input, dir = dirname(destination)): Promise<void> => {
  35. const p = mkdirp(dir);
  36. if (p) {
  37. await p;
  38. }
  39. return fsp.writeFile(destination, input, { encoding: 'utf-8' });
  40. };
  41. export const removeFiles = async (files: string[]) => Promise.all(files.map((file) => fsp.rm(file, { force: true })));
  42. export function withBannerArray(title: string, description: string[] | readonly string[], date: Date, content: string[]) {
  43. return [
  44. '#########################################',
  45. `# ${title}`,
  46. `# Last Updated: ${date.toISOString()}`,
  47. `# Size: ${content.length}`,
  48. ...description.map(line => (line ? `# ${line}` : '#')),
  49. '#########################################',
  50. ...content,
  51. '################## EOF ##################'
  52. ];
  53. };
  54. export function notSupported(name: string) {
  55. return (...args: unknown[]) => {
  56. console.error(`${name}: not supported.`, args);
  57. throw new Error(`${name}: not implemented.`);
  58. };
  59. }
  60. export function withIdentityContent(title: string, description: string[] | readonly string[], date: Date, content: string[]) {
  61. return content;
  62. };
  63. export function isDirectoryEmptySync(path: PathLike) {
  64. const directoryHandle = fs.opendirSync(path);
  65. try {
  66. return directoryHandle.readSync() === null;
  67. } finally {
  68. directoryHandle.closeSync();
  69. }
  70. }
  71. export function fastIpVersion(ip: string) {
  72. return ip.includes(':') ? 6 : (ip.includes('.') ? 4 : 0);
  73. }