-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
362 lines (340 loc) · 11.2 KB
/
main.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
import { App, Editor, MarkdownView, Notice, parseYaml, Plugin, requestUrl, arrayBufferToBase64, base64ToArrayBuffer, MarkdownRenderer, FuzzySuggestModal } from "obsidian";
// Util functions
async function getFiles(
app: App,
path: string,
ignoreList: string[],
filter: RegExp[]
) {
const w = await app.vault.adapter.list(path);
let files = [
...w.files
.filter((e) => !ignoreList.some((ee) => e.endsWith(ee)))
.filter((e) => !filter || filter.some((ee) => e.match(ee))),
];
L1: for (const v of w.folders) {
for (const ignore of ignoreList) {
if (v.endsWith(ignore)) {
continue L1;
}
}
// files = files.concat([v]);
files = files.concat(await getFiles(app, v, ignoreList, filter));
}
return files;
}
async function getDirectories(app: App, path: string, ignoreList: string[]) {
const w = await app.vault.adapter.list(path);
let dirs: string[] = [];
L1: for (const v of w.folders) {
for (const ignore of ignoreList) {
if (v.endsWith(ignore)) {
continue L1;
}
}
dirs = dirs.concat([v]);
dirs = dirs.concat(await getDirectories(app, v, ignoreList));
}
return dirs;
}
function isPlainText(filename: string): boolean {
if (filename.endsWith(".md")) return true;
if (filename.endsWith(".txt")) return true;
if (filename.endsWith(".svg")) return true;
if (filename.endsWith(".html")) return true;
if (filename.endsWith(".csv")) return true;
if (filename.endsWith(".css")) return true;
if (filename.endsWith(".js")) return true;
if (filename.endsWith(".json")) return true;
if (filename.endsWith(".xml")) return true;
if (filename.endsWith(".ts")) return true;
if (filename.endsWith(".canvas")) return true;
return false;
}
async function ensureDirectory(app: App, fullpath: string) {
const pathElements = fullpath.split("/");
pathElements.pop();
let c = "";
for (const v of pathElements) {
c += v;
try {
await app.vault.createFolder(c);
} catch (ex) {
// basically skip exceptions.
if (ex.message && ex.message == "Folder already exists.") {
// especialy this message is.
} else {
new Notice("Folder Create Error");
console.log(ex);
}
}
c += "/";
}
}
export default class ScrewDriverPlugin extends Plugin {
async onload() {
await this.loadSettings();
this.addCommand({
id: "screwdriver-add-target-dir",
name: "Add target directory",
editorCallback: async (editor: Editor, view: MarkdownView) => {
const list = await getDirectories(
this.app,
this.app.vault.configDir,
["node_modules", ".git"]
);
const selected = await askSelectString(this.app, "Select target directory", list);
if (selected) {
let filters = [] as string[];
if (selected.indexOf("plugins") !== -1) {
if (await askSelectString(this.app, "Do you want to include plugin's data?", ["yes", "no"]) == "yes") {
filters = ["main\\.js$", "manifest\\.json$", "styles\\.css$", "data\\.json$"];
} else {
filters = ["main\\.js$", "manifest\\.json$", "styles\\.css$"];
}
} else if (selected.indexOf("themes") !== -1) {
filters = ["manifest\\.json$", "theme\\.css$"];
} else if (selected.indexOf("snippets") !== -1) {
filters = (await getFiles(this.app, selected, [], [/\.css$/])).map(e => e.substring(selected.length).replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "$");
}
this.app.fileManager.processFrontMatter(view.file, async fm => {
fm.targets = [...new Set([...fm.targets ?? [], selected])];
if (filters.length > 0) {
fm.filters = [...new Set([...(fm.filters ?? []), ...filters])]
}
})
}
}
});
this.addCommand({
id: "screwdriver-create-template-dump",
name: "Create or add local file exporting template",
editorCallback: async (editor: Editor, view: MarkdownView) => {
this.app.fileManager.processFrontMatter(view.file, fn => {
fn.targets = fn.targets ?? [];
fn.ignores = fn.ignores ?? ["/node_modules", "/.git"];
fn.filters = fn.filters ?? [];
fn.comment = fn.comment ?? "'Add target directory' to add targets";
fn.tags = fn.tags ?? [];
});
},
});
this.addCommand({
id: "screwdriver-create-template-fetch",
name: "Create or add remote file fetching template",
editorCallback: async (editor: Editor, view: MarkdownView) => {
this.app.fileManager.processFrontMatter(view.file, fn => {
fn.urls = fn.urls ?? [];
fn.authorization = fn.authorization ?? "";
fn.tags = fn.tags ?? [];
fn.header_json = fn.header_json ?? "";
});
},
})
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: "screwdriver-dump",
name: "Export specified files and store into the active file",
editorCallback: async (editor: Editor, view: MarkdownView) => {
const data = view.data;
const bodyStartIndex = data.indexOf("\n---");
if (!data.startsWith("---") || bodyStartIndex === -1) {
new Notice("Frontmatter was not found.");
}
//
const yaml = data.substring(3, bodyStartIndex);
const yamlData = parseYaml(yaml);
let newData = "---" + yaml + "\n---\n\n";
const target = yamlData.target ?? "";
let targets = (yamlData.targets ?? []) as string[];
if (target) targets = [...targets, target];
targets = targets.map(e => e.trim()).filter(e => e != "");
const ignoresSrc = yamlData.ignores;
const ignores: string[] = Array.isArray(ignoresSrc)
? ignoresSrc
: (ignoresSrc + "").split(",");
const filterSrc = yamlData.filters;
const filters = !filterSrc
? null
: filterSrc.map((e: string) => new RegExp(e));
const urls = (yamlData.urls ?? "");
if (targets.length == 0 && urls == "") {
new Notice("Target folders or urls are not specified.");
return;
}
for (const url of urls) {
try {
let fileDat = "";
let bin = false;
const w = await requestUrl(url);
const filename = new URL(url).pathname.split("/").last();
const dt = w.arrayBuffer;
try {
const text = new TextDecoder("utf-8", { fatal: true }).decode(dt);
fileDat = text;
fileDat = fileDat.replace(/\\/g, "\\\\");
fileDat = fileDat.replace(/`/g, "\\`");
} catch (ex2) {
fileDat = await arrayBufferToBase64(dt);
bin = true;
}
newData += "\n";
newData += `# ${url} \n`;
newData += `- Fetched :${new Date().toLocaleString()} \n`;
newData += "\n```screwdriver:" + filename + (bin ? ":bin" : "") + "\n";
newData += fileDat + "";
newData += "\n```";
} catch (ex) {
new Notice(`Error on fetching ${url}\n${ex}`);
}
}
for (const target of targets) {
const files = await getFiles(
this.app,
target,
ignores,
filters
);
for (const file of files) {
let fileDat = "";
let bin = false;
const dt = await this.app.vault.adapter.readBinary(file);
const stat = await this.app.vault.adapter.stat(file);
try {
const text = new TextDecoder("utf-8", { fatal: true }).decode(dt);
fileDat = text;
fileDat = fileDat.replace(/\\/g, "\\\\");
fileDat = fileDat.replace(/`/g, "\\`");
} catch (ex2) {
fileDat = await arrayBufferToBase64(dt);
bin = true;
}
newData += "\n";
newData += `# ${file} \n`;
newData += `- Created :${new Date(
stat.ctime
).toLocaleString()} \n`;
newData += `- Modified:${new Date(
stat.mtime
).toLocaleString()} \n`;
newData += "\n```screwdriver:" + file + ":" + (bin ? "bin" : "plain") + "\n";
newData += fileDat + "";
newData += "\n```";
}
}
editor.setValue(newData);
},
});
this.registerMarkdownCodeBlockProcessor("screwdriver", (source, el, ctx) => {
const sourcePath = ctx.sourcePath;
const si = ctx.getSectionInfo(el);
const fxx = si.text.split("\n")[si.lineStart];
const filename = `${fxx}:::`.split(":")[1];
const rSource = `${"```\n"}${source}${"\n```"}`;
const renderSource = `> [!screwdriver]- ${filename}\n${rSource.replace(/^/mg, "> ")}`;
const fx = el.createDiv({ text: "", cls: ["screwdriver-display"] });
MarkdownRenderer.renderMarkdown(renderSource, fx, sourcePath, this)
el.replaceWith(fx);
});
this.addCommand({
id: "screwdriver-restore",
name: "Restore exported files from the active file",
editorCallback: async (editor: Editor, view: MarkdownView) => {
const data = view.data;
if (data.startsWith("---")) {
const bodyStartIndex = data.indexOf("\n---");
if (bodyStartIndex !== -1) {
const preBlocks = data
.substring(bodyStartIndex)
.matchAll(/^```(?:screwdriver:|)([\s\S]*?)\n([\s\S]*?)^```/gm);
for (const preBlock of preBlocks) {
const [, filenameSrc, data] = preBlock;
const [filename, dataType] = `${filenameSrc}:`.split(":");
let saveData = data;
try {
if ((isPlainText(filename) && dataType != "bin") || dataType == "plain") {
saveData = saveData.replace(/\\`/g, "`");
saveData = saveData.replace(/\\\\/g, "\\");
saveData = saveData.substring(
0,
saveData.lastIndexOf("\n")
);
await ensureDirectory(this.app, filename);
await this.app.vault.adapter.write(
filename,
saveData
);
} else {
saveData = saveData.substring(
0,
saveData.lastIndexOf("\n")
);
const saveDataArrayBuffer =
base64ToArrayBuffer(saveData);
await ensureDirectory(this.app, filename);
await this.app.vault.adapter.writeBinary(
filename,
saveDataArrayBuffer
);
}
new Notice(
`File:${filename} has been wrote to your device.`
);
console.log(`File:${filename} has been wrote to your device.`)
} catch (ex) {
new Notice(`Failed to write ${filename}`);
console.error(`Failed to write ${filename}`)
console.log(ex);
}
}
return;
}
}
new Notice("Frontmatter was not found.");
console.error("Frontmatter was not found")
},
});
}
onunload() { }
async loadSettings() { }
async saveSettings() { }
}
export class PopoverSelectString extends FuzzySuggestModal<string> {
app: App;
callback: (e: string) => void = () => { };
getItemsFun: () => string[] = () => {
return ["yes", "no"];
}
constructor(app: App, note: string, placeholder: string | null, getItemsFun: () => string[], callback: (e: string) => void) {
super(app);
this.app = app;
this.setPlaceholder((placeholder ?? "y/n) ") + note);
if (getItemsFun) this.getItemsFun = getItemsFun;
this.callback = callback;
}
getItems(): string[] {
return this.getItemsFun();
}
getItemText(item: string): string {
return item;
}
onChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {
// debugger;
this.callback(item);
this.callback = null;
}
onClose(): void {
setTimeout(() => {
if (this.callback != null) {
this.callback("");
}
}, 100);
}
}
export const askSelectString = (app: App, message: string, items: string[]): Promise<string> => {
const getItemsFun = () => items;
return new Promise((res) => {
const popover = new PopoverSelectString(app, message, "", getItemsFun, (result) => res(result));
popover.open();
});
};