generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathFile.ts
198 lines (175 loc) · 6.04 KB
/
File.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
import { MarkdownView, MetadataCache, Notice, TFile, Vault, Workspace } from 'obsidian';
import type { ListItemCache } from 'obsidian';
import { getSettings } from './Config/Settings';
import type { Task } from './Task';
let metadataCache: MetadataCache | undefined;
let vault: Vault | undefined;
let workspace: Workspace | undefined;
/** the two lists below must be maintained together. */
const supportedFileExtensions = ['md'];
const supportedViewTypes = [MarkdownView];
export const initializeFile = ({
metadataCache: newMetadataCache,
vault: newVault,
workspace: newWorkspace,
}: {
metadataCache: MetadataCache;
vault: Vault;
workspace: Workspace;
}) => {
metadataCache = newMetadataCache;
vault = newVault;
workspace = newWorkspace;
};
/**
* Replaces the original task with one or more new tasks.
*
* If you pass more than one replacement task, all subsequent tasks in the same
* section must be re-rendered, as their section indexes change. Assuming that
* this is done faster than user interaction in practice.
*
* In addition, this function is meant to be called with reasonable confidence
* that the {@code originalTask} is unmodified and at the exact same section and
* sectionIdx in the source file it was originally found in. It will fail otherwise.
*/
export const replaceTaskWithTasks = async ({
originalTask,
newTasks,
}: {
originalTask: Task;
newTasks: Task | Task[];
}): Promise<void> => {
if (vault === undefined || metadataCache === undefined || workspace === undefined) {
errorAndNotice('Tasks: cannot use File before initializing it.');
return;
}
if (!Array.isArray(newTasks)) {
newTasks = [newTasks];
}
tryRepetitive({
originalTask,
newTasks,
vault,
metadataCache,
workspace,
previousTries: 0,
});
};
function errorAndNotice(message: string) {
console.error(message);
new Notice(message, 10000);
}
function warnAndNotice(message: string) {
console.warn(message);
new Notice(message, 10000);
}
/**
* This is a workaround to re-try when the returned file cache is `undefined`.
* Retrying after a while may return a valid file cache.
* Reported in https://github.com/obsidian-tasks-group/obsidian-tasks/issues/87
*/
const tryRepetitive = async ({
originalTask,
newTasks,
vault,
metadataCache,
workspace,
previousTries,
}: {
originalTask: Task;
newTasks: Task[];
vault: Vault;
metadataCache: MetadataCache;
workspace: Workspace;
previousTries: number;
}): Promise<void> => {
const retry = () => {
if (previousTries > 10) {
errorAndNotice('Tasks: Too many retries. File update not possible ...');
return;
}
const timeout = Math.min(Math.pow(10, previousTries), 100); // 1, 10, 100, 100, 100, ...
setTimeout(() => {
tryRepetitive({
originalTask,
newTasks,
vault,
metadataCache,
workspace,
previousTries: previousTries + 1,
});
}, timeout);
};
const file = vault.getAbstractFileByPath(originalTask.path);
if (!(file instanceof TFile)) {
warnAndNotice(`Tasks: No file found for task ${originalTask.description}. Retrying ...`);
return retry();
}
if (!supportedFileExtensions.includes(file.extension)) {
errorAndNotice(`Tasks: Does not support files with the ${file.extension} file extension.`);
return;
}
const fileCache = metadataCache.getFileCache(file);
if (fileCache == undefined || fileCache === null) {
warnAndNotice(`Tasks: No file cache found for file ${file.path}. Retrying ...`);
return retry();
}
const listItemsCache = fileCache.listItems;
if (listItemsCache === undefined || listItemsCache.length === 0) {
warnAndNotice(`Tasks: No list items found in file cache of ${file.path}. Retrying ...`);
return retry();
}
// before reading the file, save all open views which may contain dirty data not yet saved to filesys.
// TODO: future opt is save only if some dirty bit is set.
const promises: Promise<void>[] = [];
workspace.iterateAllLeaves((leaf) => {
supportedViewTypes.forEach((viewType) => {
if (leaf.view instanceof viewType && leaf.view.file.path === file.path) {
promises.push(leaf.view.save());
}
});
});
await Promise.all(promises);
const fileContent = await vault.read(file); // TODO: replace with vault.process.
const fileLines = fileContent.split('\n');
const { globalFilter } = getSettings();
let listItem: ListItemCache | undefined;
let sectionIndex = 0;
for (const listItemCache of listItemsCache) {
if (listItemCache.position.start.line < originalTask.sectionStart) {
continue;
}
if (listItemCache.task === undefined) {
continue;
}
const line = fileLines[listItemCache.position.start.line];
if (line.includes(globalFilter)) {
if (sectionIndex === originalTask.sectionIndex) {
if (line === originalTask.originalMarkdown) {
listItem = listItemCache;
} else {
errorAndNotice(
`Tasks: Unable to find task in file ${originalTask.path}.
Expected task:
${originalTask.toFileLineString()}
Found task:
${line}`,
);
return;
}
break;
}
sectionIndex++;
}
}
if (listItem === undefined) {
errorAndNotice('Tasks: could not find task to toggle in the file.');
return;
}
const updatedFileLines = [
...fileLines.slice(0, listItem.position.start.line),
...newTasks.map((task: Task) => task.toFileLineString()),
...fileLines.slice(listItem.position.start.line + 1), // Only supports single-line tasks.
];
await vault.modify(file, updatedFileLines.join('\n'));
};