/
VaultAddCommand.ts
506 lines (478 loc) · 16.3 KB
/
VaultAddCommand.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
import {
asyncLoopOneAtATime,
ConfigUtils,
CONSTANTS,
DendronError,
DVault,
DWorkspace,
FOLDERS,
DendronConfig,
SelfContainedVault,
VaultRemoteSource,
VaultUtils,
WorkspaceEvents,
} from "@dendronhq/common-all";
import {
DConfig,
GitUtils,
pathForVaultRoot,
simpleGit,
} from "@dendronhq/common-server";
import {
Git,
WorkspaceService,
WorkspaceUtils,
} from "@dendronhq/engine-server";
import fs from "fs-extra";
import _ from "lodash";
import path from "path";
import { commands, ProgressLocation, QuickPickItem, window } from "vscode";
import { PickerUtilsV2 } from "../components/lookup/utils";
import { DENDRON_COMMANDS, DENDRON_REMOTE_VAULTS } from "../constants";
import { ExtensionProvider } from "../ExtensionProvider";
import { Logger } from "../logger";
import { AnalyticsUtils } from "../utils/analytics";
import { PluginFileUtils } from "../utils/files";
import { MessageSeverity, VSCodeUtils } from "../vsCodeUtils";
import { BasicCommand } from "./base";
type CommandOpts = {
type: VaultRemoteSource;
path: string;
pathRemote?: string;
name?: string;
isSelfContained?: boolean;
};
type CommandOutput = { vaults: DVault[] };
export { CommandOpts as VaultAddCommandOpts };
type SourceQuickPickEntry = QuickPickItem & { src: string };
enum VaultType {
LOCAL = "local",
REMOTE = "remote",
}
export class VaultAddCommand extends BasicCommand<CommandOpts, CommandOutput> {
key = DENDRON_COMMANDS.VAULT_ADD.key;
generateRemoteEntries = (): SourceQuickPickEntry[] => {
return DENDRON_REMOTE_VAULTS.map(
({ name: label, description, data: src }): SourceQuickPickEntry => {
return { label, description, src };
}
).concat([
{
label: "custom",
description: "custom endpoint",
alwaysShow: true,
src: "",
},
]);
};
/** A regular, non-self contained vault. */
async gatherVaultStandard(
sourceType: VaultRemoteSource
): Promise<CommandOpts | undefined> {
const localVaultPathPlaceholder = "vault2";
let sourcePath: string;
let sourceName: string | undefined;
if (sourceType === VaultType.REMOTE) {
// eslint-disable-next-line no-async-promise-executor
const out = new Promise<CommandOpts | undefined>(async (resolve) => {
const qp = VSCodeUtils.createQuickPick<SourceQuickPickEntry>();
qp.ignoreFocusOut = true;
qp.placeholder = "choose a preset or enter a custom git endpoint";
qp.items = this.generateRemoteEntries();
qp.onDidAccept(async () => {
const value = qp.value;
const selected = qp.selectedItems[0];
if (selected.label === "custom") {
if (PickerUtilsV2.isInputEmpty(value)) {
return window.showInformationMessage("please enter an endpoint");
}
selected.src = qp.value;
}
const sourceRemotePath = selected.src;
const path2Vault =
selected.label === "custom"
? GitUtils.getRepoNameFromURL(sourceRemotePath)
: selected.label;
const placeHolder = path2Vault;
const out = await VSCodeUtils.showInputBox({
prompt: "Path to your new vault (relative to your workspace root)",
placeHolder: localVaultPathPlaceholder,
value: path2Vault,
});
if (PickerUtilsV2.isInputEmpty(out)) {
resolve(undefined);
}
sourcePath = out!;
sourceName = await VSCodeUtils.showInputBox({
prompt: "Name of new vault (optional, press enter to skip)",
value: placeHolder,
});
qp.hide();
return resolve({
type: sourceType!,
name: sourceName,
path: sourcePath,
pathRemote: sourceRemotePath,
});
});
qp.show();
});
return out;
} else {
const out = await VSCodeUtils.showInputBox({
prompt: "Path to your new vault (relative to your workspace root)",
placeHolder: localVaultPathPlaceholder,
});
if (PickerUtilsV2.isInputEmpty(out)) return;
sourcePath = out!;
}
sourceName = await VSCodeUtils.showInputBox({
prompt: "Name of new vault (optional, press enter to skip)",
});
return {
type: sourceType,
name: sourceName,
path: sourcePath,
};
}
async gatherVaultSelfContained(
sourceType: VaultRemoteSource
): Promise<CommandOpts | undefined> {
// If the vault name already exists, creating a vault with the same name would break things
if (sourceType === VaultType.LOCAL) {
// Local vault
// For self contained vaults, we'll have the vault name match the folder for
// now. We can make this flexible later if that's a better UX, or give
// instructions on the wiki on how to change the name later.
const vaultName = await VSCodeUtils.showInputBox({
title: "Vault name",
prompt: "Name for the new vault",
placeHolder: "my-vault",
});
// If empty, then user cancelled the prompt
if (PickerUtilsV2.isInputEmpty(vaultName)) return;
return {
type: sourceType,
name: vaultName,
path: path.join(
FOLDERS.DEPENDENCIES,
FOLDERS.LOCAL_DEPENDENCY,
vaultName
),
isSelfContained: true,
};
} else {
// Remote vault
const remote = await VSCodeUtils.showInputBox({
title: "Remote URL",
prompt: "Enter the URL for the git remote",
placeHolder: "git@github.com:dendronhq/dendron.git",
ignoreFocusOut: true,
});
// Cancelled
if (PickerUtilsV2.isInputEmpty(remote)) return;
// Calculate the vault name from the remote. If that fails, ask the user for a unique name to use.
const vaultName: string | undefined = GitUtils.getRepoNameFromURL(remote);
return {
type: sourceType,
name: vaultName,
path: path.join(
FOLDERS.DEPENDENCIES,
GitUtils.remoteUrlToDependencyPath({
vaultName,
url: remote,
})
),
pathRemote: remote,
isSelfContained: true,
};
}
}
async gatherInputs(): Promise<CommandOpts | undefined> {
window.showWarningMessage(
`This command will be deprecated in future releases.
Please use Dendron: Create New Vault to create a new vault and
Dendron: Add Existing Vault to add an existing vault to your workspace.`
);
const sourceTypeSelected = await VSCodeUtils.showQuickPick([
{ label: VaultType.LOCAL, picked: true },
{ label: VaultType.REMOTE },
]);
if (!sourceTypeSelected) {
return;
}
const sourceType = sourceTypeSelected.label;
const { config } = ExtensionProvider.getDWorkspace();
if (config.dev?.enableSelfContainedVaults) {
return this.gatherVaultSelfContained(sourceType);
} else {
// A "standard", non self contained vault
return this.gatherVaultStandard(sourceType);
}
}
async handleRemoteRepo(
opts: CommandOpts
): Promise<{ vaults: DVault[]; workspace?: DWorkspace }> {
const { vaults, workspace } = await window.withProgress(
{
location: ProgressLocation.Notification,
title: "Adding remote vault",
cancellable: false,
},
async (progress) => {
progress.report({
message: "cloning repo",
});
const baseDir = ExtensionProvider.getDWorkspace().wsRoot;
const git = simpleGit({ baseDir });
await git.clone(opts.pathRemote!, opts.path);
const { vaults, workspace } = await GitUtils.getVaultsFromRepo({
repoPath: path.join(baseDir, opts.path),
wsRoot: ExtensionProvider.getDWorkspace().wsRoot,
repoUrl: opts.pathRemote!,
});
if (_.size(vaults) === 1 && opts.name) {
vaults[0].name = opts.name;
}
// add all vaults
progress.report({
message: "adding vault",
});
const wsRoot = ExtensionProvider.getDWorkspace().wsRoot;
const wsService = new WorkspaceService({ wsRoot });
if (workspace) {
await wsService.addWorkspace({ workspace });
await this.addWorkspaceToWorkspace(workspace);
} else {
// Some things, like updating config, can't be parallelized so needs to be done one at a time
for (const vault of vaults) {
// eslint-disable-next-line no-await-in-loop
await wsService.createVault({ vault });
// eslint-disable-next-line no-await-in-loop
await this.addVaultToWorkspace(vault);
}
}
return { vaults, workspace };
}
);
return { vaults, workspace };
}
async handleRemoteRepoSelfContained(
opts: CommandOpts
): Promise<{ vaults: DVault[] }> {
return window.withProgress(
{
location: ProgressLocation.Notification,
title: "Adding remote vault",
cancellable: false,
},
async (progress) => {
const { wsRoot } = ExtensionProvider.getDWorkspace();
progress.report({
message: "cloning repo",
increment: 0,
});
const { name, pathRemote: remoteUrl } = opts;
const localUrl = path.join(wsRoot, opts.path);
if (!remoteUrl) {
throw new DendronError({
message:
"Remote vault has no remote set. This should never happen, please send a bug report if you encounter this.",
});
}
await fs.ensureDir(localUrl);
const git = new Git({ localUrl, remoteUrl });
// `.` so it clones into the `localUrl` directory, not into a subdirectory of that
await git.clone(".");
const { vaults, workspace } = await GitUtils.getVaultsFromRepo({
repoPath: localUrl,
wsRoot,
repoUrl: remoteUrl,
});
if (_.size(vaults) === 1 && name) {
vaults[0].name = name;
}
// add all vaults
const increment = 100 / (vaults.length + 1);
progress.report({
message:
vaults.length === 1
? "adding vault"
: `adding ${vaults.length} vaults`,
increment,
});
const wsService = new WorkspaceService({ wsRoot });
if (workspace) {
// This is a backwards-compatibility fix until workspace vaults are
// deprecated. If what we cloned was a workspace, then move it where
// Dendron expects it, because we can't override the path.
const clonedWSPath = path.join(wsRoot, workspace.name);
await fs.move(localUrl, clonedWSPath);
// Because we moved the workspace, we also have to recompute the vaults config.
workspace.vaults = (
await GitUtils.getVaultsFromRepo({
repoPath: clonedWSPath,
repoUrl: remoteUrl,
wsRoot,
})
).vaults;
// Then handle the workspace vault as usual, without self contained vault stuff
await wsService.addWorkspace({ workspace });
await this.addWorkspaceToWorkspace(workspace);
} else {
// Some things, like updating config, can't be parallelized so needs
// to be done one at a time
await asyncLoopOneAtATime(vaults, async (vault) => {
if (VaultUtils.isSelfContained(vault)) {
await this.checkAndWarnTransitiveDeps({ vault, wsRoot });
await wsService.createSelfContainedVault({
vault,
addToConfig: true,
newVault: false,
});
} else {
await wsService.createVault({ vault });
}
await this.addVaultToWorkspace(vault);
progress.report({ increment });
});
}
wsService.dispose();
return { vaults, workspace };
}
);
}
/** If a self contained vault contains transitive dependencies, warn the user
* that they won't be accessible.
*
* Adding transitive deps is not supported yet, this check can be removed once
* support is added.
*/
async checkAndWarnTransitiveDeps(opts: {
vault: SelfContainedVault;
wsRoot: string;
}) {
const vaultRootPath = pathForVaultRoot(opts);
try {
if (
await fs.pathExists(
path.join(vaultRootPath, CONSTANTS.DENDRON_CONFIG_FILE)
)
) {
const vaultConfig = DConfig.getRaw(vaultRootPath) as DendronConfig;
if (ConfigUtils.getVaults(vaultConfig)?.length > 1) {
await AnalyticsUtils.trackForNextRun(
WorkspaceEvents.TransitiveDepsWarningShow
);
// Wait for the user to accept the prompt, otherwise window will
// reload before they see the warning
const openDocsOption = "Open documentation & continue";
const select = await VSCodeUtils.showMessage(
MessageSeverity.WARN,
"The vault you added depends on other vaults, which is not supported.",
{
modal: true,
detail:
"You may be unable to access these transitive vaults. The vault itself should continue to work. Please see for [details]()",
},
{
title: "Continue",
isCloseAffordance: true,
},
{ title: openDocsOption }
);
if (select?.title === openDocsOption) {
// Open a page in the default browser that describes what transitive
// dependencies are, and how to add them.
await PluginFileUtils.openWithDefaultApp(
"https://wiki.dendron.so/notes/q9yo0y7czv8mxlkbnw1ugj1"
);
}
}
}
} catch (err) {
// If anything does fail, ignore the error. This check is not crucial to
// adding a vault, it's better if we let the user keep adding.
Logger.warn({
ctx: "VaultAddCommand.handleRemoteRepoSelfContained",
err,
});
}
}
async addWorkspaceToWorkspace(workspace: DWorkspace) {
const wsRoot = ExtensionProvider.getDWorkspace().wsRoot;
const vaults = workspace.vaults;
// Some things, like updating workspace file, can't be parallelized so needs to be done one at a time
for (const vault of vaults) {
// eslint-disable-next-line no-await-in-loop
await this.addVaultToWorkspace(vault);
}
// add to gitignore
await GitUtils.addToGitignore({
addPath: workspace.name,
root: wsRoot,
noCreateIfMissing: true,
});
const workspaceDir = path.join(wsRoot, workspace.name);
await fs.ensureDir(workspaceDir);
await GitUtils.addToGitignore({
addPath: ".dendron.cache.*",
root: workspaceDir,
});
}
async addVaultToWorkspace(vault: DVault) {
return WorkspaceUtils.addVaultToWorkspace({
vault,
wsRoot: ExtensionProvider.getDWorkspace().wsRoot,
});
}
/**
* Returns all vaults added
* @param opts
* @returns
*/
async execute(opts: CommandOpts) {
const ctx = "VaultAdd";
let vaults: DVault[] = [];
Logger.info({ ctx, msg: "enter", opts });
if (opts.type === VaultType.REMOTE) {
if (opts.isSelfContained) {
({ vaults } = await this.handleRemoteRepoSelfContained(opts));
} else {
({ vaults } = await this.handleRemoteRepo(opts));
}
} else {
const wsRoot = ExtensionProvider.getDWorkspace().wsRoot;
const fsPath = VaultUtils.normVaultPath({
vault: { fsPath: opts.path },
wsRoot,
});
const wsService = new WorkspaceService({ wsRoot });
const vault: DVault = {
fsPath,
};
// Make sure these don't get set to undefined, or serialization breaks
if (opts.isSelfContained) {
vault.selfContained = true;
}
if (opts.name) {
vault.name = opts.name;
}
if (VaultUtils.isSelfContained(vault)) {
await wsService.createSelfContainedVault({
vault,
addToConfig: true,
addToCodeWorkspace: false,
newVault: true,
});
} else {
await wsService.createVault({ vault });
}
await this.addVaultToWorkspace(vault);
vaults = [vault];
}
window.showInformationMessage("finished adding vault");
await commands.executeCommand("workbench.action.reloadWindow");
return { vaults };
}
}