-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathTemplateEngine.ts
More file actions
302 lines (257 loc) · 9.06 KB
/
TemplateEngine.ts
File metadata and controls
302 lines (257 loc) · 9.06 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
import { QuickAddEngine } from "./QuickAddEngine";
import { CompleteFormatter } from "../formatters/completeFormatter";
import type { LinkToCurrentFileBehavior } from "../formatters/formatter";
import type { App } from "obsidian";
import { TFile } from "obsidian";
import type QuickAdd from "../main";
import {
getTemplater,
overwriteTemplaterOnce,
templaterParseTemplate,
} from "../utilityObsidian";
import GenericSuggester from "../gui/GenericSuggester/genericSuggester";
import { MARKDOWN_FILE_EXTENSION_REGEX, CANVAS_FILE_EXTENSION_REGEX } from "../constants";
import { reportError } from "../utils/errorUtils";
import { basenameWithoutMdOrCanvas } from "../utils/pathUtils";
import { MacroAbortError } from "../errors/MacroAbortError";
import { isCancellationError } from "../utils/errorUtils";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import { log } from "../logger/logManager";
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[]): Promise<string> {
let folderPath: string;
if (folders.length > 1) {
try {
folderPath = await GenericSuggester.Suggest(
this.app,
folders,
folders
);
if (!folderPath) throw new Error("No folder selected.");
} catch (error) {
// Always abort on cancelled input
if (isCancellationError(error)) {
throw new MacroAbortError("Input cancelled by user");
}
throw error;
}
} else {
folderPath = folders[0];
}
if (folderPath) await this.createFolder(folderPath);
else folderPath = "";
return folderPath;
}
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 actualFolderPath: string = folderPath ? `${folderPath}/` : "";
const extension = this.getTemplateExtension(templatePath);
const formattedFileName: string = 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;
}
}
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 = 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);
}
}