obsideno/cmd/install.ts

99 lines
2.4 KiB
TypeScript

import { resolve } from "jsr:@std/path";
import { buildPlugin } from "./build.ts";
import { exists } from "jsr:@std/fs";
interface InstallArgs {
pluginDir?: string;
production?: boolean;
}
export async function installPlugin(args: InstallArgs, vault: string) {
console.info("Building plugin");
await buildPlugin(args);
const cwd = args.pluginDir ? resolve(Deno.cwd(), args.pluginDir) : Deno.cwd();
const manifestPath = resolve(cwd, "manifest.json");
const versionsPath = resolve(cwd, "versions.json");
const manifestText = await Deno.readTextFile(manifestPath);
const manifest = JSON.parse(manifestText);
const jsPath = resolve(cwd, "main.js");
const vaultPath = resolve(cwd, vault);
const pluginPath = resolve(
vaultPath,
".obsidian",
"plugins",
manifest.id,
);
console.info("Verifying required paths");
try {
await Promise.allSettled([
Deno.lstat(jsPath),
Deno.lstat(manifestPath),
Deno.lstat(versionsPath),
Deno.lstat(resolve(vaultPath, ".obsidian")),
]);
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
console.info(
"Failed to find the specified vault or one of the required main.js, versions.json, and manifest.json files",
);
console.error(err.message);
Deno.exit(1);
}
throw err;
}
if (await exists(pluginPath, { isDirectory: true })) {
console.info(
`Vault already has plugin ${manifest.name} installed. Aborting`,
);
Deno.exit(0);
}
console.info("Creating plugin directory");
try {
await Deno.mkdir(pluginPath, { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
console.info("Plugin directory already exists. Continuing");
}
console.info("Creating symbolic links");
try {
await Promise.all([
Deno.symlink(
manifestPath,
resolve(pluginPath, "manifest.json"),
{ type: "file" },
),
Deno.symlink(
versionsPath,
resolve(pluginPath, "versions.json"),
{ type: "file" },
),
Deno.symlink(
jsPath,
resolve(pluginPath, "main.js"),
{ type: "file" },
),
]);
} catch (err) {
throw err;
}
const kv = await Deno.openKv();
await kv.set(
["installed-plugins", manifest.id, vaultPath],
vaultPath,
);
console.log("Plugin has been installed in the specified vault");
}