| 1 | import { randomUUID } from "crypto"; |
| 2 | import fs from "fs"; |
| 3 | import { mkdir, rm } from "fs/promises"; |
| 4 | import path from "path"; |
| 5 | import { exec as execCallback } from "child_process"; |
| 6 | import { File, Blob } from "node-fetch"; |
| 7 | import { ValidationError, ValidationErrorEnum } from "./errors.js"; |
| 8 | |
| 9 | export async function exec(cmd: string): Promise<string> { |
| 10 | return new Promise((resolve, reject) => { |
| 11 | execCallback(cmd, (error, stdout, stderr) => { |
| 12 | if (error) { |
| 13 | reject(error); |
| 14 | } |
| 15 | resolve(stdout || stderr); |
| 16 | }); |
| 17 | }); |
| 18 | } |
| 19 | |
| 20 | export function validateSpecName(name: string) { |
| 21 | if (name.includes(" ")) { |
| 22 | throw new ValidationError(ValidationErrorEnum.nameWithSpace); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | export function createFile(content: string, name: string) { |
| 27 | const blob = new Blob([content]); |
| 28 | return new File([blob], name); |
| 29 | } |
| 30 | |
| 31 | export async function createFileFrom(filePath: string, name: string) { |
| 32 | return new Promise<File>((resolve, reject) => { |
| 33 | const bytes: BlobPart[] = []; |
| 34 | fs.createReadStream(filePath) |
| 35 | .on("data", (byte) => bytes.push(byte)) |
| 36 | .once("end", () => { |
| 37 | const blob = new Blob(bytes); |
| 38 | resolve(new File([blob], name)); |
| 39 | }) |
| 40 | .once("error", reject); |
| 41 | }); |
| 42 | } |
| 43 | |
| 44 | type CreateTempDirResult = [tempDirPath: string, cleanTempDirFn: () => Promise<void>]; |
| 45 | |
| 46 | export async function createTempDir(rootDir: string): Promise<CreateTempDirResult> { |
| 47 | const dir = path.resolve(rootDir, randomUUID()); |
| 48 | if (!fs.existsSync(dir)) { |
| 49 | await mkdir(dir, { recursive: true }); |
| 50 | } |
| 51 | const removeFn = async () => { |
| 52 | if (fs.existsSync(dir)) { |
| 53 | await rm(dir, { recursive: true }); |
| 54 | } |
| 55 | }; |
| 56 | return [dir, removeFn]; |
| 57 | } |