microsoft/typespec
Publicmirrored from https://github.com/microsoft/typespecAvailable
packages/compiler/cmd/runner.ts
42lines · modecode
| 1 | import { readFile, realpath, stat } from "fs/promises"; |
| 2 | import path from "path"; |
| 3 | import url from "url"; |
| 4 | import { resolveModule, ResolveModuleHost } from "../core/module-resolver.js"; |
| 5 | /** |
| 6 | * Run script given by relative path from @cadl-lang/compiler package root. |
| 7 | * Prefer local install resolved from cwd over current package. |
| 8 | * |
| 9 | * Prevents loading two conflicting copies of Cadl modules from global and |
| 10 | * local package locations. |
| 11 | */ |
| 12 | export async function runScript(relativePath: string): Promise<void> { |
| 13 | let packageRoot; |
| 14 | try { |
| 15 | const host: ResolveModuleHost = { |
| 16 | realpath, |
| 17 | readFile: async (path: string) => await readFile(path, "utf-8"), |
| 18 | stat, |
| 19 | }; |
| 20 | const resolved = await resolveModule(host, "@cadl-lang/compiler", { |
| 21 | baseDir: process.cwd(), |
| 22 | }); |
| 23 | packageRoot = path.resolve(resolved, "../../.."); |
| 24 | } catch (err: any) { |
| 25 | if (err.code === "MODULE_NOT_FOUND") { |
| 26 | // Resolution from cwd failed: use current package. |
| 27 | packageRoot = path.resolve(await realpath(url.fileURLToPath(import.meta.url)), "../../.."); |
| 28 | } else { |
| 29 | throw err; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | if (packageRoot) { |
| 34 | const script = path.join(packageRoot, relativePath); |
| 35 | const scriptUrl = url.pathToFileURL(script).toString(); |
| 36 | import(scriptUrl); |
| 37 | } else { |
| 38 | throw new Error( |
| 39 | "Couldn't resolve Cadl compiler root. This is unexpected. Please file an issue at https://github.com/Microsoft/cadl." |
| 40 | ); |
| 41 | } |
| 42 | } |
| 43 | |