-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathTemplateEngine.ts
More file actions
672 lines (579 loc) · 18.6 KB
/
TemplateEngine.ts
File metadata and controls
672 lines (579 loc) · 18.6 KB
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
import { QuickAddEngine } from "./QuickAddEngine";
import { CompleteFormatter } from "../formatters/completeFormatter";
import type { LinkToCurrentFileBehavior } from "../formatters/formatter";
import type { App } from "obsidian";
import { Notice, TFile } from "obsidian";
import type QuickAdd from "../main";
import {
getTemplater,
overwriteTemplaterOnce,
templaterParseTemplate,
} from "../utilityObsidian";
import GenericSuggester from "../gui/GenericSuggester/genericSuggester";
import InputSuggester from "../gui/InputSuggester/inputSuggester";
import { MARKDOWN_FILE_EXTENSION_REGEX, CANVAS_FILE_EXTENSION_REGEX } from "../constants";
import { reportError } from "../utils/errorUtils";
import { basenameWithoutMdOrCanvas } from "../utils/pathUtils";
import {
INVALID_FOLDER_CHARS_REGEX,
INVALID_FOLDER_CONTROL_CHARS_REGEX,
INVALID_FOLDER_TRAILING_CHARS_REGEX,
isReservedWindowsDeviceName,
} from "../utils/pathValidation";
import { MacroAbortError } from "../errors/MacroAbortError";
import { isCancellationError } from "../utils/errorUtils";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import { log } from "../logger/logManager";
type FolderChoiceOptions = {
allowCreate?: boolean;
placeholder?: string;
allowedRoots?: string[];
topItems?: Array<{ path: string; label: string }>;
};
type FolderSelectionContext = {
items: string[];
displayItems: string[];
normalizedItems: string[];
canonicalByNormalized: Map<string, string>;
displayByNormalized: Map<string, string>;
existingSet: Set<string>;
allowCreate: boolean;
allowedRoots: string[];
placeholder?: string;
};
type FolderSelection = {
raw: string;
normalized: string;
resolved: string;
exists: boolean;
isAllowed: boolean;
isEmpty: boolean;
};
class InvalidFolderPathError extends Error {
constructor(message: string) {
super(message);
this.name = "InvalidFolderPathError";
}
}
function isMacroAbortError(error: unknown): error is MacroAbortError {
return (
error instanceof MacroAbortError ||
(Boolean(error) &&
typeof error === "object" &&
"name" in (error as Record<string, unknown>) &&
(error as { name?: string }).name === "MacroAbortError")
);
}
export abstract class TemplateEngine extends QuickAddEngine {
protected formatter: CompleteFormatter;
protected readonly templater;
protected constructor(
app: App,
protected plugin: QuickAdd,
choiceFormatter?: IChoiceExecutor
) {
super(app);
this.templater = getTemplater(app);
this.formatter = new CompleteFormatter(app, plugin, choiceFormatter);
}
public abstract run():
| Promise<void>
| Promise<string>
| Promise<{ file: TFile; content: string }>;
protected async getOrCreateFolder(
folders: string[],
options: FolderChoiceOptions = {},
): Promise<string> {
const context = this.buildFolderSelectionContext(folders, options);
if (!this.shouldPromptForFolder(context)) {
return await this.handleSingleSelection(context);
}
const selection = await this.promptUntilAllowed(context);
return selection.isEmpty ? "" : selection.resolved;
}
private buildFolderSelectionContext(
folders: string[],
options: FolderChoiceOptions,
): FolderSelectionContext {
const allowCreate = options.allowCreate ?? false;
const allowedRoots =
options.allowedRoots?.map((root) => this.normalizeFolderPath(root)) ?? [];
const {
items,
displayItems,
normalizedItems,
canonicalByNormalized,
displayByNormalized,
} = this.buildFolderSuggestions(
folders,
options.topItems ?? [],
allowedRoots.length > 0 ? allowedRoots : undefined,
);
return {
items,
displayItems,
normalizedItems,
canonicalByNormalized,
displayByNormalized,
existingSet: new Set(normalizedItems),
allowCreate,
allowedRoots,
placeholder: options.placeholder,
};
}
private shouldPromptForFolder(context: FolderSelectionContext): boolean {
return (
context.items.length > 1 ||
(context.allowCreate && context.items.length === 0)
);
}
private async promptForFolder(context: FolderSelectionContext): Promise<string> {
try {
if (context.allowCreate) {
return await InputSuggester.Suggest(
this.app,
context.displayItems,
context.items,
{
placeholder:
context.placeholder ?? "Choose a folder or type to create one",
renderItem: (item, el) => {
this.renderFolderSuggestion(
item,
el,
context.existingSet,
context.displayByNormalized,
);
},
},
);
}
return await GenericSuggester.Suggest(
this.app,
context.displayItems,
context.items,
context.placeholder,
);
} catch (error) {
if (isCancellationError(error)) {
throw new MacroAbortError("Input cancelled by user");
}
throw error;
}
}
private async resolveSelection(
raw: string,
context: FolderSelectionContext,
): Promise<FolderSelection> {
const normalized = this.normalizeFolderPath(raw);
const isEmpty = normalized.length === 0;
const canonical = context.canonicalByNormalized.get(normalized);
const resolved = canonical ?? normalized;
const exists = isEmpty
? false
: canonical !== undefined ||
(await this.app.vault.adapter.exists(resolved));
const isAllowed =
context.allowedRoots.length === 0
? true
: this.isPathAllowed(isEmpty ? "" : resolved, context.allowedRoots);
return {
raw,
normalized,
resolved,
exists,
isAllowed,
isEmpty,
};
}
private async promptUntilAllowed(
context: FolderSelectionContext,
): Promise<FolderSelection> {
// Keep prompting until the user provides an allowed selection or cancels.
for (;;) {
const raw = await this.promptForFolder(context);
const selection = await this.resolveSelection(raw, context);
if (selection.isEmpty) {
if (!selection.isAllowed) {
this.showFolderNotAllowedNotice(context.allowedRoots);
continue;
}
return selection;
}
if (!selection.isAllowed) {
this.showFolderNotAllowedNotice(context.allowedRoots);
continue;
}
try {
this.validateFolderPath(selection.resolved);
} catch (error) {
if (error instanceof InvalidFolderPathError) {
new Notice(error.message);
continue;
}
throw error;
}
await this.ensureFolderExists(selection);
return selection;
}
}
private async ensureFolderExists(selection: FolderSelection): Promise<void> {
if (selection.isEmpty || selection.exists) return;
await this.createFolder(selection.resolved);
}
private async handleSingleSelection(
context: FolderSelectionContext,
): Promise<string> {
const raw = context.items[0] ?? "";
const selection = await this.resolveSelection(raw, context);
if (selection.isEmpty) return "";
if (!selection.isAllowed) {
this.showFolderNotAllowedNotice(context.allowedRoots);
throw new MacroAbortError("Selected folder not allowed.");
}
if (selection.resolved) {
try {
this.validateFolderPath(selection.resolved);
} catch (error) {
if (error instanceof InvalidFolderPathError) {
new Notice(error.message);
return "";
}
throw error;
}
}
await this.ensureFolderExists(selection);
return selection.resolved;
}
private normalizeFolderPath(path: string): string {
return path.trim().replace(/^\/+/, "").replace(/\/+$/, "");
}
private validateFolderPath(path: string): void {
const trimmed = path.trim();
if (!trimmed) return;
const segments = trimmed.split("/");
for (const segment of segments) {
this.validateFolderSegment(segment);
}
}
private validateFolderSegment(segment: string): void {
if (!segment) {
throw new InvalidFolderPathError("Folder name cannot be empty.");
}
if (segment === "." || segment === "..") {
throw new InvalidFolderPathError("Folder name cannot be '.' or '..'.");
}
if (INVALID_FOLDER_CONTROL_CHARS_REGEX.test(segment)) {
throw new InvalidFolderPathError(
"Folder name cannot contain control characters.",
);
}
if (INVALID_FOLDER_CHARS_REGEX.test(segment)) {
throw new InvalidFolderPathError(
"Folder name cannot contain any of the following characters: \\ / : * ? \" < > |",
);
}
if (INVALID_FOLDER_TRAILING_CHARS_REGEX.test(segment)) {
throw new InvalidFolderPathError(
"Folder name cannot end with a space or a period.",
);
}
const normalized = segment.replace(/[. ]+$/u, "");
const base = normalized.split(".")[0] ?? "";
if (base && isReservedWindowsDeviceName(base)) {
throw new InvalidFolderPathError(
"Folder name cannot be a reserved name like CON, PRN, AUX, NUL, COM1-9, or LPT1-9.",
);
}
}
private isPathAllowed(path: string, roots: string[]): boolean {
const normalizedPath = this.normalizeFolderPath(path);
for (const root of roots) {
if (!root) return true;
if (normalizedPath === root) return true;
if (normalizedPath.startsWith(`${root}/`)) return true;
}
return false;
}
private showFolderNotAllowedNotice(roots: string[]): void {
const displayRoots = roots.map((root) => (root ? root : "/"));
const list =
displayRoots.length > 3
? `${displayRoots.slice(0, 3).join(", ")}...`
: displayRoots.join(", ");
new Notice(`Folder must be under: ${list}`);
}
private buildFolderSuggestions(
folders: string[],
topItems: Array<{ path: string; label: string }>,
allowedRoots?: string[],
): {
items: string[];
displayItems: string[];
normalizedItems: string[];
canonicalByNormalized: Map<string, string>;
displayByNormalized: Map<string, string>;
} {
const items: string[] = [];
const displayItems: string[] = [];
const normalizedItems: string[] = [];
const canonicalByNormalized = new Map<string, string>();
const displayByNormalized = new Map<string, string>();
const seen = new Set<string>();
const addItem = (path: string, label?: string) => {
const normalized = this.normalizeFolderPath(path);
if (seen.has(normalized)) return;
if (
allowedRoots &&
allowedRoots.length > 0 &&
!this.isPathAllowed(normalized, allowedRoots)
) {
return;
}
seen.add(normalized);
items.push(path);
displayItems.push(label ?? path);
normalizedItems.push(normalized);
canonicalByNormalized.set(normalized, path);
if (label) displayByNormalized.set(normalized, label);
};
for (const item of topItems) addItem(item.path, item.label);
for (const folder of folders) addItem(folder);
return {
items,
displayItems,
normalizedItems,
canonicalByNormalized,
displayByNormalized,
};
}
private renderFolderSuggestion(
item: string,
el: HTMLElement,
existingSet: Set<string>,
displayByNormalized: Map<string, string>,
): void {
el.empty();
el.classList.add("mod-complex");
const normalized = this.normalizeFolderPath(item);
const display = displayByNormalized.get(normalized);
const displayPath = item || "/";
const isExisting = existingSet.has(normalized);
let indicator = "";
if (display === "<current folder>") {
indicator = "Current folder";
} else if (!isExisting) {
indicator = "Create folder";
}
const content = el.createDiv("suggestion-content");
const title = content.createDiv("suggestion-title");
title.createSpan({ text: displayPath });
if (indicator) {
const aux = el.createDiv("suggestion-aux");
aux.createEl("kbd", { cls: "suggestion-hotkey", text: indicator });
}
}
protected async getFormattedFilePath(
folderPath: string,
format: string,
promptHeader: string
): Promise<string> {
const formattedName = await this.formatter.formatFileName(
format,
promptHeader
);
return this.normalizeMarkdownFilePath(folderPath, formattedName);
}
protected getTemplateExtension(templatePath: string): string {
if (CANVAS_FILE_EXTENSION_REGEX.test(templatePath)) {
return ".canvas";
}
return ".md";
}
protected normalizeTemplateFilePath(
folderPath: string,
fileName: string,
templatePath: string
): string {
const safeFolderPath = this.stripLeadingSlash(folderPath);
const actualFolderPath: string = safeFolderPath ? `${safeFolderPath}/` : "";
const extension = this.getTemplateExtension(templatePath);
const formattedFileName: string = this.stripLeadingSlash(fileName)
.replace(MARKDOWN_FILE_EXTENSION_REGEX, "")
.replace(CANVAS_FILE_EXTENSION_REGEX, "");
return `${actualFolderPath}${formattedFileName}${extension}`;
}
protected async incrementFileName(fileName: string) {
const fileExists = await this.app.vault.adapter.exists(fileName);
let newFileName = fileName;
// Determine the extension from the filename and construct a matching regex
const extension = CANVAS_FILE_EXTENSION_REGEX.test(fileName) ? ".canvas" : ".md";
const extPattern = extension.replace(/\./g, "\\.");
const numberWithExtRegex = new RegExp(`(\\d*)${extPattern}$`);
const exec = numberWithExtRegex.exec(fileName);
const numStr = exec?.[1];
if (fileExists && numStr !== undefined) {
if (numStr.length > 0) {
const number = parseInt(numStr, 10);
if (Number.isNaN(number)) {
throw new Error("detected numbers but couldn't get them.");
}
newFileName = newFileName.replace(numberWithExtRegex, `${number + 1}${extension}`);
} else {
// No digits previously; insert 1 before extension
newFileName = newFileName.replace(new RegExp(`${extPattern}$`), `1${extension}`);
}
} else if (fileExists) {
// No match; simply append 1 before the extension
newFileName = newFileName.replace(new RegExp(`${extPattern}$`), `1${extension}`);
}
const newFileExists = await this.app.vault.adapter.exists(newFileName);
if (newFileExists)
newFileName = await this.incrementFileName(newFileName);
return newFileName;
}
protected async createFileWithTemplate(
filePath: string,
templatePath: string
) {
try {
const templateContent: string = await this.getTemplateContent(
templatePath
);
// Extract filename without extension from the full path (supports .md and .canvas)
const fileBasename = basenameWithoutMdOrCanvas(filePath);
this.formatter.setTitle(fileBasename);
const formattedTemplateContent: string =
await this.formatter.formatFileContent(templateContent);
// Get template variables before creating the file
const templateVars = this.formatter.getAndClearTemplatePropertyVars();
log.logMessage(`TemplateEngine.createFileWithTemplate: Collected ${templateVars.size} template property variables for ${filePath}`);
if (templateVars.size > 0) {
log.logMessage(`Variables: ${Array.from(templateVars.keys()).join(', ')}`);
}
const suppressTemplaterOnCreate = filePath
.toLowerCase()
.endsWith(".md");
const createdFile: TFile = await this.createFileWithInput(
filePath,
formattedTemplateContent,
{ suppressTemplaterOnCreate },
);
// Post-process front matter for template property types BEFORE Templater
if (this.shouldPostProcessFrontMatter(createdFile, templateVars)) {
await this.postProcessFrontMatter(createdFile, templateVars);
}
// Process Templater commands for template choices
await overwriteTemplaterOnce(this.app, createdFile);
return createdFile;
} catch (err) {
if (isMacroAbortError(err)) {
throw err;
}
reportError(err, `Could not create file with template at ${filePath}`);
return null;
}
}
protected async formatTemplateForFile(
templatePath: string,
targetFile: TFile,
): Promise<{ content: string; templateVars: Map<string, unknown> }> {
const templateContent: string = await this.getTemplateContent(templatePath);
// Use the target file's basename as the title
this.formatter.setTitle(targetFile.basename);
const formattedTemplateContent: string =
await this.formatter.formatFileContent(templateContent);
const templateVars = this.formatter.getAndClearTemplatePropertyVars();
return {
content: formattedTemplateContent,
templateVars,
};
}
public setLinkToCurrentFileBehavior(behavior: LinkToCurrentFileBehavior) {
this.formatter.setLinkToCurrentFileBehavior(behavior);
}
protected async overwriteFileWithTemplate(
file: TFile,
templatePath: string
) {
try {
const templateContent: string = await this.getTemplateContent(
templatePath
);
// Use the existing file's basename as the title
const fileBasename = file.basename;
this.formatter.setTitle(fileBasename);
const formattedTemplateContent: string =
await this.formatter.formatFileContent(templateContent);
// Get template variables before modifying the file
const templateVars = this.formatter.getAndClearTemplatePropertyVars();
log.logMessage(`TemplateEngine.overwriteFileWithTemplate: Collected ${templateVars.size} template property variables for ${file.path}`);
if (templateVars.size > 0) {
log.logMessage(`Variables: ${Array.from(templateVars.keys()).join(', ')}`);
}
await this.app.vault.modify(file, formattedTemplateContent);
// Post-process front matter for template property types BEFORE Templater
if (this.shouldPostProcessFrontMatter(file, templateVars)) {
await this.postProcessFrontMatter(file, templateVars);
}
// Process Templater commands
await overwriteTemplaterOnce(this.app, file);
return file;
} catch (err) {
if (isMacroAbortError(err)) {
throw err;
}
reportError(err, "Could not overwrite file with template");
return null;
}
}
protected async appendToFileWithTemplate(
file: TFile,
templatePath: string,
section: "top" | "bottom"
) {
try {
const templateContent: string = await this.getTemplateContent(
templatePath
);
// Use the existing file's basename as the title
const fileBasename = file.basename;
this.formatter.setTitle(fileBasename);
let formattedTemplateContent: string =
await this.formatter.formatFileContent(templateContent);
if (file.extension === "md") {
formattedTemplateContent = await templaterParseTemplate(
this.app,
formattedTemplateContent,
file,
);
}
const fileContent: string = await this.app.vault.cachedRead(file);
const newFileContent: string =
section === "top"
? `${formattedTemplateContent}\n${fileContent}`
: `${fileContent}\n${formattedTemplateContent}`;
await this.app.vault.modify(file, newFileContent);
return file;
} catch (err) {
if (isMacroAbortError(err)) {
throw err;
}
reportError(err, "Could not append to file with template");
return null;
}
}
protected async getTemplateContent(templatePath: string): Promise<string> {
let correctTemplatePath: string = this.stripLeadingSlash(templatePath);
if (!MARKDOWN_FILE_EXTENSION_REGEX.test(templatePath) &&
!CANVAS_FILE_EXTENSION_REGEX.test(templatePath))
correctTemplatePath += ".md";
const templateFile =
this.app.vault.getAbstractFileByPath(correctTemplatePath);
if (!(templateFile instanceof TFile))
throw new Error(
`Template file not found at path "${correctTemplatePath}".`
);
return await this.app.vault.cachedRead(templateFile);
}
}