|
| 1 | +import { Denops, fs, hash, path } from "../deps.ts"; |
| 2 | +import { execute } from "./execute.ts"; |
| 3 | + |
| 4 | +/** |
| 5 | + * Load Vim script in local/remote URL |
| 6 | + */ |
| 7 | +export async function load( |
| 8 | + denops: Denops, |
| 9 | + url: URL, |
| 10 | +): Promise<void> { |
| 11 | + const scriptPath = await ensureLocalFile(url); |
| 12 | + await execute( |
| 13 | + denops, |
| 14 | + "execute printf('source %s', fnameescape(scriptPath)) ", |
| 15 | + { scriptPath }, |
| 16 | + ); |
| 17 | +} |
| 18 | + |
| 19 | +async function ensureLocalFile(url: URL): Promise<string> { |
| 20 | + if (url.protocol === "file:") { |
| 21 | + return path.fromFileUrl(url); |
| 22 | + } |
| 23 | + const cacheDir = await getOrCreateCacheDir(); |
| 24 | + const filename = getLocalFilename(url); |
| 25 | + const filepath = path.join(cacheDir, filename); |
| 26 | + if (await fs.exists(filepath)) { |
| 27 | + return filepath; |
| 28 | + } |
| 29 | + const response = await fetch(url); |
| 30 | + if (response.status !== 200) { |
| 31 | + throw new Error(`Failed to fetch '${url}'`); |
| 32 | + } |
| 33 | + const content = await response.arrayBuffer(); |
| 34 | + await Deno.writeFile( |
| 35 | + filepath, |
| 36 | + new Uint8Array(content), |
| 37 | + { mode: 0o700 }, // Do NOT allow groups/others to read the file |
| 38 | + ); |
| 39 | + return filepath; |
| 40 | +} |
| 41 | + |
| 42 | +function getLocalFilename(url: URL): string { |
| 43 | + const h = hash.createHash("sha256"); |
| 44 | + h.update(url.href); |
| 45 | + const basename = path.basename(url.pathname); |
| 46 | + return `${h.digest()}-${basename}`; |
| 47 | +} |
| 48 | + |
| 49 | +async function getOrCreateCacheDir(): Promise<string> { |
| 50 | + const cacheDir = Deno.build.os === "windows" |
| 51 | + ? getCacheDirWindows() |
| 52 | + : getCacheDirUnix(); |
| 53 | + await Deno.mkdir(cacheDir, { recursive: true }); |
| 54 | + return cacheDir; |
| 55 | +} |
| 56 | + |
| 57 | +function getCacheDirUnix(): string { |
| 58 | + const root = Deno.env.get("HOME"); |
| 59 | + if (!root) { |
| 60 | + throw new Error("`HOME` environment variable is not defined."); |
| 61 | + } |
| 62 | + return path.join(root, ".cache", "denops_std", "load"); |
| 63 | +} |
| 64 | + |
| 65 | +function getCacheDirWindows(): string { |
| 66 | + const root = Deno.env.get("LOCALAPPDATA"); |
| 67 | + if (!root) { |
| 68 | + throw new Error("`LOCALAPPDATA` environment variable is not defined."); |
| 69 | + } |
| 70 | + return path.join(root, "denops_std", "load"); |
| 71 | +} |
0 commit comments