-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathTemplateChoiceEngine.ts
More file actions
279 lines (246 loc) · 7.8 KB
/
TemplateChoiceEngine.ts
File metadata and controls
279 lines (246 loc) · 7.8 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
import type { App } from "obsidian";
import { TFile } from "obsidian";
import invariant from "src/utils/invariant";
import {
fileExistsAppendToBottom,
fileExistsAppendToTop,
fileExistsChoices,
fileExistsDoNothing,
fileExistsIncrement,
fileExistsOverwriteFile,
VALUE_SYNTAX,
} from "../constants";
import GenericSuggester from "../gui/GenericSuggester/genericSuggester";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import { log } from "../logger/logManager";
import type QuickAdd from "../main";
import type ITemplateChoice from "../types/choices/ITemplateChoice";
import { normalizeAppendLinkOptions } from "../types/linkPlacement";
import {
getAllFolderPathsInVault,
insertFileLinkToActiveView,
jumpToNextTemplaterCursorIfPossible,
openExistingFileTab,
openFile,
} from "../utilityObsidian";
import { isCancellationError, reportError } from "../utils/errorUtils";
import { TemplateEngine } from "./TemplateEngine";
import { MacroAbortError } from "../errors/MacroAbortError";
import { handleMacroAbort } from "../utils/macroAbortHandler";
export class TemplateChoiceEngine extends TemplateEngine {
public choice: ITemplateChoice;
private readonly choiceExecutor: IChoiceExecutor;
constructor(
app: App,
plugin: QuickAdd,
choice: ITemplateChoice,
choiceExecutor: IChoiceExecutor,
) {
super(app, plugin, choiceExecutor);
this.choiceExecutor = choiceExecutor;
this.choice = choice;
}
public async run(): Promise<void> {
try {
invariant(this.choice.templatePath, () => {
return `Invalid template path for ${this.choice.name}. ${this.choice.templatePath.length === 0
? "Template path is empty."
: `Template path is not valid: ${this.choice.templatePath}`
}`;
});
const linkOptions = normalizeAppendLinkOptions(this.choice.appendLink);
this.setLinkToCurrentFileBehavior(
linkOptions.enabled && !linkOptions.requireActiveFile
? "optional"
: "required",
);
let folderPath = "";
if (this.choice.folder.enabled) {
folderPath = await this.getFolderPath();
} else {
// Respect Obsidian's "Default location for new notes" setting
const parent = this.app.fileManager.getNewFileParent(
this.app.workspace.getActiveFile()?.path ?? ""
);
folderPath = parent === this.app.vault.getRoot() ? "" : parent.path;
}
const format = this.choice.fileNameFormat.enabled
? this.choice.fileNameFormat.format
: VALUE_SYNTAX;
const formattedName = await this.formatter.formatFileName(
format,
this.choice.name,
);
let filePath = this.normalizeTemplateFilePath(
folderPath,
formattedName,
this.choice.templatePath,
);
if (this.choice.fileExistsMode === fileExistsIncrement)
filePath = await this.incrementFileName(filePath);
let createdFile: TFile | null;
let shouldAutoOpen = false;
if (await this.app.vault.adapter.exists(filePath)) {
const file = this.findExistingFile(filePath);
if (
!(file instanceof TFile) ||
(file.extension !== "md" && file.extension !== "canvas")
) {
log.logError(
`'${filePath}' already exists but could not be resolved as a markdown or canvas file.`,
);
return;
}
let userChoice: (typeof fileExistsChoices)[number] =
this.choice.fileExistsMode;
if (!this.choice.setFileExistsBehavior) {
try {
userChoice = await GenericSuggester.Suggest(
this.app,
[...fileExistsChoices],
[...fileExistsChoices],
);
} catch (error) {
if (isCancellationError(error)) {
throw new MacroAbortError("Input cancelled by user");
}
throw error;
}
}
switch (userChoice) {
case fileExistsAppendToTop:
createdFile = await this.appendToFileWithTemplate(
file,
this.choice.templatePath,
"top",
);
break;
case fileExistsAppendToBottom:
createdFile = await this.appendToFileWithTemplate(
file,
this.choice.templatePath,
"bottom",
);
break;
case fileExistsOverwriteFile:
createdFile = await this.overwriteFileWithTemplate(
file,
this.choice.templatePath,
);
break;
case fileExistsDoNothing:
createdFile = file;
shouldAutoOpen = true; // Auto-open existing file when user chooses "Nothing"
log.logMessage(`Opening existing file: ${file.path}`);
break;
case fileExistsIncrement: {
const incrementFileName = await this.incrementFileName(filePath);
createdFile = await this.createFileWithTemplate(
incrementFileName,
this.choice.templatePath,
);
break;
}
default:
log.logWarning("File not written to.");
return;
}
} else {
createdFile = await this.createFileWithTemplate(
filePath,
this.choice.templatePath,
);
if (!createdFile) {
log.logWarning(`Could not create file '${filePath}'.`);
return;
}
}
if (linkOptions.enabled && createdFile) {
insertFileLinkToActiveView(this.app, createdFile, linkOptions);
}
if ((this.choice.openFile || shouldAutoOpen) && createdFile) {
const focus = this.choice.fileOpening.focus ?? true;
const openExistingTab = openExistingFileTab(
this.app,
createdFile,
focus,
);
if (!openExistingTab) {
await openFile(this.app, createdFile, this.choice.fileOpening);
}
await jumpToNextTemplaterCursorIfPossible(this.app, createdFile);
}
} catch (err) {
if (
handleMacroAbort(err, {
logPrefix: "Template execution aborted",
noticePrefix: "Template execution aborted",
defaultReason: "Template execution aborted",
})
) {
this.choiceExecutor.signalAbort?.(err as MacroAbortError);
return;
}
reportError(err, `Error running template choice "${this.choice.name}"`);
}
}
private findExistingFile(filePath: string): TFile | null {
const direct = this.app.vault.getAbstractFileByPath(filePath);
if (direct instanceof TFile) return direct;
if (direct) return null;
// On case-insensitive filesystems, adapter.exists can return true even when
// Obsidian's case-sensitive path index can't resolve the file.
const lowerPath = filePath.toLowerCase();
const matches = this.app.vault
.getFiles()
.filter((file) => file.path.toLowerCase() === lowerPath);
if (matches.length === 1) return matches[0];
if (matches.length > 1) {
log.logError(
`Multiple files match '${filePath}' when ignoring case.`,
);
}
return null;
}
private async formatFolderPaths(folders: string[]) {
const folderPaths = await Promise.all(
folders.map(async (folder) => {
return await this.formatter.formatFolderPath(folder);
}),
);
return folderPaths;
}
private async getFolderPath() {
const folders: string[] = await this.formatFolderPaths([
...this.choice.folder.folders,
]);
if (
this.choice.folder?.chooseFromSubfolders &&
!(
this.choice.folder?.chooseWhenCreatingNote ||
this.choice.folder?.createInSameFolderAsActiveFile
)
) {
const allFoldersInVault: string[] = getAllFolderPathsInVault(this.app);
const subfolders = allFoldersInVault.filter((folder) => {
return folders.some((f) => folder.startsWith(f));
});
return await this.getOrCreateFolder(subfolders);
}
if (this.choice.folder?.chooseWhenCreatingNote) {
const allFoldersInVault: string[] = getAllFolderPathsInVault(this.app);
return await this.getOrCreateFolder(allFoldersInVault);
}
if (this.choice.folder?.createInSameFolderAsActiveFile) {
const activeFile = this.app.workspace.getActiveFile();
if (!activeFile || !activeFile.parent) {
log.logWarning(
"No active file or active file has no parent. Cannot create file in same folder as active file. Creating in root folder.",
);
return "";
}
return this.getOrCreateFolder([activeFile.parent.path]);
}
return await this.getOrCreateFolder(folders);
}
}