generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
89 lines (73 loc) · 2.67 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
import { Notice, Plugin, TFile } from 'obsidian';
import * as path from 'path';
import { matches, transform } from 'regex/Regex';
import { PluginSettings, SettingsTab } from './settings/SettingsTab';
const DEFAULT_SETTINGS: PluginSettings = {
tableEntries: []
}
export default class NewFileRenamer extends Plugin {
settings: PluginSettings;
async onload() {
await this.loadSettings();
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingsTab(this.app, this));
this.registerEvent(this.app.vault.on('rename', async (file, oldPath) => {
// Find the first xformation entry that matches the file path
const xformEntry = this.settings.tableEntries.find(entry =>
matches(file.name, new RegExp(entry.fileNameMatcher))
);
if (xformEntry) {
// Rename the file using the newFileReplacePattern
const newFileName =
transform(file.name, new RegExp(xformEntry.fileNameMatcher), xformEntry.newFileReplacePattern);
const newFilePath = file.parent?.path + path.sep + newFileName;
console.log(`File renamer - renaming file: ${file.path} to ${newFilePath}`);
const previousContent =
file instanceof TFile ? await this.app.vault.cachedRead(file) : "";
// create a new file and remove the old one, so that the rename event isn't triggered again
const newFile = await this.app.vault.create(newFilePath, previousContent);
// show the file in the current editor
if (newFile) {
await this.app.workspace.getLeaf().openFile(newFile);
} else {
console.log("[ERROR] File renamer - new file not found: " + newFilePath);
}
// delete the old file
this.app.vault.delete(file, true);
// Apply the template if there is one
if(xformEntry.template) {
const template = xformEntry.template;
if(previousContent === "") {
const tp = await this.getTemplater();
const templateFile = this.app.vault.getFileByPath(template);
tp.write_template_to_file(templateFile, newFile);
}
else {
new Notice(`${newFile.path} already has content. Not overwriting it.`);
}
}
}
else {
console.log("No pattern match found. Regular rename proceeding");
}
}));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
async getTemplater(): Promise<any> {
// try to get the Templater folder first
const plugins = (this.app as any).plugins;
const tp = plugins.getPlugin("templater-obsidian").templater;
// if templater is installed
if(tp) {
return tp;
}
return undefined;
}
}