genezio
Version:
Command line utility to interact with Genezio infrastructure.
66 lines (65 loc) • 2.77 kB
JavaScript
import { promises as fs } from "fs";
import os from "os";
import path from "path";
import { Language } from "../projectConfiguration/yaml/models.js";
import zod from "zod";
async function getLinkContent() {
const directoryPath = path.join(os.homedir(), ".genezio");
const filePath = path.join(directoryPath, "geneziolinks");
try {
// Try to read the file
const data = await fs.readFile(filePath, "utf8");
// Parse the content as JSON and convert it as a Map
const projectMap = new Map(Object.entries(JSON.parse(data)));
const linkedFrontendSchema = zod.object({
path: zod.string(),
language: zod.nativeEnum(Language),
});
for (const [projectName, linkedFrontends] of projectMap.entries()) {
// Ignore values that do not match the `LinkedFrontend` schema, because they are most likely using an old version format
projectMap.set(projectName, linkedFrontends.filter((f) => linkedFrontendSchema.safeParse(f).success));
}
return projectMap;
}
catch (error) {
const err = error;
if (err.code === "ENOENT" || err.code === "ENOTDIR") {
await fs.mkdir(directoryPath, { recursive: true });
// If the file doesn't exist, create it with an empty object
await fs.writeFile(filePath, JSON.stringify({}), "utf8");
return new Map();
}
// Rethrow the error if it's not because the file doesn't exist
throw error;
}
}
async function saveLinkContent(content) {
const directoryPath = path.join(os.homedir(), ".genezio");
const filePath = path.join(directoryPath, "geneziolinks");
await fs.writeFile(filePath, JSON.stringify(Object.fromEntries(content)), "utf8");
}
export async function getLinkedFrontendsForProject(projectName) {
const content = await getLinkContent();
return content.get(projectName) || [];
}
export async function linkFrontendsToProject(projectName, frontends) {
const content = await getLinkContent();
const linkedFrontends = content.get(projectName) || [];
for (const frontend of frontends) {
// If the frontend is already linked don't add it twice
if (linkedFrontends.find((linked) => linked.path === frontend.path && linked.language === frontend.language)) {
continue;
}
linkedFrontends.push(frontend);
}
content.set(projectName, linkedFrontends);
await saveLinkContent(content);
}
export async function deleteAllLinkPaths() {
await saveLinkContent(new Map());
}
export async function deleteLinkPathForProject(projectName) {
const content = await getLinkContent();
content.delete(projectName);
await saveLinkContent(content);
}