microsoft/typespec

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
69077cc204bc0b1cef0f44bc01c2a74b5208965c

Branches

Tags

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

Clone

HTTPS

Download ZIP

packages/compiler/cmd/runner.ts

68lines · modecode

1import { access, readFile, realpath, stat } from "fs/promises";
2import { join, resolve } from "path";
3import { fileURLToPath, pathToFileURL } from "url";
4import { resolveModule, ResolveModuleHost } from "../core/module-resolver.js";
5
6/**
7 * Run script given by relative path from @cadl-lang/compiler package root.
8 * Prefer local install resolved from cwd over current package.
9 *
10 * Prevents loading two conflicting copies of Cadl modules from global and
11 * local package locations.
12 */
13export async function runScript(relativePath: string, backupPath: string): Promise<void> {
14 const packageRoot = await resolvePackageRoot();
15
16 if (packageRoot) {
17 let script = join(packageRoot, relativePath);
18 if (!(await checkFileExists(script)) && backupPath) {
19 script = join(packageRoot, backupPath);
20 }
21 const scriptUrl = pathToFileURL(script).toString();
22 await import(scriptUrl);
23 } else {
24 throw new Error(
25 "Couldn't resolve Cadl compiler root. This is unexpected. Please file an issue at https://github.com/Microsoft/cadl."
26 );
27 }
28}
29
30function checkFileExists(file: string) {
31 return access(file)
32 .then(() => true)
33 .catch(() => false);
34}
35
36async function resolvePackageRoot(): Promise<string> {
37 if (process.env.CADL_SKIP_COMPILER_RESOLVE === "1") {
38 return await getThisPackageRoot();
39 }
40
41 try {
42 const host: ResolveModuleHost = {
43 realpath,
44 readFile: async (path: string) => await readFile(path, "utf-8"),
45 stat,
46 };
47 const resolved = await resolveModule(host, "@cadl-lang/compiler", {
48 baseDir: process.cwd(),
49 });
50 if (resolved.type !== "module") {
51 throw new Error(
52 `Error resolving "@cadl-lang/compiler", expected to find a node module but found a file: "${resolved.path}".`
53 );
54 }
55 return resolved.path;
56 } catch (err: any) {
57 if (err.code === "MODULE_NOT_FOUND") {
58 // Resolution from cwd failed: use current package.
59 return await getThisPackageRoot();
60 } else {
61 throw err;
62 }
63 }
64}
65
66async function getThisPackageRoot() {
67 return resolve(await realpath(fileURLToPath(import.meta.url)), "../../..");
68}
69