microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
e966efd30e552f4e84d5ae7224515199738ddd8e

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/compiler/cmd/runner.ts

42lines · modecode

1import { readFile, realpath, stat } from "fs/promises";
2import path from "path";
3import url from "url";
4import { 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 */
12export 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