microsoft/typespec
Publicmirrored from https://github.com/microsoft/typespecAvailable
packages/compiler/.scripts/helpers.ts
45lines · modecode
| 1 | import { readdir } from "fs/promises"; |
| 2 | import { dirname } from "path"; |
| 3 | import { join, resolve } from "path/posix"; |
| 4 | import { fileURLToPath } from "url"; |
| 5 | |
| 6 | export const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); |
| 7 | const templateDir = "templates"; |
| 8 | |
| 9 | function isEnoentError(e: unknown): e is { code: "ENOENT" } { |
| 10 | return typeof e === "object" && e !== null && "code" in e; |
| 11 | } |
| 12 | |
| 13 | async function readFilesInDirRecursively(dir: string): Promise<string[]> { |
| 14 | let entries; |
| 15 | try { |
| 16 | entries = await readdir(dir, { withFileTypes: true }); |
| 17 | } catch (e) { |
| 18 | if (isEnoentError(e)) { |
| 19 | return []; |
| 20 | } else { |
| 21 | throw new Error(`Failed to read dir "${dir}"\n Error: ${e}`); |
| 22 | } |
| 23 | } |
| 24 | const files: string[] = []; |
| 25 | for (const entry of entries) { |
| 26 | if (entry.isDirectory()) { |
| 27 | for (const file of await readFilesInDirRecursively(resolve(dir, entry.name))) { |
| 28 | files.push(join(entry.name, file)); |
| 29 | } |
| 30 | } else { |
| 31 | files.push(entry.name); |
| 32 | } |
| 33 | } |
| 34 | return files; |
| 35 | } |
| 36 | |
| 37 | export function localFile(templateName: string, path: string): any { |
| 38 | const destination = path.endsWith(".mu") ? path.slice(0, -3) : path; |
| 39 | return { path: join(templateName, path), destination }; |
| 40 | } |
| 41 | |
| 42 | export async function localDir(templateName: string): Promise<any[]> { |
| 43 | const files = await readFilesInDirRecursively(resolve(templateDir, templateName)); |
| 44 | return files.map((f) => localFile(templateName, f)); |
| 45 | } |
| 46 | |