misc.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. import { appendArrayInPlace } from 'foxts/append-array-in-place';
  6. export type MaybePromise<T> = T | Promise<T>;
  7. interface Write {
  8. (
  9. destination: string,
  10. input: NodeJS.TypedArray | string,
  11. ): Promise<void>
  12. }
  13. export type VoidOrVoidArray = void | VoidOrVoidArray[];
  14. export function mkdirp(dir: string) {
  15. if (fs.existsSync(dir)) {
  16. return;
  17. }
  18. return fsp.mkdir(dir, { recursive: true });
  19. }
  20. export const writeFile: Write = async (destination: string, input, dir = dirname(destination)): Promise<void> => {
  21. const p = mkdirp(dir);
  22. if (p) {
  23. await p;
  24. }
  25. return fsp.writeFile(destination, input, { encoding: 'utf-8' });
  26. };
  27. export function withBannerArray(title: string, description: string[] | readonly string[], date: Date, content: string[]) {
  28. const result: string[] = [
  29. '#########################################',
  30. `# ${title}`,
  31. `# Last Updated: ${date.toISOString()}`,
  32. `# Size: ${content.length}`
  33. ];
  34. appendArrayInPlace(result, description.map(line => (line ? `# ${line}` : '#')));
  35. result.push('#########################################');
  36. appendArrayInPlace(result, content);
  37. result.push('################## EOF ##################');
  38. return result;
  39. };
  40. export function notSupported(name: string) {
  41. return (...args: unknown[]) => {
  42. console.error(`${name}: not supported.`, args);
  43. throw new Error(`${name}: not implemented.`);
  44. };
  45. }
  46. export function withIdentityContent(title: string, description: string[] | readonly string[], date: Date, content: string[]) {
  47. return content;
  48. };
  49. export function isDirectoryEmptySync(path: PathLike) {
  50. const directoryHandle = fs.opendirSync(path);
  51. try {
  52. return directoryHandle.readSync() === null;
  53. } finally {
  54. directoryHandle.closeSync();
  55. }
  56. }