/
workspace.ts
618 lines (557 loc) · 17.2 KB
/
workspace.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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
import {
CONSTANTS,
DendronConfig,
DEngineClientV2,
DVault,
getStage,
} from "@dendronhq/common-all";
import {
readJSONWithComments,
readMD,
writeJSONWithComments,
} from "@dendronhq/common-server";
import { DConfig, HistoryService } from "@dendronhq/engine-server";
import fs from "fs-extra";
import _ from "lodash";
import open from "open";
import path from "path";
import * as vscode from "vscode";
import { ALL_COMMANDS } from "./commands";
import { GoToSiblingCommand } from "./commands/GoToSiblingCommand";
import { LookupCommand } from "./commands/LookupCommand";
import { ReloadIndexCommand } from "./commands/ReloadIndex";
import {
CONFIG,
DENDRON_COMMANDS,
extensionQualifiedId,
GLOBAL_STATE,
} from "./constants";
import BacklinksTreeDataProvider from "./features/BacklinksTreeDataProvider";
import { completionProvider } from "./features/completionProvider";
import DefinitionProvider from "./features/DefinitionProvider";
import DocumentLinkProvider from "./features/DocumentLinkProvider";
import ReferenceHoverProvider from "./features/ReferenceHoverProvider";
import ReferenceProvider from "./features/ReferenceProvider";
import { VaultWatcher } from "./fileWatcher";
import { Logger } from "./logger";
import { WorkspaceSettings } from "./types";
import { DisposableStore, resolvePath, VSCodeUtils } from "./utils";
import { isAnythingSelected } from "./utils/editor";
import { DendronTreeViewV2 } from "./views/DendronTreeViewV2";
import { SchemaWatcher } from "./watchers/schemaWatcher";
import { WindowWatcher } from "./windowWatcher";
import { WorkspaceWatcher } from "./WorkspaceWatcher";
let _DendronWorkspace: DendronWorkspace | null;
export type ServerConfiguration = {
serverPort: string;
};
/**
* Check for boolean toggles
*/
export function when(key: keyof DendronConfig, cb: () => void): void {
try {
const out = DendronWorkspace.instance().config[key];
if (out === false || _.isUndefined(out) ? false : true) {
cb();
}
} catch (err) {}
}
export function whenGlobalState(key: string, cb?: () => boolean): boolean {
cb =
cb ||
function () {
return true;
};
// @ts-ignore
const out = DendronWorkspace.instance().getGlobalState(key);
if (out === false || _.isUndefined(out) ? false : true) {
return cb();
}
return false;
}
export function getGlobalState<T>(key: GLOBAL_STATE) {
return DendronWorkspace.instance().getGlobalState<T>(key);
}
export function getCodeConfig<T>(key: string): T | undefined {
return DendronWorkspace.configuration().get<T>(key);
}
export function getWS() {
return DendronWorkspace.instance();
}
export function getEngine() {
return DendronWorkspace.instance().getEngine();
}
export function resolveRelToWSRoot(fpath: string): string {
return resolvePath(fpath, DendronWorkspace.wsRoot() as string);
}
// --- Main
export class DendronWorkspace {
static DENDRON_WORKSPACE_FILE: string = "dendron.code-workspace";
static _SERVER_CONFIGURATION: Partial<ServerConfiguration>;
public dendronTreeView: DendronTreeViewV2 | undefined;
public vaultWatcher?: VaultWatcher;
public port?: number;
static instance(): DendronWorkspace {
if (!_DendronWorkspace) {
throw Error("Dendronworkspace not initialized");
}
return _DendronWorkspace;
}
static serverConfiguration() {
if (!DendronWorkspace._SERVER_CONFIGURATION) {
DendronWorkspace._SERVER_CONFIGURATION = {};
}
return DendronWorkspace._SERVER_CONFIGURATION as ServerConfiguration;
}
/**
* Global Workspace configuration
*/
static configuration(
section?: string | undefined
): vscode.WorkspaceConfiguration {
// the reason this is static is so we can stub it for tests
return vscode.workspace.getConfiguration(section);
}
/**
* Full path to workspace root
*/
static wsRoot(): string {
const rootDir = getCodeConfig<string>(CONFIG.ROOT_DIR.key);
const workspaceDir = path.dirname(DendronWorkspace.workspaceFile().fsPath);
if (rootDir) {
return resolvePath(rootDir, workspaceDir);
}
return workspaceDir;
}
static lsp(): boolean {
return true;
}
/**
* Workspace settings file
*/
static workspaceFile(): vscode.Uri {
if (!vscode.workspace.workspaceFile) {
throw Error("no workspace file");
}
return vscode.workspace.workspaceFile;
}
static workspaceFolders(): readonly vscode.WorkspaceFolder[] | undefined {
return vscode.workspace.workspaceFolders;
}
static rootWorkspaceFolder(): vscode.WorkspaceFolder | undefined {
const wsFolders = DendronWorkspace.workspaceFolders();
if (wsFolders) {
return wsFolders[0];
}
return;
}
/**
* Currently, this is a check to see if rootDir is defined in settings
*/
static isActive(): boolean {
/**
* we do a try catch because `DendronWorkspace.workspaceFile` throws an error if workspace file doesn't exist
* the reason we don't use `vscode.*` method is because we need to stub this value during tests
*/
try {
return (
path.basename(DendronWorkspace.workspaceFile().fsPath) ===
this.DENDRON_WORKSPACE_FILE
);
} catch (err) {
return false;
}
}
static version(): string {
let version: string | undefined;
if (VSCodeUtils.isDebuggingExtension()) {
version = VSCodeUtils.getVersionFromPkg();
} else {
try {
const dendronExtension = vscode.extensions.getExtension(
extensionQualifiedId
)!;
version = dendronExtension.packageJSON.version;
} catch (err) {
version = VSCodeUtils.getVersionFromPkg();
}
}
if (_.isUndefined(version)) {
version = "0.0.0";
}
return version;
}
static async resetConfig(globalState: vscode.Memento) {
return await Promise.all(
_.keys(GLOBAL_STATE).map((k) => {
const _key = GLOBAL_STATE[k as keyof typeof GLOBAL_STATE];
return globalState.update(_key, undefined);
})
);
}
public context: vscode.ExtensionContext;
public windowWatcher?: WindowWatcher;
public fsWatcher?: vscode.FileSystemWatcher;
public serverWatcher?: vscode.FileSystemWatcher;
public schemaWatcher?: SchemaWatcher;
public L: typeof Logger;
public _enginev2?: DEngineClientV2;
private disposableStore: DisposableStore;
static getOrCreate(
context: vscode.ExtensionContext,
opts?: { skipSetup?: boolean }
) {
if (!_DendronWorkspace) {
_DendronWorkspace = new DendronWorkspace(context, opts);
}
return _DendronWorkspace;
}
static async updateWorkspaceFile(opts: {
updateCb: (settings: WorkspaceSettings) => WorkspaceSettings;
}) {
const { updateCb } = opts;
const wsPath = DendronWorkspace.workspaceFile().fsPath;
let settings = (await readJSONWithComments(wsPath)) as WorkspaceSettings;
settings = updateCb(settings);
await writeJSONWithComments(wsPath, settings);
return settings;
}
constructor(
context: vscode.ExtensionContext,
opts?: { skipSetup?: boolean }
) {
opts = _.defaults(opts, { skipSetup: false });
this.context = context;
_DendronWorkspace = this;
this.L = Logger;
this.disposableStore = new DisposableStore();
this._setupCommands();
this.setupLanguageFeatures(context);
this.setupViews(context);
const ctx = "DendronWorkspace";
this.L.info({ ctx, msg: "initialized" });
}
get configRoot(): string {
const dendronDir = getCodeConfig<string | undefined>(
CONFIG.DENDRON_DIR.key
);
if (_.isEmpty(dendronDir) || _.isUndefined(dendronDir)) {
return DendronWorkspace.wsRoot();
} else {
return resolveRelToWSRoot(dendronDir);
}
}
get config(): DendronConfig {
const dendronRoot = getWS().configRoot;
if (!dendronRoot) {
throw `dendronRoot not set when get config`;
}
return DConfig.getOrCreate(dendronRoot);
}
get podsDir(): string {
const rootDir = DendronWorkspace.wsRoot();
if (!rootDir) {
throw `rootdir not set when get podsDir`;
}
const podsPath = path.join(rootDir, "pods");
fs.ensureDirSync(podsPath);
return podsPath;
}
get repoDir(): string {
const repoDir = path.join(
DendronWorkspace.wsRoot(),
CONSTANTS.DENDRON_REPO_DIR
);
return repoDir;
}
get rootWorkspace(): vscode.WorkspaceFolder {
const wsFolders = DendronWorkspace.workspaceFolders();
if (_.isEmpty(wsFolders) || _.isUndefined(wsFolders)) {
throw Error("no ws folders");
}
return wsFolders[0] as vscode.WorkspaceFolder;
}
get extensionAssetsDir(): vscode.Uri {
const assetsDir = vscode.Uri.file(
path.join(this.context.extensionPath, "assets")
);
return assetsDir;
}
/**
* Get vaults with path fully resolved
*/
get vaults(): DVault[] {
const vaults = DendronWorkspace.instance().config.vaults;
return vaults.map((ent) => ({
...ent,
fsPath: resolvePath(ent.fsPath, DendronWorkspace.wsRoot() as string),
}));
}
getEngine(): DEngineClientV2 {
if (!this._enginev2) {
throw Error("engine not set");
}
return this._enginev2;
}
setEngine(engine: DEngineClientV2) {
this._enginev2 = engine;
}
async setupViews(context: vscode.ExtensionContext) {
const ctx = "setupViews";
HistoryService.instance().subscribe("extension", async (event) => {
if (event.action === "initialized") {
Logger.info({ ctx, msg: "init:backlinks" });
const backlinksTreeDataProvider = new BacklinksTreeDataProvider();
vscode.window.onDidChangeActiveTextEditor(
async () => await backlinksTreeDataProvider.refresh()
);
context.subscriptions.push(
vscode.window.createTreeView("dendron.backlinksPanel", {
treeDataProvider: backlinksTreeDataProvider,
showCollapseAll: true,
})
);
}
});
}
setupLanguageFeatures(context: vscode.ExtensionContext) {
const mdLangSelector = { language: "markdown", scheme: "*" };
vscode.languages.registerDocumentLinkProvider(
mdLangSelector,
new DocumentLinkProvider()
);
vscode.languages.registerReferenceProvider(
mdLangSelector,
new ReferenceProvider()
);
vscode.languages.registerDefinitionProvider(
mdLangSelector,
new DefinitionProvider()
);
vscode.languages.registerHoverProvider(
mdLangSelector,
new ReferenceHoverProvider()
);
completionProvider.activate(context);
}
_setupCommands() {
ALL_COMMANDS.map((Cmd) => {
this.context.subscriptions.push(
vscode.commands.registerCommand(Cmd.key, async (args: any) => {
await new Cmd().run(args);
})
);
});
// ----
this.context.subscriptions.push(
vscode.commands.registerCommand(
DENDRON_COMMANDS.LOOKUP.key,
async (args: any) => {
new LookupCommand().run({ ...args, flavor: "note" });
}
)
);
this.context.subscriptions.push(
vscode.commands.registerCommand(
DENDRON_COMMANDS.LOOKUP_SCHEMA.key,
async () => {
return new LookupCommand().run({ flavor: "schema" });
}
)
);
this.context.subscriptions.push(
vscode.commands.registerCommand(
DENDRON_COMMANDS.OPEN_LINK.key,
async () => {
const ctx = DENDRON_COMMANDS.OPEN_LINK;
this.L.info({ ctx });
if (!isAnythingSelected()) {
return vscode.window.showErrorMessage("nothing selected");
}
const { text } = VSCodeUtils.getSelection();
if (_.isUndefined(text)) {
return vscode.window.showErrorMessage("nothing selected");
}
const assetPath = resolvePath(text, this.rootWorkspace.uri.fsPath);
if (!fs.existsSync(assetPath)) {
return vscode.window.showErrorMessage(
`${assetPath} does not exist`
);
}
return open(assetPath).catch((err) => {
vscode.window.showInformationMessage(
"error: " + JSON.stringify(err)
);
});
}
)
);
this.context.subscriptions.push(
vscode.commands.registerCommand(
DENDRON_COMMANDS.RELOAD_INDEX.key,
async (silent?: boolean) => {
const out = await new ReloadIndexCommand().execute();
if (!silent) {
vscode.window.showInformationMessage(`finish reload`);
}
return out;
}
)
);
// ---
this.context.subscriptions.push(
vscode.commands.registerCommand(
DENDRON_COMMANDS.GO_NEXT_HIERARCHY.key,
async () => {
await new GoToSiblingCommand().execute({ direction: "next" });
}
)
);
this.context.subscriptions.push(
vscode.commands.registerCommand(
DENDRON_COMMANDS.GO_PREV_HIERARCHY.key,
async () => {
await new GoToSiblingCommand().execute({ direction: "prev" });
}
)
);
}
addDisposable(_disposable: vscode.Disposable) {
// TODO
// handle all disposables
}
// === Utils
getGlobalState<T>(key: GLOBAL_STATE) {
//const _key = GLOBAL_STATE[key];
return this.context.globalState.get<T>(key);
}
updateGlobalState(key: keyof typeof GLOBAL_STATE, value: any) {
const _key = GLOBAL_STATE[key];
return this.context.globalState.update(_key, value);
}
// === Workspace
/**
* - get workspace config and workspace folder
* - activate workspacespace watchers
*/
async activateWatchers() {
const ctx = "activateWorkspace";
const stage = getStage();
this.L.info({ ctx, stage, msg: "enter" });
const rootDir = DendronWorkspace.wsRoot();
if (!rootDir) {
throw `rootDir not set when activating Watcher`;
}
const windowWatcher = new WindowWatcher();
windowWatcher.activate(this.context);
windowWatcher.triggerUpdateDecorations();
this.windowWatcher = windowWatcher;
const workspaceWatcher = new WorkspaceWatcher();
workspaceWatcher.activate(this.context);
const wsFolders = DendronWorkspace.workspaceFolders();
if (_.isUndefined(wsFolders) || _.isEmpty(wsFolders)) {
this.L.error({
ctx,
msg: "no folders set for workspace",
action: "Please set folder",
});
throw Error("no folders set for workspace");
}
let vaults = wsFolders as vscode.WorkspaceFolder[];
let realVaults = DendronWorkspace.instance().vaults;
const vaultWatcher = new VaultWatcher({
vaults: realVaults,
});
const schemaWatcher = new SchemaWatcher({ vaults });
schemaWatcher.activate(this.context);
this.schemaWatcher = schemaWatcher;
vaultWatcher.activate(DendronWorkspace.instance().context);
this.vaultWatcher = vaultWatcher;
}
async deactivate() {
const ctx = "deactivateWorkspace";
this.L.info({ ctx });
this.fsWatcher?.dispose();
this.disposableStore.dispose();
}
async createServerWatcher() {
const ctx = "createServerWatcher";
const portFile = path.join(
path.dirname(DendronWorkspace.workspaceFile().fsPath),
CONSTANTS.DENDRON_SERVER_PORT
);
this.L.info({ ctx, portFile });
this.serverWatcher = vscode.workspace.createFileSystemWatcher(
portFile,
false,
false,
false
);
const updateServerConfig = (uri: vscode.Uri) => {
const port = _.trim(fs.readFileSync(uri.fsPath, { encoding: "utf-8" }));
DendronWorkspace.serverConfiguration()["serverPort"] = port;
const ctx = "updateServerConfig";
this.L.info({ ctx, msg: "update serverConfig", port });
HistoryService.instance().add({
source: "apiServer",
action: "changedPort",
});
};
// file watcher can't watch outside of workspace and our integ tests mock workspaces
if (getStage() === "test") {
fs.watchFile(portFile, () => {
fs.existsSync(portFile) &&
updateServerConfig(vscode.Uri.file(portFile));
});
}
this.disposableStore.add(
this.serverWatcher.onDidCreate(async (uri: vscode.Uri) => {
const ctx = "createServerWatcher.onDidCreate";
this.L.info({ ctx, uri });
updateServerConfig(uri);
}, this)
);
this.disposableStore.add(
this.serverWatcher.onDidChange(async (uri: vscode.Uri) => {
const ctx = "createServerWatcher.onDidChange";
this.L.info({ ctx, uri });
updateServerConfig(uri);
}, this)
);
}
/**
* Performs a series of step to initialize the workspace
* Calls activate workspace
* - initializes DendronEngine
* @param mainVault
*/
async reloadWorkspace() {
try {
const out = await vscode.commands.executeCommand(
DENDRON_COMMANDS.RELOAD_INDEX.key,
true
);
return out;
} catch (err) {
vscode.window.showErrorMessage(
`error initializing dendron: ${JSON.stringify(err)}`
);
}
}
async showWelcome(
welcomeUri?: vscode.Uri,
_opts?: { reuseWindow?: boolean }
) {
welcomeUri =
welcomeUri ||
vscode.Uri.joinPath(this.rootWorkspace.uri, "dendron.quickstart.md");
try {
const { content } = readMD(welcomeUri.fsPath);
if (getStage() !== "test") {
VSCodeUtils.showWebView({ title: "Welcome", content });
}
} catch (err) {
vscode.window.showErrorMessage(JSON.stringify(err));
}
}
}