-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.ts
510 lines (483 loc) · 13.9 KB
/
plugin.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// =============================================================================
// File : plugin.ts
// Author : yukimemi
// Last Change : 2024/07/27 22:57:53.
// =============================================================================
import * as fn from "jsr:@denops/std@7.0.3/function";
import * as op from "jsr:@denops/std@7.0.3/option";
import * as path from "jsr:@std/path@1.0.2";
import type { Denops } from "jsr:@denops/std@7.0.3";
import { Git } from "./git.ts";
import { Result } from "npm:result-type-ts@2.1.3";
import { Semaphore } from "jsr:@lambdalisue/async@2.1.1";
import { cmdOutToString, executeFile, getExecuteStr } from "./util.ts";
import { echo, execute } from "jsr:@denops/std@7.0.3/helper";
import { ensure, is } from "jsr:@core/unknownutil@4.1.0";
import { exists, expandGlob } from "jsr:@std/fs@1.0.1";
export type TrueFalse =
| boolean
| ((
{ denops, info }: { denops: Denops; info: PlugInfo },
) => Promise<boolean>);
export type Plug = {
url: string;
dst?: string;
branch?: string;
enabled?: TrueFalse;
before?: (
{ denops, info }: { denops: Denops; info: PlugInfo },
) => Promise<void>;
beforeSource?: (
{ denops, info }: { denops: Denops; info: PlugInfo },
) => Promise<void>;
beforeSourceFile?: string;
beforeFile?: string;
afterFile?: string;
after?: (
{ denops, info }: { denops: Denops; info: PlugInfo },
) => Promise<void>;
build?: (
{ denops, info }: { denops: Denops; info: PlugInfo },
) => Promise<void>;
cache?: {
enabled?: TrueFalse;
before?: string;
after?: string;
beforeFile?: string;
afterFile?: string;
};
clone?: TrueFalse;
dependencies?: Plug[];
depth?: number;
};
export type PlugInfo = Plug & {
isLoad: boolean;
isUpdate: boolean;
isCache: boolean;
elaps: number;
};
export type PluginOption = {
base: string;
debug?: boolean;
profile?: boolean;
logarg?: string[];
};
export class Plugin {
static mutex: Semaphore = new Semaphore(1);
/// plugin information
public info: PlugInfo;
constructor(
public denops: Denops,
public plug: Plug,
public pluginOption: PluginOption,
) {
this.info = {
...plug,
isLoad: false,
isUpdate: false,
isCache: false,
elaps: 0,
};
}
/**
* Creates a new Plugin instance
*/
public static async create(
denops: Denops,
plug: Plug,
pluginOption: PluginOption,
): Promise<Plugin> {
const p = new Plugin(denops, plug, pluginOption);
if (p.plug.url.startsWith("http") || p.plug.url.startsWith("git")) {
p.info.url = p.plug.url;
} else {
p.info.url = `https://github.com/${p.plug.url}`;
}
const url = new URL(p.info.url);
p.info.dst = path.join(pluginOption.base, url.hostname, url.pathname);
if (p.info.depth == undefined) {
p.info.depth = 0;
}
if (p.plug.dst) {
p.clog(`[create] ${p.info.dst} set dst to ${p.plug.dst}`);
p.info.dst = ensure(await fn.expand(denops, p.plug.dst), is.String);
}
if (p.plug.enabled == undefined) {
p.info.enabled = true;
}
if (await p.isTrueFalse(p.plug.clone, true) === false) {
p.info.enabled = false;
p.info.clone = false;
} else {
p.info.clone = true;
}
if (
p.plug.cache?.before || p.plug.cache?.after || p.plug.cache?.beforeFile ||
p.plug.cache?.afterFile
) {
p.info.cache = {
enabled: true,
...p.info.cache,
};
}
return p;
}
// deno-lint-ignore no-explicit-any
private clog(data: any) {
if (this.pluginOption.debug) {
console.log(data);
}
}
private async isTrueFalse(tf: TrueFalse | undefined, def: boolean) {
if (tf == undefined) {
return def;
}
if (is.Boolean(tf)) {
return tf;
}
return await tf({ denops: this.denops, info: this.info });
}
private async isEnabled() {
return await this.isTrueFalse(this.info.enabled, true);
}
private async isClone() {
return await this.isTrueFalse(this.info.clone, true);
}
private async isCache() {
return await this.isTrueFalse(this.info.cache?.enabled, false);
}
/**
* Add a plugin to dvpm list
*/
public async add() {
try {
this.clog(`[add] ${this.info.url} start !`);
if (!(await this.isEnabled())) {
return;
}
await this.before();
await this.register();
if (this.info.isUpdate) {
await this.build();
}
await this.after();
} catch (e) {
console.error(e);
} finally {
this.clog(`[add] ${this.info.url} end !`);
}
}
/**
* Cache a plugin and plugin config
*/
public async cache(): Promise<string> {
try {
this.clog(`[cache] ${this.info.url} start !`);
if (
!(await this.isEnabled()) || !(await this.isCache())
) {
return "";
}
this.info.isCache = true;
const cacheStr = [this.info.cache?.before || ""];
if (this.info.cache?.beforeFile) {
cacheStr.push(await getExecuteStr(this.denops, this.info.cache.beforeFile));
}
cacheStr.push(`set runtimepath+=${this.info.dst}`);
for await (const file of expandGlob(`${this.info.dst}/plugin/**/*.vim`)) {
cacheStr.push(`source ${file.path}`);
}
for await (const file of expandGlob(`${this.info.dst}/plugin/**/*.lua`)) {
cacheStr.push(`luafile ${file.path}`);
}
if (this.info.cache?.afterFile) {
cacheStr.push(await getExecuteStr(this.denops, this.info.cache.afterFile));
}
cacheStr.push(this.info.cache?.after || "");
return cacheStr.join("\n");
} catch (e) {
console.error(e);
return "";
} finally {
this.clog(`[cache] ${this.info.url} end !`);
}
}
/**
* plugin end function
*/
public async end() {
await this.sourceAfter();
}
/**
* Add plugin to runtimepath
*/
public async register() {
this.clog(`[register] ${this.info.url} start !`);
let registered = false;
let starttime = 0;
await Plugin.mutex.lock(async () => {
if (this.pluginOption.profile) {
starttime = performance.now();
}
const rtp = (await op.runtimepath.get(this.denops)).split(",");
if (!rtp.includes(ensure(this.info.dst, is.String))) {
registered = true;
await op.runtimepath.set(this.denops, `${rtp},${this.info.dst}`);
}
});
if (registered) {
await this.beforeSource();
await this.source();
await this.registerDenops();
if (this.pluginOption.profile) {
this.info.elaps = performance.now() - starttime;
}
}
this.info.isLoad = true;
this.clog(`[register] ${this.info.url} end !`);
return;
}
/**
* plugin config before adding to runtimepath
*/
public async before() {
if (this.info.before) {
this.clog(`[before] ${this.info.url} start !`);
await this.info.before({ denops: this.denops, info: this.info });
this.clog(`[before] ${this.info.url} end !`);
}
if (this.info.beforeFile) {
await executeFile(this.denops, this.info.beforeFile);
}
}
/**
* plugin config before source plugin/*.vim and plugin/*.lua files
*/
public async beforeSource() {
if (this.info.beforeSource) {
this.clog(`[beforeSource] ${this.info.url} start !`);
await this.info.beforeSource({ denops: this.denops, info: this.info });
this.clog(`[beforeSource] ${this.info.url} end !`);
}
if (this.info.beforeSourceFile) {
await executeFile(this.denops, this.info.beforeSourceFile);
}
}
/**
* plugin config after adding to runtimepath
*/
public async after() {
if (this.info.after) {
this.clog(`[after] ${this.info.url} start !`);
await this.info.after({ denops: this.denops, info: this.info });
this.clog(`[after] ${this.info.url} end !`);
}
if (this.info.afterFile) {
await executeFile(this.denops, this.info.afterFile);
}
}
/**
* plugin build config
*/
public async build() {
if (this.info.build && await this.isEnabled()) {
this.clog(`[build] ${this.info.url} start !`);
await this.info.build({ denops: this.denops, info: this.info });
this.clog(`[build] ${this.info.url} end !`);
}
}
/**
* source plugin
*/
private async source() {
try {
this.clog(`[source] ${this.info.url} start !`);
await this.sourceVimPre();
await this.sourceLuaPre();
} catch (e) {
console.error(e);
} finally {
this.clog(`[source] ${this.info.url} end !`);
}
}
/**
* source plugin config after adding to runtimepath
*/
private async sourceAfter() {
try {
this.clog(`[sourceAfter] ${this.info.url} start !`);
await this.sourceVimAfter();
await this.sourceLuaAfter();
} catch (e) {
console.error(e);
} finally {
this.clog(`[sourceAfter] ${this.info.url} end !`);
}
}
private async sourceVim(target: string) {
for await (const file of expandGlob(target)) {
await execute(this.denops, `source ${file.path}`);
}
}
private async sourceVimPre() {
const target = `${this.info.dst}/plugin/**/*.vim`;
await this.sourceVim(target);
}
private async sourceVimAfter() {
const target = `${this.info.dst}/after/plugin/**/*.vim`;
await this.sourceVim(target);
}
private async sourceLua(target: string) {
for await (const file of expandGlob(target)) {
await execute(this.denops, `luafile ${file.path}`);
}
}
private async sourceLuaPre() {
const target = `${this.info.dst}/plugin/**/*.lua`;
await this.sourceLua(target);
}
private async sourceLuaAfter() {
const target = `${this.info.dst}/after/plugin/**/*.lua`;
await this.sourceLua(target);
}
private async registerDenops() {
const target = `${this.info.dst}/denops/*/main.ts`;
for await (const file of expandGlob(target)) {
const name = path.basename(path.dirname(file.path));
try {
await this.denops.call("denops#plugin#load", name, file.path);
} catch (e) {
if (e.match(/Vim:E117:/)) {
await this.denops.call("denops#plugin#register", name, file.path, {
mode: "skip",
});
} else {
throw e;
}
}
}
}
private async isHelptagsOld(docDir: string) {
const txts: string[] = [];
const tags: string[] = [];
for await (const entry of expandGlob(docDir + "/*.{txt,[a-z][a-z]x}")) {
txts.push(entry.path);
}
for await (const entry of expandGlob(docDir + "/tags{-[a-z][a-z],}")) {
tags.push(entry.path);
}
const txtNewest = Math.max(...txts.map((txt) => Deno.statSync(txt).mtime?.getTime() ?? 0));
const tagOldest = Math.min(...tags.map((tag) => Deno.statSync(tag).mtime?.getTime() ?? 0));
return tags.length === 0 || txtNewest > tagOldest;
}
/**
* Generate helptags
*/
public async genHelptags() {
const docDir = path.join(ensure(this.info.dst, is.String), "doc");
if (!(await this.isHelptagsOld(docDir))) {
return;
}
await execute(
this.denops,
`silent! helptags ${await fn.fnameescape(this.denops, docDir)}`,
);
}
/**
* Install a plugin
*/
public async install(): Promise<Result<string[], string[]>> {
const gitDir = path.join(ensure(this.info.dst, is.String), ".git");
if (await exists(gitDir)) {
return Result.success([]);
}
if (!(await this.isClone())) {
return Result.success([]);
}
const output = await Git.clone(
this.info.url,
ensure(this.info.dst, is.String),
this.info.branch,
this.info.depth,
);
if (output.success) {
await this.genHelptags();
this.info.isUpdate = true;
let returnMsg = `Git clone ${this.info.url}`;
if (this.info.branch) {
returnMsg += ` --branch=${this.info.branch}`;
}
if (this.info.depth != undefined && this.info.depth > 0) {
returnMsg += ` --depth=${this.info.depth}`;
}
return Result.success([returnMsg]);
}
return Result.failure([
`Failed to clone ${this.info.url}`,
`stdout:`,
...cmdOutToString(output.stdout),
`stderr:`,
...cmdOutToString(output.stderr),
]);
}
/**
* Update a plugin
*/
public async update(): Promise<Result<string[], string[]>> {
if (!(await this.isClone())) {
return Result.success([]);
}
const git = new Git(ensure(this.info.dst, is.String));
const beforeRev = await git.getRevision();
this.info.branch
? await echo(this.denops, `Update ${this.info.url}, branch: ${this.info.branch}`)
: await echo(this.denops, `Update ${this.info.url}`);
const output = await git.pull(this.info.branch);
const afterRev = await git.getRevision();
await this.genHelptags();
if (output.success) {
if (beforeRev !== afterRev) {
this.info.isUpdate = true;
await this.build();
const outputLog = await git.getLog(
beforeRev,
afterRev,
this.pluginOption.logarg,
);
const outputDiff = await git.getDiff(
beforeRev,
afterRev,
);
if (outputLog.success) {
const log = [
`--- ○: ${this.info.dst} --------------------`,
...cmdOutToString(outputLog.stdout),
];
if (outputDiff.success) {
log.push(`---`);
log.push(...cmdOutToString(outputDiff.stdout));
}
return Result.success(log);
}
return Result.success([
`--- ×: ${this.info.dst} --------------------`,
`Failed to git log ${this.info.dst}`,
`stdout:`,
...cmdOutToString(outputLog.stdout),
`stderr:`,
...cmdOutToString(outputLog.stderr),
]);
}
await this.build();
return Result.success([]);
}
return Result.failure([
`--- ×: ${this.info.dst} --------------------`,
`Failed to git pull ${this.info.url}`,
`stdout:`,
...cmdOutToString(output.stdout),
`stderr:`,
...cmdOutToString(output.stderr),
]);
}
}