-
Notifications
You must be signed in to change notification settings - Fork 235
Expand file tree
/
Copy pathfs.ts
More file actions
71 lines (62 loc) · 2.61 KB
/
fs.ts
File metadata and controls
71 lines (62 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { mkdir, rm, stat, readFile, access } from "node:fs/promises";
import { Logger } from "./log.js";
import { parse as parseYaml } from "yaml";
import { TspLocation } from "./typespec.js";
import { joinPaths, normalizePath, resolvePath } from "@typespec/compiler";
export async function ensureDirectory(path: string) {
await mkdir(path, { recursive: true });
}
export async function removeDirectory(path: string) {
await rm(path, { recursive: true, force: true });
}
export async function createTempDirectory(outputDir: string): Promise<string> {
const tempRoot = joinPaths(outputDir, "TempTypeSpecFiles");
await mkdir(tempRoot, { recursive: true });
Logger.debug(`Created temporary working directory ${tempRoot}`);
return tempRoot;
}
export async function readTspLocation(rootDir: string): Promise<TspLocation> {
try {
const yamlPath = resolvePath(rootDir, "tsp-location.yaml");
const fileStat = await stat(yamlPath);
if (fileStat.isFile()) {
const fileContents = await readFile(yamlPath, "utf8");
const tspLocation: TspLocation = parseYaml(fileContents);
if (!tspLocation.directory || !tspLocation.commit || !tspLocation.repo) {
throw new Error("Invalid tsp-location.yaml");
}
if (!tspLocation.additionalDirectories) {
tspLocation.additionalDirectories = [];
}
// Normalize the directory path and remove trailing slash
tspLocation.directory = normalizeDirectory(tspLocation.directory);
tspLocation.additionalDirectories = tspLocation.additionalDirectories.map(normalizeDirectory);
return tspLocation;
}
throw new Error("Could not find tsp-location.yaml");
} catch (e) {
Logger.error(`Error reading tsp-location.yaml: ${e}`);
throw e;
}
}
export async function getEmitterFromRepoConfig(emitterPath: string): Promise<string> {
await access(emitterPath);
const data = await readFile(emitterPath, 'utf8');
const obj = JSON.parse(data);
if (!obj || !obj.dependencies) {
throw new Error("Invalid emitter-package.json");
}
const languages: string[] = ["@azure-tools/typespec-", "@typespec/openapi3"];
for (const lang of languages) {
const emitter = Object.keys(obj.dependencies).find((dep: string) => dep.startsWith(lang));
if (emitter) {
Logger.info(`Found emitter package ${emitter}@${obj.dependencies[emitter]}`);
return emitter;
}
}
throw new Error("Could not find emitter package");
}
export function normalizeDirectory(directory: string): string {
const normalizedDir = normalizePath(directory);
return normalizedDir.endsWith("/") ? normalizedDir.slice(0, -1) : normalizedDir;
}