UNPKG

@typespec/compiler

Version:

TypeSpec Compiler Preview

77 lines 2.48 kB
import { createDiagnostic } from "../core/messages.js"; import { getDirectoryPath, joinPaths } from "../core/path-utils.js"; import { createSourceFile } from "../core/source-file.js"; import { NoTarget } from "../core/types.js"; export async function doIO(action, path, reportDiagnostic, options) { let result; try { result = await action(path); } catch (e) { let diagnostic; let target = options?.diagnosticTarget ?? NoTarget; // blame the JS file, not the TypeSpec import statement for JS syntax errors. if (e instanceof SyntaxError && options?.jsDiagnosticTarget) { target = options.jsDiagnosticTarget; } switch (e.code) { case "ENOENT": if (options?.allowFileNotFound) { return undefined; } diagnostic = createDiagnostic({ code: "file-not-found", target, format: { path } }); break; default: diagnostic = createDiagnostic({ code: "file-load", target, format: { message: e.message }, }); break; } reportDiagnostic(diagnostic); return undefined; } return result; } export async function loadFile(host, path, load, reportDiagnostic, options) { const file = await doIO(host.readFile, path, reportDiagnostic, options); if (!file) { return [undefined, createSourceFile("", path)]; } let data; try { data = load(file.text); } catch (e) { reportDiagnostic({ code: "file-load", message: e.message, severity: "error", target: { file, pos: 1, end: 1 }, }); return [undefined, file]; } return [data, file]; } /** * Look for the project root by looking up until a `package.json` is found. * @param path Path to start looking * @param lookIn */ export async function findProjectRoot(statFn, path) { let current = path; while (true) { const pkgPath = joinPaths(current, "package.json"); const stat = await doIO(() => statFn(pkgPath), pkgPath, () => { }); if (stat?.isFile()) { return current; } const parent = getDirectoryPath(current); if (parent === current) { return undefined; } current = parent; } } //# sourceMappingURL=io.js.map