Merge pull request #10 from IdanLib/fix-file-move-bug-3

Fix file move bug 3
This commit is contained in:
Idan Liberman 2024-10-17 22:35:26 +03:00 committed by GitHub
commit 97f8d32aa8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 470 additions and 73 deletions

View file

@ -1,6 +1,6 @@
import RedirectPlugin from "../main";
import { App, PluginSettingTab, Setting } from "obsidian";
import { App, Notice, PluginSettingTab, Setting } from "obsidian";
export default class RedirectSettingsTab extends PluginSettingTab {
plugin: RedirectPlugin;
@ -22,6 +22,13 @@ export default class RedirectSettingsTab extends PluginSettingTab {
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.openInNewTab);
toggle.onChange((value) => {
// this.showSwitchToNewTabSetting = value;
// this.plugin.changeSettings(
// this.showSwitchToNewTabSetting,
// false
// );
// console.log("this.plugin.settings: ", this.plugin.settings);
if (value) {
this.showSwitchToNewTabSetting = true;
this.plugin.changeSettings(true, false);
@ -29,7 +36,7 @@ export default class RedirectSettingsTab extends PluginSettingTab {
this.showSwitchToNewTabSetting = false;
this.plugin.changeSettings(false, false);
}
this.plugin.saveSettings();
// this.plugin.saveSettings();
this.display();
});
});
@ -43,12 +50,21 @@ export default class RedirectSettingsTab extends PluginSettingTab {
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.switchToNewTab);
toggle.onChange((value) => {
// this.plugin.changeSettings(
// this.plugin.settings.openInNewTab,
// value
// );
// console.log(
// "this.plugin.settings: ",
// this.plugin.settings
// );
if (value) {
this.plugin.changeSettings(true, true);
} else {
this.plugin.changeSettings(true, false);
}
this.plugin.saveSettings();
// this.plugin.saveSettings();
});
});
@ -64,9 +80,26 @@ export default class RedirectSettingsTab extends PluginSettingTab {
const redirectsFolder =
this.app.vault.getFolderByPath("_redirects");
if (!redirectsFolder) {
new Notice(
"The _redirects folder cannot be found.",
2000
);
return;
}
this.app.vault.delete(redirectsFolder, true);
try {
this.app.vault.delete(redirectsFolder, true);
new Notice(
"_redirects folder deleted successfully.",
2000
);
} catch (error) {
new Notice(
"Could not delete the _redirects folder.",
2000
);
console.error(error);
}
});
});
}

281
main.ts
View file

@ -1,10 +1,11 @@
import {
getLinkpath,
MarkdownView,
Plugin,
Notice,
TFolder,
TFile,
WorkspaceLeaf,
OpenViewState,
} from "obsidian";
import RedirectSettingsTab from "components/Settings";
@ -18,13 +19,204 @@ const DEFAULT_SETTINGS: RedirectSettings = {
switchToNewTab: false,
};
// class Leaf extends WorkspaceLeaf {
// async openFile(file: TFile, openState?: OpenViewState): Promise<void> {
// return;
// }
// }
export default class RedirectPlugin extends Plugin {
settings: RedirectSettings;
redirectsFolder: TFolder | null = null;
changeSettings(newTab: boolean, switchToTab: boolean): void {
async changeSettings(newTab: boolean, switchToTab: boolean): Promise<void> {
this.settings.openInNewTab = newTab;
this.settings.switchToNewTab = switchToTab;
await this.saveSettings();
}
private async createRedirectsFolder() {
const currentRedirectsFolder =
this.app.vault.getAbstractFileByPath("/_redirects");
if (!currentRedirectsFolder) {
try {
this.redirectsFolder = await this.app.vault.createFolder(
"/_redirects"
);
} catch (error) {
new Notice("Failed to create the _redirects folder.", 3000);
console.warn(error);
}
} else {
// this.redirectsFolder = currentRedirectsFolder as TFolder;
// new Notice("_redirects folder found.", 2000);
}
}
private async redirect() {
const currentFile = this.app.workspace.getActiveFile();
const currentFileContent = await this.getCurrentFileContent(
currentFile
);
if (!currentFileContent) {
console.error(
"Failed to load file content or no content available."
);
return;
}
const targetNoteFile = this.getTargetFile(currentFileContent);
// console.log("targetNoteFile: ", targetNoteFile);
if (!targetNoteFile) {
// console.info("No target note file found.");
return;
}
// console.log("this.settings: ", this.settings);
const updatedRedirectingNote =
await this.moveRedirectNoteToRedirectsFolder(currentFile);
console.log(
"updatedRedirectingNote returned from the move function: ",
updatedRedirectingNote
);
if (updatedRedirectingNote) {
// MOVE TO MOVE FILE FUNCTION, THAT'S LOGICALLY PART OF THE MOVING MECHANISM
await this.app.workspace.openLinkText(
updatedRedirectingNote.name,
updatedRedirectingNote.path
);
}
// await this.app.workspace.openLinkText(
// targetNoteFile.name,
// targetNoteFile.path,
// this.settings.openInNewTab,
// { active: this.settings.switchToNewTab }
// );
}
private async getCurrentFileContent(
currentFile: TFile | null
): Promise<string | null> {
if (!currentFile) {
console.error("No active file found!");
return null;
}
try {
return await this.app.vault.read(currentFile);
} catch (error) {
new Notice(`Cannot read ${currentFile}.`);
console.error(
console.error(`Failed to read ${currentFile} content: `, error)
);
return null;
}
}
private getTargetFile(currentFileContent: string): TFile | null {
const linkTextRegex = /::>\[\[(.*[\w\s]*)\]\]/i;
const targetNoteName = currentFileContent.match(linkTextRegex)?.at(1);
if (!targetNoteName) {
console.info("No redirect syntax found.");
return null;
}
const targetNoteFile = this.app.metadataCache.getFirstLinkpathDest(
getLinkpath(targetNoteName),
""
);
if (!targetNoteFile) {
console.error(
`No target note file found for target: ${targetNoteName}`
);
return null;
}
return targetNoteFile;
}
private async moveRedirectNoteToRedirectsFolder(
redirectingNote: TFile | null
): Promise<TFile | void> {
if (!redirectingNote) {
return;
}
if (!this.redirectsFolder) {
await this.createRedirectsFolder();
}
try {
await this.app.vault.copy(
redirectingNote,
`/_redirects/${redirectingNote.name}`
);
} catch (error) {
// if (error.message.includes("Folder already exists.")) {
// new Notice(
// `File "${redirectingNote.name}" already exists in the _redirects folder.`,
// 2000
// );
// } else {
new Notice(
`Failed to move ${redirectingNote.name} to the _redirects folder.`,
2000
);
// }
console.warn(error);
// return;
}
console.log("redirectingNote.path: ", redirectingNote.path);
if (redirectingNote.path === `_redirects/${redirectingNote.name}`) {
new Notice(
`${redirectingNote.name} is in the _redirects folder.`,
2000
);
return;
}
console.log("redirectingNote.path: ", redirectingNote.path);
const updatedRedirectingNote = await this.deleteNote(redirectingNote);
console.log("updatedRedirectingNote: ", updatedRedirectingNote);
return updatedRedirectingNote;
}
private async deleteNote(orgRedirectingNote: TFile) {
let updatedRedirectingNote = orgRedirectingNote;
if (this.settings.openInNewTab) {
updatedRedirectingNote = Object.create(orgRedirectingNote);
console.log(
"orgRedirectingNote after copying: ",
orgRedirectingNote
);
updatedRedirectingNote.path = `_redirects/${orgRedirectingNote.path}`;
console.log("updatedRedirectingNote: ", updatedRedirectingNote);
}
try {
await this.app.vault.delete(orgRedirectingNote);
} catch (error) {
new Notice(
"Failed to delete directing note from original location. Please delete manually."
);
console.error(error);
}
console.log("deleted the original redirecting note");
return updatedRedirectingNote; // return to caller to open re-open directing tab in tab
}
async onload() {
@ -33,85 +225,36 @@ export default class RedirectPlugin extends Plugin {
this.addSettingTab(new RedirectSettingsTab(this.app, this));
this.app.workspace.onLayoutReady(async () => {
try {
this.redirectsFolder = await this.app.vault.createFolder(
"/_redirects"
);
} catch (error) {
new Notice("The `_redirects` folder exists.", 3000);
console.error(error);
}
});
this.app.workspace.onLayoutReady(() => {
await this.createRedirectsFolder();
this.redirect();
});
this.app.workspace.on("active-leaf-change", (leaf) => {
this.app.workspace.on("file-open", (leaf) => {
this.redirect();
});
}
redirect() {
const currentMdView =
this.app.workspace.getActiveViewOfType(MarkdownView);
const linkTextRegex = /::>\[\[(.*[\w\s]*)\]\]/i;
const targetNoteName = currentMdView
?.getViewData()
.match(linkTextRegex)
?.at(1);
if (!targetNoteName) {
return;
}
const targetNotePath = this.app.metadataCache.getFirstLinkpathDest(
getLinkpath(targetNoteName),
""
);
this.app.workspace.openLinkText(
targetNoteName,
targetNotePath?.path as string,
this.settings.openInNewTab,
{ active: this.settings.switchToNewTab }
);
this.moveRedirectNoteToRedirectsFolder();
onunload() {
this.app.workspace.off("file-open", this.redirect);
}
async moveRedirectNoteToRedirectsFolder() {
const redirectingNote = this.app.workspace.getActiveFile() as TFile;
try {
await this.app.vault.copy(
redirectingNote,
`/_redirects/${redirectingNote.name}`
);
} catch (error) {
new Notice(
`${redirectingNote.name} is in the _redirects folder.`,
2000
);
}
if (redirectingNote.path === `_redirects/${redirectingNote.name}`) {
return;
}
await this.app.vault.delete(redirectingNote);
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
try {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
} catch (error) {
console.error("Failed to load settings: ", error);
}
}
async saveSettings() {
await this.saveData(this.settings);
try {
await this.saveData(this.settings);
} catch (error) {
console.error("Failed to save settings: ", error);
}
}
}

221
main_backup.ts Normal file
View file

@ -0,0 +1,221 @@
import {
getLinkpath,
Plugin,
Notice,
TFolder,
TFile,
FileView,
TextFileView,
} from "obsidian";
import RedirectSettingsTab from "components/Settings";
interface RedirectSettings {
openInNewTab: boolean;
switchToNewTab: boolean;
}
const DEFAULT_SETTINGS: RedirectSettings = {
openInNewTab: false,
switchToNewTab: false,
};
export default class RedirectPlugin extends Plugin {
settings: RedirectSettings;
redirectsFolder: TFolder | null = null;
changeSettings(newTab: boolean, switchToTab: boolean): void {
this.settings.openInNewTab = newTab;
this.settings.switchToNewTab = switchToTab;
}
async createRedirectsFolder() {
try {
this.redirectsFolder = await this.app.vault.createFolder(
"/_redirects"
);
} catch (error) {
new Notice("The _redirects folder exists.", 3000);
console.info(error);
}
}
async onload() {
await this.loadSettings();
this.addSettingTab(new RedirectSettingsTab(this.app, this));
this.app.workspace.onLayoutReady(async () => {
await this.createRedirectsFolder();
});
this.app.workspace.onLayoutReady(() => {
this.redirect();
});
this.app.workspace.on("file-open", (leaf) => {
this.redirect();
});
}
// redirect() {
// console.log("redirect called");
// const currentMdView =
// this.app.workspace.getActiveViewOfType(MarkdownView);
// console.log("in redirect function, currentMdView: ", currentMdView);
// const redirectingNote = currentMdView?.file as TFile | null;
// console.log("in redirect function, redirectingNote: ", redirectingNote);
// // setTimeout(() => {
// const redirectingNoteContent = currentMdView?.getViewData();
// console.log("redirectingNoteContent: ", redirectingNoteContent);
// // }, 100); // Adjust the delay as necessary (100ms or more)
// const linkTextRegex = /::>\[\[(.*[\w\s]*)\]\]/i;
// const targetNoteName = currentMdView
// ?.getViewData()
// .match(linkTextRegex)
// ?.at(1);
// console.log("targetNoteName: ", targetNoteName);
// if (!targetNoteName) {
// return;
// }
// const targetNoteFile = this.app.metadataCache.getFirstLinkpathDest(
// getLinkpath(targetNoteName),
// ""
// );
// console.log("targetNoteFile: ", targetNoteFile);
// this.app.workspace.openLinkText(
// targetNoteName,
// targetNoteFile?.path as string,
// this.settings.openInNewTab,
// { active: this.settings.switchToNewTab }
// );
// // this.moveRedirectNoteToRedirectsFolder(redirectingNote);
// }
async redirect() {
console.log("async redirect called");
const currentFile = this.app.workspace.getActiveFile();
const currentFileContent = await this.getCurrentFileContent(
currentFile
);
console.log(
"in async redirect function, currentFileContent: ",
currentFileContent
);
if (!currentFileContent) {
console.error(
"Failed to load file content or no content available."
);
return; // Safely exit if file content is unavailable
}
const targetNoteFile = this.getTargetFilePath(currentFileContent);
console.log("targetNoteFile: ", targetNoteFile);
// TODO if not target note exists, create it
if (!targetNoteFile) {
console.error("No target note file found.");
return; // Safely exit if target file is not found
}
await this.app.workspace.openLinkText(
targetNoteFile.basename,
targetNoteFile.path,
this.settings.openInNewTab,
{ active: this.settings.switchToNewTab }
);
this.moveRedirectNoteToRedirectsFolder(currentFile);
}
getTargetFilePath(currentFileContent: string | null) {
const linkTextRegex = /::>\[\[(.*[\w\s]*)\]\]/i;
const targetNoteName = currentFileContent?.match(linkTextRegex)?.at(1);
console.log("targetNoteName: ", targetNoteName);
if (!targetNoteName) {
return null;
}
return this.app.metadataCache.getFirstLinkpathDest(
getLinkpath(targetNoteName),
""
);
}
getCurrentFileContent(currentFile: TFile | null) {
// const currentFile = this.app.workspace.getActiveFile();
if (!currentFile) {
console.error("No active file found!");
return null;
}
return this.app.vault.read(currentFile);
}
async moveRedirectNoteToRedirectsFolder(redirectingNote: TFile | null) {
// const redirectingNote = this.app.workspace.getActiveFile() as TFile;
if (!redirectingNote) {
return;
}
console.log(
"in moveRedirectNoteToRedirectsFolder, redirectingNote: ",
redirectingNote
);
await this.createRedirectsFolder();
try {
await this.app.vault.copy(
redirectingNote,
`/_redirects/${redirectingNote.name}`
);
} catch (error) {
console.error(error);
new Notice(
`${redirectingNote.name} cannot be moved to the _redirects folder.`,
2000
);
return;
}
if (redirectingNote.path === `_redirects/${redirectingNote.name}`) {
new Notice(
`${redirectingNote.name} is in the _redirects folder.`,
2000
);
return;
}
await this.app.vault.delete(redirectingNote);
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
}