-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.ts
97 lines (89 loc) · 2.57 KB
/
util.ts
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// =============================================================================
// File : util.ts
// Author : yukimemi
// Last Change : 2024/10/27 11:48:35.
// =============================================================================
import * as fn from "jsr:@denops/std@7.3.2/function";
import * as fs from "jsr:@std/fs@1.0.5";
import type { Denops } from "jsr:@denops/std@7.3.2";
import { dirname, extname } from "jsr:@std/path@1.0.8";
import { echo, echoerr, execute } from "jsr:@denops/std@7.3.2/helper";
import { logger } from "./logger.ts";
import { z } from "npm:zod@3.23.8";
/**
* vim.notify function
*/
export async function notify(denops: Denops, msg: string) {
try {
if (await fn.has(denops, "nvim")) {
logger().debug(msg);
await execute(
denops,
`lua vim.notify([[${msg}]], vim.log.levels.INFO)`,
);
} else {
await echo(denops, msg);
}
} catch (e) {
if (e instanceof Error) {
logger().error(`[notify] ${e.message}, ${e.stack}`);
}
}
}
/**
* Cache the script
*/
export async function cache(
denops: Denops,
arg: { script: string; path: string },
) {
const p = z.string().parse(await fn.expand(denops, arg.path));
const s = arg.script.trim();
await fs.ensureDir(dirname(p));
if (await fs.exists(p)) {
const content = (await Deno.readTextFile(p)).trim();
if (s !== content) {
logger().debug(`Save to ${p}`);
await Deno.writeTextFile(p, s);
}
} else {
logger().debug(`Save to ${p}`);
await Deno.writeTextFile(p, s);
}
}
/**
* Determine whether it is typescript, lua or vim and return the string to read
*/
export async function getExecuteStr(denops: Denops, path: string): Promise<string> {
const p = z.string().parse(await fn.expand(denops, path));
const extension = extname(p);
if (extension === ".lua") {
return `luafile ${p}`;
} else if (extension === ".vim") {
return `source ${p}`;
}
await echoerr(denops, `unknown extension: ${extension}`);
return "";
}
/**
* execute `lua` or `vim` file
*/
export async function executeFile(denops: Denops, path: string): Promise<void> {
const executeStr = await getExecuteStr(denops, path);
await execute(denops, executeStr);
}
/**
* Convert command output to string
*/
export function cmdOutToString(cmdout: Uint8Array): string[] {
return new TextDecoder().decode(cmdout).split("\n").map((l) => l.trim());
}
/**
* Convert url
*/
export function convertUrl(url: string): string {
if (url.startsWith("https://") || url.startsWith("git")) {
return url;
}
return `https://github.com/${url}`;
}