/
storev2.ts
1564 lines (1458 loc) · 47.3 KB
/
storev2.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
assert,
BacklinkUtils,
BulkWriteNotesOpts,
ConfigUtils,
CONSTANTS,
DeleteSchemaResp,
DendronCompositeError,
DendronError,
DEngineClient,
DHookEntry,
DLink,
DLinkUtils,
DNodeUtils,
DNoteAnchorPositioned,
DNoteLoc,
DStore,
DVault,
EngineDeleteOpts,
EngineSchemaWriteOpts,
EngineUpdateNodesOptsV2,
EngineWriteOptsV2,
error2PlainObject,
ErrorUtils,
ERROR_SEVERITY,
ERROR_STATUS,
FindNoteOpts,
GetSchemaResp,
IDendronError,
DendronConfig,
isNotUndefined,
NoteChangeEntry,
NoteChangeUpdateEntry,
NoteDictsUtils,
NoteFnameDictUtils,
NoteProps,
NotePropsByFnameDict,
NotePropsByIdDict,
NotesCacheEntryMap,
NoteUtils,
RenameNoteOpts,
RespV3,
RespWithOptError,
SchemaModuleDict,
SchemaModuleProps,
SchemaUtils,
StoreV2InitResp,
stringifyError,
TAGS_HIERARCHY,
TimeUtils,
USERS_HIERARCHY,
USER_MESSAGES,
VaultUtils,
WriteNoteResp,
WriteSchemaResp,
} from "@dendronhq/common-all";
import {
DConfig,
DLogger,
file2Note,
getAllFiles,
getDurationMilliseconds,
note2File,
schemaModuleProps2File,
vault2Path,
} from "@dendronhq/common-server";
import { LinkUtils } from "@dendronhq/unified";
import fs from "fs-extra";
import _ from "lodash";
import path from "path";
import { URI } from "vscode-uri";
import { NotesFileSystemCache } from "../../cache";
import { HookUtils, RequireHookResp } from "../../topics/hooks";
import { InMemoryNoteCache } from "../../util/inMemoryNoteCache";
import { EngineUtils } from "../../utils";
import { SQLiteMetadataStore } from "../SQLiteMetadataStore";
import { NoteParser } from "./noteParser";
import { SchemaParser } from "./schemaParser";
export type DEngineInitSchemaResp = RespWithOptError<SchemaModuleProps[]>;
export class FileStorage implements DStore {
public vaults: DVault[];
/**
* Warning: currently this note dictionary contains backlink data that gets
* populated upon initialization. However, the update note operations do not change
* the backlink data in this dictionary hence it starts to contain stale backlink data.
* */
public notes: NotePropsByIdDict;
public noteFnames: NotePropsByFnameDict;
public schemas: SchemaModuleDict;
public logger: DLogger;
public anchors: DNoteAnchorPositioned[];
public wsRoot: string;
public config: DendronConfig;
private engine: DEngineClient;
constructor(props: {
engine: DEngineClient;
logger: DLogger;
config: DendronConfig;
}) {
const { vaults, wsRoot } = props.engine;
const { logger, config } = props;
this.wsRoot = wsRoot;
this.vaults = vaults;
this.notes = {};
this.noteFnames = {};
this.schemas = {};
this.anchors = [];
this.logger = logger;
this.config = config;
const ctx = "FileStorageV2";
this.logger.info({ ctx, wsRoot, vaults, level: this.logger.level });
this.engine = props.engine;
}
async init(): Promise<StoreV2InitResp> {
const ctx = "FileStorage:init";
let errors: IDendronError<any>[] = [];
try {
const resp = await this.initSchema();
if (resp.error) {
errors.push(FileStorage.createMalformedSchemaError(resp));
}
resp.data.map((ent) => {
this.schemas[ent.root.id] = ent;
});
const { errors: initErrors } = await this.initNotes();
errors = errors.concat(initErrors);
this.logger.info({ ctx, msg: "post:initNotes", errors });
// Backlink candidates have to be done after notes are initialized because it depends on the engine already having notes in it
if (this.config.dev?.enableLinkCandidates) {
const ctx = "_addLinkCandidates";
const start = process.hrtime();
this.logger.info({ ctx, msg: "pre:addLinkCandidates" });
// this mutates existing note objects so we don't need to reset the notes
this._addLinkCandidates();
const duration = getDurationMilliseconds(start);
this.logger.info({ ctx, duration });
}
const { notes, schemas, config } = this;
let error: IDendronError | undefined = errors[0];
if (errors.length > 1) {
error = new DendronCompositeError(errors);
}
this.logger.info({ ctx, msg: "exit" });
return {
data: {
notes,
schemas,
config,
wsRoot: this.wsRoot,
vaults: this.vaults,
},
error,
};
} catch (err) {
this.logger.error(err);
throw err;
}
}
static createMalformedSchemaError(resp: DEngineInitSchemaResp) {
let fileName = USER_MESSAGES.UNKNOWN;
try {
if (resp.error && resp.error.payload) {
fileName = JSON.parse(JSON.parse(resp.error.payload)[0].payload).fpath;
}
} catch (parseErr) {
fileName = USER_MESSAGES.UNKNOWN;
}
let fullPath;
try {
if (resp.error && resp.error.payload) {
fullPath = JSON.parse(
JSON.parse(resp.error.payload)[0].payload
).fullPath;
}
} catch (parseErr) {
fullPath = undefined;
}
let reason = USER_MESSAGES.UNKNOWN;
try {
if (resp.error && resp.error.payload) {
reason = JSON.parse(JSON.parse(resp.error.payload)[0].payload).message;
}
} catch (parseErr) {
reason = USER_MESSAGES.UNKNOWN;
}
return new DendronError({
message: `Schema '${fileName}' is malformed. Reason: ${reason}`,
severity: ERROR_SEVERITY.MINOR,
payload: { schema: resp.error, fullPath },
});
}
/**
* See {@link DStore.getNote}
*/
async getNote(id: string): Promise<RespV3<NoteProps>> {
const maybeNote = this.notes[id];
if (maybeNote) {
return { data: _.cloneDeep(maybeNote) };
} else {
return {
error: DendronError.createFromStatus({
status: ERROR_STATUS.CONTENT_NOT_FOUND,
message: `NoteProps not found for key ${id}.`,
severity: ERROR_SEVERITY.MINOR,
}),
};
}
}
/**
* See {@link DStore.findNotes}
*/
async findNotes(opts: FindNoteOpts): Promise<NoteProps[]> {
const { fname, vault, excludeStub } = opts;
if (!fname && !vault && _.isUndefined(excludeStub)) {
return [];
}
let notes: NoteProps[];
if (fname) {
notes = NoteDictsUtils.findByFname({
fname,
noteDicts: { notesById: this.notes, notesByFname: this.noteFnames },
vault,
});
} else if (vault) {
notes = _.values(this.notes).filter((note) =>
VaultUtils.isEqualV2(note.vault, vault)
);
} else {
notes = _.values(this.notes);
}
if (excludeStub) {
notes = notes.filter((note) => note.stub !== true);
}
return _.cloneDeep(notes);
}
/**
*
* @param id id of note to be deleted
* @returns
*/
async deleteNote(
id: string,
opts?: EngineDeleteOpts
): Promise<NoteChangeEntry[]> {
const ctx = "deleteNote";
if (id === "root") {
throw new DendronError({
message: "",
status: ERROR_STATUS.CANT_DELETE_ROOT,
});
}
const noteToDelete = this.notes[id];
this.logger.info({ ctx, noteToDelete, opts, id });
if (_.isUndefined(noteToDelete))
throw new DendronError({
message: `Unable to find node ${id}`,
severity: ERROR_SEVERITY.FATAL,
payload: ctx,
});
const ext = ".md";
const vault = noteToDelete.vault;
const vpath = vault2Path({ vault, wsRoot: this.wsRoot });
const fpath = path.join(vpath, noteToDelete.fname + ext);
let out: NoteChangeEntry[] = [];
const noteAsLog = NoteUtils.toLogObj(noteToDelete);
// if have children, create stub note with a new id
if (!_.isEmpty(noteToDelete.children)) {
const replacingStub = NoteUtils.create({
// the replacing stub should not keep the old note's body and link.
// otherwise, it will be captured while processing links and will
// fail because this note is not actually in the file system.
..._.omit(noteToDelete, ["id", "links", "body"]),
stub: true,
});
this.logger.info({ ctx, noteAsLog, msg: "delete from parent" });
if (!noteToDelete.parent) {
throw DendronError.createFromStatus({
status: ERROR_STATUS.NO_PARENT_FOR_NOTE,
});
}
const parentNote: NoteProps | undefined = this.notes[noteToDelete.parent];
if (parentNote) {
const parentNotePrev = { ...parentNote };
DNodeUtils.removeChild(parentNote, noteToDelete);
DNodeUtils.addChild(parentNote, replacingStub);
out.push({
note: parentNote,
status: "update",
prevNote: parentNotePrev,
});
} else {
this.logger.error({
ctx,
noteToDelete,
message: "Parent note missing from state",
});
}
// Update children's parent id to new note
noteToDelete.children.forEach((child) => {
const childNote = this.notes[child];
const prevChildNoteState = { ...childNote };
childNote.parent = replacingStub.id;
// add one entry for each child updated
out.push({
prevNote: prevChildNoteState,
note: childNote,
status: "update",
});
});
await this.updateNote(replacingStub);
out.push({ note: replacingStub, status: "create" });
} else {
// no children, delete reference from parent
this.logger.info({ ctx, noteAsLog, msg: "delete from parent" });
if (!noteToDelete.parent) {
throw DendronError.createFromStatus({
status: ERROR_STATUS.NO_PARENT_FOR_NOTE,
});
}
// remove from parent
const resps: Promise<NoteChangeEntry[]>[] = [];
let parentNote = this.notes[noteToDelete.parent];
if (parentNote) {
const parentNotePrev = { ...parentNote };
parentNote.children = _.reject(
parentNote.children,
(ent) => ent === noteToDelete.id
);
// if parent note is not a stub, update it
if (!parentNote.stub) {
out.push({
note: parentNote,
status: "update",
prevNote: parentNotePrev,
});
}
// check all stubs
while (parentNote.stub && !opts?.noDeleteParentStub) {
const newParent = parentNote.parent;
const resp = this.deleteNote(parentNote.id, {
metaOnly: true,
noDeleteParentStub: true,
});
resps.push(resp);
if (newParent) {
parentNote = this.notes[newParent];
} else {
assert(false, "illegal state in note delete");
}
}
} else {
this.logger.error({
ctx,
noteToDelete,
message: "Parent note missing from state",
});
}
for (const resp of await Promise.all(resps)) {
out = out.concat(resp);
}
}
// remove from fs
if (!opts?.metaOnly) {
this.logger.info({ ctx, noteAsLog, msg: "removing from disk", fpath });
await fs.unlink(fpath);
}
// delete from note dictionary
NoteDictsUtils.delete(noteToDelete, {
notesById: this.notes,
notesByFname: this.noteFnames,
});
// Remove backlinks if applicable
const backlinkChanges = await Promise.all(
noteToDelete.links.map((link) => this.removeBacklink(link))
);
out = out.concat(backlinkChanges.flat());
out.push({ note: noteToDelete, status: "delete" });
return out;
}
getSchema(id: string): Promise<GetSchemaResp> {
return Promise.resolve({ data: this.schemas[id] });
}
async deleteSchema(
id: string,
opts?: EngineDeleteOpts
): Promise<DeleteSchemaResp> {
const ctx = "deleteSchema";
this.logger.info({ ctx, msg: "enter", id });
if (id === "root") {
throw DendronError.createFromStatus({
status: ERROR_STATUS.CANT_DELETE_ROOT,
});
}
const schemaToDelete = this.schemas[id];
const ext = ".schema.yml";
const vault = schemaToDelete.vault;
const vpath = vault2Path({ vault, wsRoot: this.wsRoot });
const fpath = path.join(vpath, schemaToDelete.fname + ext);
if (!opts?.metaOnly) {
fs.unlinkSync(fpath);
}
delete this.schemas[id];
return this.init();
}
async initSchema(): Promise<DEngineInitSchemaResp> {
const ctx = "initSchema";
this.logger.info({ ctx, msg: "enter" });
const out = await Promise.all(
(this.vaults as DVault[]).map(async (vault) => {
return this._initSchema(vault);
})
);
const _out = _.reduce<
{ data: SchemaModuleProps[]; errors: any[] },
{ data: SchemaModuleProps[]; errors: any[] }
>(
out,
(ent, acc) => {
acc.data = acc.data.concat(ent.data);
acc.errors = acc.errors.concat(ent.errors);
return acc;
},
{ data: [], errors: [] }
);
const { data, errors } = _out;
const result = {
data,
error: _.isEmpty(errors)
? undefined
: new DendronError({ message: "multiple errors", payload: errors }),
};
return result;
}
async _initSchema(
vault: DVault
): Promise<{ data: SchemaModuleProps[]; errors: any[] }> {
const ctx = "initSchema";
this.logger.info({ ctx, msg: "enter" });
const vpath = vault2Path({ vault, wsRoot: this.wsRoot });
const out = await getAllFiles({
root: URI.file(vpath),
include: ["*.schema.yml"],
});
if (out.error || !out.data) {
return {
data: [],
errors: [
new DendronError({
message: `Unable to get schemas for vault ${VaultUtils.getName(
vault
)}`,
severity: ERROR_SEVERITY.MINOR,
payload: out.error,
}),
],
};
}
const schemaFiles = out.data.map((entry) => entry.toString());
this.logger.info({ ctx, schemaFiles });
if (_.isEmpty(schemaFiles)) {
throw DendronError.createFromStatus({
status: ERROR_STATUS.NO_SCHEMA_FOUND,
message: JSON.stringify(vault),
});
}
const { schemas, errors } = await new SchemaParser({
wsRoot: this.wsRoot,
logger: this.logger,
}).parse(schemaFiles, vault);
return {
data: schemas,
errors: _.isNull(errors) ? [] : errors,
};
}
async initNotes(): Promise<{
errors: IDendronError[];
}> {
const ctx = "initNotes";
this.logger.info({ ctx, msg: "enter" });
let notesWithLinks: NoteProps[] = [];
let errors: IDendronError<any>[] = [];
const start = process.hrtime();
// instantiate so we can use singleton later
if (this.config.workspace.metadataStore === "sqlite") {
// eslint-disable-next-line no-new
const store = new SQLiteMetadataStore({
wsRoot: this.wsRoot,
force: true,
});
// sleep until store is done
const output = await TimeUtils.awaitWithLimit(
{ limitMs: 6e4 },
async () => {
while (store.status === "loading") {
this.logger.info({ ctx, msg: "downloading sql dependencies..." });
// eslint-disable-next-line no-await-in-loop
await TimeUtils.sleep(1000);
}
return;
}
);
this.logger.info({
ctx,
msg: "checking if sql is initialized...",
output,
});
if (!(await SQLiteMetadataStore.isDBInitialized())) {
await SQLiteMetadataStore.createAllTables();
await SQLiteMetadataStore.createWorkspace(this.wsRoot);
}
}
const out = await Promise.all(
(this.vaults as DVault[]).map(async (vault) => {
const {
notesById,
cacheUpdates,
errors: initErrors,
} = await this._initNotes(vault);
errors = errors.concat(initErrors);
notesWithLinks = notesWithLinks.concat(
_.filter(notesById, (n) => !_.isEmpty(n.links))
);
this.logger.info({
ctx,
vault,
numEntries: _.size(notesById),
numCacheUpdates: _.size(cacheUpdates),
});
return notesById;
})
);
this.notes = Object.assign({}, ...out);
this.noteFnames = NoteFnameDictUtils.createNotePropsByFnameDict(this.notes);
const allNotes = _.values(this.notes);
if (_.size(this.notes) === 0) {
errors.push(
new DendronError({
message: "No vaults initialized!",
severity: ERROR_SEVERITY.FATAL,
})
);
}
this._addBacklinks({ notesWithLinks, allNotes });
const duration = getDurationMilliseconds(start);
this.logger.info({ ctx, msg: `time to init notes: "${duration}" ms` });
return { errors };
}
/** Adds backlinks mutating 'allNotes' argument in place. */
private _addBacklinks({
notesWithLinks,
allNotes,
}: {
notesWithLinks: NoteProps[];
allNotes: NoteProps[];
}): void {
const ctx = "_addBacklinks:ext";
const start = process.hrtime();
this._addBacklinksImpl(allNotes, notesWithLinks);
const duration = getDurationMilliseconds(start);
this.logger.info({ ctx, duration });
}
private _addBacklinksImpl(
allNotes: NoteProps[],
notesWithLinks: NoteProps[]
) {
const noteCache = new InMemoryNoteCache(allNotes);
notesWithLinks.forEach((noteFrom) => {
let _noteToForErrorLog: NoteProps | undefined;
try {
noteFrom.links.forEach((link) => {
const maybeBacklink = BacklinkUtils.createFromDLink(link);
if (maybeBacklink) {
const notes = noteCache.getNotesByFileNameIgnoreCase(
link.to!.fname!
);
notes.forEach((noteTo: NoteProps) => {
_noteToForErrorLog = noteTo;
BacklinkUtils.addBacklinkInPlace({
note: noteTo,
backlink: maybeBacklink,
});
});
}
});
} catch (err: any) {
const error = error2PlainObject(err);
this.logger.error({
error,
noteFrom: NoteUtils.toLogObj(noteFrom),
noteTo: _noteToForErrorLog
? NoteUtils.toLogObj(_noteToForErrorLog)
: null,
message: "issue with backlinks",
});
}
});
}
private _addLinkCandidates() {
return _.map(this.notes, (noteFrom: NoteProps) => {
try {
const maxNoteLength = ConfigUtils.getWorkspace(
this.config
).maxNoteLength;
if (
noteFrom.body.length <
(maxNoteLength || CONSTANTS.DENDRON_DEFAULT_MAX_NOTE_LENGTH)
) {
const linkCandidates = LinkUtils.findLinkCandidatesSync({
note: noteFrom,
noteDicts: {
notesById: this.notes,
notesByFname: this.noteFnames,
},
config: this.config,
});
noteFrom.links = noteFrom.links.concat(linkCandidates);
}
} catch (err: any) {
const error = error2PlainObject(err);
this.logger.error({
error,
noteFrom,
message: "issue with link candidates",
});
return;
}
});
}
async _initNotes(vault: DVault): Promise<{
notesById: NotePropsByIdDict;
cacheUpdates: NotesCacheEntryMap;
errors: IDendronError[];
}> {
const ctx = "initNotes";
let errors: IDendronError[] = [];
this.logger.info({ ctx, msg: "enter" });
const wsRoot = this.wsRoot;
const vpath = vault2Path({ vault, wsRoot });
const out = await getAllFiles({
root: URI.file(vpath),
include: ["*.md"],
});
if (out.error) {
// Keep initializing other vaults
errors.push(
new DendronError({
message: `Unable to read notes for vault ${VaultUtils.getName(
vault
)}`,
severity: ERROR_SEVERITY.MINOR,
payload: out.error,
})
);
}
const cachePath = path.join(vpath, CONSTANTS.DENDRON_CACHE_FILE);
const notesCache: NotesFileSystemCache = new NotesFileSystemCache({
cachePath,
// TODO: remove caching logic later
// noCaching: this.config.noCaching,
noCaching: false,
logger: this.logger,
});
if (!out.data) {
return {
cacheUpdates: {},
errors,
notesById: {},
};
}
const noteFiles = out.data;
const {
notesById,
cacheUpdates,
errors: parseErrors,
} = await new NoteParser({
store: this,
cache: notesCache,
engine: this.engine,
logger: this.logger,
}).parseFiles(noteFiles, vault, this.schemas, {
useSQLiteMetadataStore: this.config.workspace.metadataStore === "sqlite",
});
errors = errors.concat(parseErrors);
this.logger.info({ ctx, msg: "parseNotes:fin" });
return { notesById, cacheUpdates, errors };
}
async bulkWriteNotes(opts: BulkWriteNotesOpts) {
this.logger.info({ ctx: "bulkWriteNotes", msg: "enter" });
if (opts.skipMetadata) {
const noteDicts = {
notesById: this.notes,
notesByFname: this.noteFnames,
};
await Promise.all(
opts.notes.map((note) => {
NoteDictsUtils.add(note, noteDicts);
return note2File({
note,
vault: note.vault,
wsRoot: this.wsRoot,
});
})
);
const notesChanged: NoteChangeEntry[] = opts.notes.map((n) => {
return { note: n, status: "create" as const };
});
return {
data: notesChanged,
};
}
const writeResponses = await Promise.all(
opts.notes.flatMap(async (note) => {
return this.writeNote(note, opts.opts);
})
);
const errors = writeResponses
.flatMap((response) => response.error)
.filter(isNotUndefined);
return {
error: errors.length > 0 ? new DendronCompositeError(errors) : undefined,
data: writeResponses
.flatMap((response) => response.data)
.filter(isNotUndefined),
};
}
private referenceRangeParts(anchorHeader?: string): string[] {
if (!anchorHeader || anchorHeader.indexOf(":") === -1) return [];
let [start, end] = anchorHeader.split(":");
start = start.replace(/^#*/, "");
end = end.replace(/^#*/, "");
return [start, end];
}
/**
* Update the links inside this note that need to be updated for the rename from `oldLoc` to `newLoc`
* Will update the note in place
*/
private async processNoteChangedByRename({
note,
oldLoc,
newLoc,
}: {
note: NoteProps;
oldLoc: DNoteLoc;
newLoc: DNoteLoc;
}): Promise<NoteChangeUpdateEntry | undefined> {
const ctx = "store:processNoteChangedByRename";
const prevNote = { ...note };
const vault = note.vault;
const vaultPath = vault2Path({ vault, wsRoot: this.wsRoot });
// read note in case its changed
const resp = file2Note(path.join(vaultPath, note.fname + ".md"), vault);
if (ErrorUtils.isErrorResp(resp)) {
// couldn't read note. log it and return.
this.logger.error({ ctx, error: stringifyError(resp.error) });
return;
}
const _n = resp.data;
const foundLinks = LinkUtils.findLinksFromBody({
note: _n,
filter: { loc: oldLoc },
config: this.config,
});
// important to order by position since we replace links and this affects
// subsequent links
let allLinks = _.orderBy(
foundLinks,
(link) => {
return link.position?.start.offset;
},
"desc"
);
// perform header updates as needed
if (
oldLoc.fname.toLowerCase() === newLoc.fname.toLowerCase() &&
// TODO: we don't have a spec on vault name but to be consistent, we should also lowercase
oldLoc.vaultName === newLoc.vaultName &&
oldLoc.anchorHeader &&
newLoc.anchorHeader
) {
// Renaming the header, only update links that link to the old header
allLinks = _.filter(allLinks, (link): boolean => {
// This is a wikilink to this header
if (link.to?.anchorHeader === oldLoc.anchorHeader) return true;
// Or this is a range reference, and one part of the range includes this header
return (
link.type === "ref" &&
isNotUndefined(oldLoc.anchorHeader) &&
this.referenceRangeParts(link.to?.anchorHeader).includes(
oldLoc.anchorHeader
)
);
});
}
// filter all links for following criteria:
// - only modify links that have same _to_ vault name
// - explicitly same: has vault prefix
// - implicitly same: to.vaultName is undefined, but link is in a note that's in the vault.
allLinks = allLinks.filter((link) => {
const oldLocVaultName = oldLoc.vaultName as string;
const explicitlySameVault = link.to?.vaultName === oldLocVaultName;
const oldLocVault = VaultUtils.getVaultByName({
vaults: this.vaults,
vname: oldLocVaultName,
});
const implicitlySameVault =
_.isUndefined(link.to?.vaultName) && _.isEqual(note.vault, oldLocVault);
return explicitlySameVault || implicitlySameVault;
});
// perform link substitution
// TODO: this should be extracted into a re-usable utility since it comes up quite a lot
const noteMod = _.reduce(
allLinks,
(note: NoteProps, link: DLink) => {
const oldLink = LinkUtils.dlink2DNoteLink(link);
// current implementation adds alias for all notes
// check if old note has alias thats different from its fname
let alias: string | undefined;
if (oldLink.from.alias && oldLink.from.alias !== oldLink.from.fname) {
alias = oldLink.from.alias;
// Update the alias if it was using the default alias.
if (
oldLoc.alias?.toLocaleLowerCase() ===
oldLink.from.alias.toLocaleLowerCase() &&
newLoc.alias
) {
alias = newLoc.alias;
}
}
// for hashtag links, we'll have to regenerate the alias
if (newLoc.fname.startsWith(TAGS_HIERARCHY)) {
const fnameWithoutTag = newLoc.fname.slice(TAGS_HIERARCHY.length);
// Frontmatter tags don't have the hashtag
if (link.type !== "frontmatterTag") alias = `#${fnameWithoutTag}`;
else alias = fnameWithoutTag;
} else if (oldLink.from.fname.startsWith(TAGS_HIERARCHY)) {
// If this used to be a hashtag but no longer is, the alias is like `#foo.bar` and no longer makes sense.
// And if this used to be a frontmatter tag, the alias being undefined will force it to be removed because a frontmatter tag can't point to something outside of tags hierarchy.
alias = undefined;
}
// for user tag links, we'll have to regenerate the alias
if (link.type !== "ref" && newLoc.fname.startsWith(USERS_HIERARCHY)) {
const fnameWithoutTag = newLoc.fname.slice(USERS_HIERARCHY.length);
alias = `@${fnameWithoutTag}`;
} else if (oldLink.from.fname.startsWith(USERS_HIERARCHY)) {
// If this used to be a user tag but no longer is, the alias is like `@foo.bar` and no longer makes sense.
alias = undefined;
}
// Correctly handle header renames in references with range based references
if (
oldLoc.anchorHeader &&
link.type === "ref" &&
isNotUndefined(oldLink.from.anchorHeader) &&
oldLink.from.anchorHeader.indexOf(":") > -1 &&
isNotUndefined(newLoc.anchorHeader) &&
newLoc.anchorHeader.indexOf(":") === -1
) {
// This is a reference, old anchor had a ":" in it, a new anchor header is provided and does not have ":" in it.
// For example, `![[foo#start:#end]]` to `![[foo#something]]`. In this case, `something` is actually supposed to replace only one part of the range.
// Find the part that matches the old header, and replace just that with the new one.
let [start, end] = this.referenceRangeParts(
oldLink.from.anchorHeader
);
if (start === oldLoc.anchorHeader) start = newLoc.anchorHeader;
if (end === oldLoc.anchorHeader) end = newLoc.anchorHeader;
newLoc.anchorHeader = `${start}:#${end}`;
}
const newBody = LinkUtils.updateLink({
note,
oldLink,
newLink: {
...oldLink,
from: {
...newLoc,
anchorHeader: newLoc.anchorHeader || oldLink.from.anchorHeader,
alias,
},
},
});
_n.body = newBody;
return _n;
},
_n
);
// replace note body if needed
const shouldChange = !(
note.body === noteMod.body && note.tags === noteMod.tags
);
if (shouldChange) {
note.body = noteMod.body;
note.tags = noteMod.tags;
return {
note,
prevNote,
status: "update",
};
}
return;
}
async renameNote(opts: RenameNoteOpts): Promise<NoteChangeEntry[]> {
const ctx = "Store:renameNote";
const { oldLoc, newLoc } = opts;
const { wsRoot } = this;
this.logger.info({ ctx, msg: "enter", opts });
const oldVault = VaultUtils.getVaultByName({
vaults: this.engine.vaults,
vname: oldLoc.vaultName!,
});
if (!oldVault) {
throw new DendronError({ message: "vault not set for loation" });
}
const vpath = vault2Path({ wsRoot, vault: oldVault });
const oldLocPath = path.join(vpath, oldLoc.fname + ".md");
// TODO: Move this business logic to engine so we can update metadata
// read from disk since contents might have changed
const resp = file2Note(oldLocPath, oldVault);
if (ErrorUtils.isErrorResp(resp)) {
throw new DendronError({ message: "file not found" });
}
const noteRaw = resp.data;
if (!this.notes[noteRaw.id]) {
throw new DendronError({
status: ERROR_STATUS.DOES_NOT_EXIST,
message:
`Unable to rename note "${
noteRaw.fname
}" in vault "${VaultUtils.getName(noteRaw.vault)}".` +
` Check that this note exists, and make sure it has a frontmatter with an id.`,
severity: ERROR_SEVERITY.FATAL,
});
}
const oldNote = NoteUtils.hydrate({
noteRaw,
noteHydrated: this.notes[noteRaw.id],
opts: { keepBackLinks: true },