diff --git a/bun.lockb b/bun.lockb index f7941b3a..65bd4b1b 100644 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index 812219e0..41309068 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,8 @@ }, "dependencies": { "dedent": "^1.5.3", - "ts-deepmerge": "^6.2.1" + "ts-deepmerge": "^6.2.1", + "tslog": "^4.9.3" }, "peerDependencies": { "@types/electron": "npm:@ophidian/electron-types@^24.3.1" diff --git a/src/GitHub/branch.ts b/src/GitHub/branch.ts index 934a6016..1d01275b 100644 --- a/src/GitHub/branch.ts +++ b/src/GitHub/branch.ts @@ -11,6 +11,7 @@ export class GithubBranch extends FilesManagement { constructor(octokit: Octokit, plugin: Enveloppe) { super(octokit, plugin); this.console = plugin.console; + } /** @@ -45,6 +46,7 @@ export class GithubBranch extends FilesManagement { throw new Error( `No main branch found for ${prop.repo}, please check the branch name in the settings` ); + } try { const shaMainBranch = mainBranch!.commit.sha; @@ -54,8 +56,7 @@ export class GithubBranch extends FilesManagement { ref: `refs/heads/${this.branchName}`, sha: shaMainBranch, }); - this.console.notif( - {}, + this.console.info( i18next.t("publish.branch.success", { branchStatus: branch.status, repo: prop }) ); return branch.status === 201; @@ -72,8 +73,7 @@ export class GithubBranch extends FilesManagement { const mainBranch = allBranch.data.find( (branch: { name: string }) => branch.name === this.branchName ); - this.console.notif( - {}, + this.console.info( i18next.t("publish.branch.alreadyExists", { branchName: this.branchName, repo: prop, @@ -81,7 +81,7 @@ export class GithubBranch extends FilesManagement { ); return !!mainBranch; } catch (e) { - this.console.notif({ e: true }, e); + this.console.error(e); return false; } } @@ -106,7 +106,7 @@ export class GithubBranch extends FilesManagement { }); return pr.data.number; } catch (e) { - this.console.logs({ e: true }, e); + this.console.trace(e); //trying to get the last open PR number try { const pr = await this.octokit.request("GET /repos/{owner}/{repo}/pulls", { @@ -117,8 +117,7 @@ export class GithubBranch extends FilesManagement { return pr.data[0]?.number || 0; } catch (e) { // there is no open PR and impossible to create a new one - this.console.notif( - { e: true }, + this.console.info( i18next.t("publish.branch.error", { error: e, repo: prop }) ); return 0; @@ -144,7 +143,7 @@ export class GithubBranch extends FilesManagement { ); return branch.status === 200; } catch (e) { - this.console.logs({ e: true }, e); + this.console.trace(e); return false; } } @@ -177,7 +176,7 @@ export class GithubBranch extends FilesManagement { ); return branch.status === 200; } catch (e) { - this.console.notif({ e: true }, e); + this.console.warn(e); new Notice(i18next.t("error.mergeconflic")); return false; } @@ -222,7 +221,7 @@ export class GithubBranch extends FilesManagement { } return true; } catch (e) { - this.console.logs({ e: true }, e); + this.console.warn(e); new Notice(i18next.t("error.errorConfig", { repo: prop })); return false; } @@ -241,6 +240,7 @@ export class GithubBranch extends FilesManagement { async checkRepository(prop: Properties | Properties[], silent = true): Promise { prop = Array.isArray(prop) ? prop : [prop]; for (const repo of prop) { + this.console.logger.silly(repo); try { const repoExist = await this.octokit .request("GET /repos/{owner}/{repo}", { @@ -259,8 +259,7 @@ export class GithubBranch extends FilesManagement { }); //@ts-ignore if (repoExist.status === 200) { - this.console.notif( - {}, + this.console.info( i18next.t("commands.checkValidity.repoExistsTestBranch", { repo }) ); @@ -272,6 +271,7 @@ export class GithubBranch extends FilesManagement { }) .catch((e) => { //check the error code + this.console.logger.warn(e); if (e.status === 404) { new Notice( i18next.t("commands.checkValidity.inBranch.error404", { repo }) @@ -282,13 +282,14 @@ export class GithubBranch extends FilesManagement { ); } }); + this.console.logger.info(branchExist); //@ts-ignore if (branchExist.status === 200 && !silent) { new Notice(i18next.t("commands.checkValidity.success", { repo })); } } } catch (e) { - this.console.logs({ e: true }, e); + this.console.logger.fatal(e); new Notice(i18next.t("commands.checkValidity.error", { repo })); break; } diff --git a/src/GitHub/delete.ts b/src/GitHub/delete.ts index e841dbbe..6dfe944a 100644 --- a/src/GitHub/delete.ts +++ b/src/GitHub/delete.ts @@ -88,7 +88,7 @@ async function deleteFromGithubOneRepo( return { success: false, deleted: [], undeleted: [] }; } if (filesInRepo.length === 0) { - pconsole.logs({}, `No file to delete in ${repo.owner}/${repo.repo}`); + pconsole.trace(`No file to delete in ${repo.owner}/${repo.repo}`); return { success: false, deleted: [], undeleted: [] }; } const allSharedFiles = filesManagement.getAllFileWithPath( @@ -126,11 +126,10 @@ async function deleteFromGithubOneRepo( : false; try { if (!checkingIndex) { - pconsole.notif( - {}, + pconsole.trace( `trying to delete file : ${file.file} from ${repo.owner}/${repo.repo}` ); - const reponse = await octokit.request( + const response = await octokit.request( "DELETE /repos/{owner}/{repo}/contents/{path}", { owner: repo.owner, @@ -141,7 +140,7 @@ async function deleteFromGithubOneRepo( branch: branchName, } ); - if (reponse.status === 200) { + if (response.status === 200) { deletedSuccess++; result.deleted.push(file.file); } else { @@ -150,7 +149,7 @@ async function deleteFromGithubOneRepo( } } } catch (e) { - if (!(e instanceof DOMException)) pconsole.logs({ e: true }, e); + if (!(e instanceof DOMException)) pconsole.fatal(true, e); } } } @@ -288,7 +287,7 @@ async function checkIndexFiles( } } catch (e) { if (!(e instanceof DOMException)) { - plugin.console.notif({ e: true }, e); + plugin.console.fatal(e); return false; } } @@ -362,9 +361,8 @@ function cleanDryRun( ? indexFileDryRun(file as TFile, app.metadataCache) : false; if (!indexFile) { - console.notif( - {}, - `[DRYRUN] trying to delete file : ${file.path} from ${dryRunFolderPath}` + console.trace( + `[DRY-RUN] trying to delete file : ${file.path} from ${dryRunFolderPath}` ); vault.trash(file, false); deletedSuccess++; diff --git a/src/GitHub/files.ts b/src/GitHub/files.ts index 42d07188..81d7f53e 100644 --- a/src/GitHub/files.ts +++ b/src/GitHub/files.ts @@ -46,7 +46,7 @@ export class FilesManagement extends Publisher { sharedFile.push(file); } } catch (e) { - this.console.logs({ e: true }, e); + this.console.trace(e); } } return sharedFile; @@ -75,7 +75,7 @@ export class FilesManagement extends Publisher { files.push(file as TFile); } } catch (e) { - this.console.logs({ e: true }, e); + this.console.trace(e); } } } @@ -222,7 +222,7 @@ export class FilesManagement extends Publisher { linkedFiles.push(thisLinkedFile); } } catch (e) { - this.console.logs({}, e); + this.console.trace(e); } } } @@ -283,7 +283,7 @@ export class FilesManagement extends Publisher { embedList.push(thisEmbed); } } catch (e) { - this.console.logs({ e: true }, `Error with this links : ${embedCache.link}`, e); + this.console.debug(`Error with this links : ${embedCache.link}`, e); } } return [...new Set(embedList)]; @@ -345,7 +345,7 @@ export class FilesManagement extends Publisher { fromWhat ) as TFile; } catch (e) { - this.console.logs({ e: true }, `Error with this file : ${embed.displayText}`, e); + this.console.debug(`Error with this file : ${embed.displayText}`, e); } return undefined; } @@ -409,7 +409,7 @@ export class FilesManagement extends Publisher { } } } catch (e) { - this.console.logs({ e: true }, e); + this.console.debug(e); } return filesInRepo; } @@ -596,8 +596,7 @@ export class FilesManagement extends Publisher { if (fileInVault && isMarkdown) { const vaultEditedTime = new Date(fileInVault.stat.mtime); if (repoEditedTime && vaultEditedTime > repoEditedTime) { - this.console.logs( - {}, + this.console.debug( `edited file : ${fileInVault.path} / ${vaultEditedTime} vs ${repoEditedTime}` ); newFiles.push(fileInVault); diff --git a/src/GitHub/upload.ts b/src/GitHub/upload.ts index 0b0a9126..924991de 100644 --- a/src/GitHub/upload.ts +++ b/src/GitHub/upload.ts @@ -137,13 +137,13 @@ export default class Publisher { } catch (e) { new Notice(i18next.t("error.unablePublishNote", { file: file.name })); fileError.push(file.name); - this.console.logs({ e: true }, e); + this.console.fatal(e); } } statusBar.finish(8000); } catch (e) { - this.console.logs({ e: true }, e); - this.console.notifError(prop); + this.console.fatal(e); + this.console.noticeErrorUpload(prop); statusBar.error(prop); } } @@ -190,7 +190,7 @@ export default class Publisher { return false; } try { - this.console.logs({}, `Publishing file: ${file.path}`); + this.console.fatal(`Publishing file: ${file.path}`); fileHistory.push(file); const frontmatterSettingsFromFile = getFrontmatterSettings( frontmatter, @@ -235,7 +235,7 @@ export default class Publisher { multiRepMsg += `[${repo.owner}/${repo.repo}/${repo.branch}] `; } const msg = `Publishing ${file.name} to ${multiRepMsg}`; - this.console.logs({}, msg); + this.console.trace(msg); const fileDeleted: Deleted[] = []; const updated: UploadedFiles[][] = []; const fileError: string[] = []; @@ -268,7 +268,7 @@ export default class Publisher { } return { deleted: fileDeleted[0], uploaded: updated[0], error: fileError }; } catch (e) { - this.console.logs({ e: true }, e); + this.console.fatal(e); return false; } } @@ -307,8 +307,7 @@ export default class Publisher { }); embedFiles = await this.cleanLinkedImageIfAlreadyInRepo(embedFiles, properties); const repo = properties.frontmatter.prop; - this.console.notif( - {}, + this.console.trace( `Upload ${file.name}:${path} on ${repo.owner}/${repo.repo}:${this.branchName}` ); const notifMob = this.console.noticeMobile( @@ -338,14 +337,14 @@ export default class Publisher { ], }; } - const embeded = await this.statusBarForEmbed( + const embedded = await this.statusBarForEmbed( embedFiles, fileHistory, deepScan, properties ); - - const embeddedUploaded = embeded.uploaded; + + const embeddedUploaded = embedded.uploaded; embeddedUploaded.push(uploaded); if (autoclean || repo.dryRun.autoclean) { deleted = await deleteFromGithub(true, this.branchName, shareFiles, { @@ -357,7 +356,7 @@ export default class Publisher { return { deleted, uploaded: embeddedUploaded, - error: embeded.error, + error: embedded.error, }; } @@ -418,7 +417,7 @@ export default class Publisher { result.isUpdated = true; } } catch { - this.console.logs({}, i18next.t("error.normal")); + this.console.trace(i18next.t("error.normal")); } payload.message = msg; @@ -524,7 +523,7 @@ export default class Publisher { const contentBase64 = Base64.encode(text).toString(); return await this.upload(contentBase64, path, title, prop); } catch (e) { - this.console.notif({ e: true }, e); + this.console.fatal(e); return undefined; } } @@ -667,8 +666,7 @@ export default class Publisher { ) { newLinkedFiles.push(file); } else - this.console.logs( - {}, + this.console.trace( i18next.t("error.alreadyExists", { file: file.name }) ); } diff --git a/src/commands/purge.ts b/src/commands/purge.ts index 51f9fdc2..4e2ad47e 100644 --- a/src/commands/purge.ts +++ b/src/commands/purge.ts @@ -75,7 +75,7 @@ async function purge( if (PublisherManager.settings.plugin.displayModalRepoEditing) new ListChangedFiles(PublisherManager.plugin.app, deleted).open(); } catch (e) { - PublisherManager.plugin.console.notif({ e: true }, e); + PublisherManager.plugin.console.fatal(e); } } diff --git a/src/commands/share/all_notes.ts b/src/commands/share/all_notes.ts index e3069b0a..3f585bf3 100644 --- a/src/commands/share/all_notes.ts +++ b/src/commands/share/all_notes.ts @@ -135,7 +135,7 @@ export async function shareAllMarkedNotes( } catch (e) { fileError.push(sharedFile.name); new Notice(i18next.t("error.unablePublishNote", { file: sharedFile.name })); - plugin.console.logs({ e: true }, e); + plugin.console.trace(e); } } statusBar.finish(8000); @@ -169,11 +169,11 @@ export async function shareAllMarkedNotes( new ListChangedFiles(PublisherManager.plugin.app, listEdited).open(); } } else { - plugin.console.notifError(prop); + plugin.console.noticeErrorUpload(prop); } } } catch (error) { - plugin.console.logs({ e: true }, error); + plugin.console.trace(error); const errorFrag = document.createDocumentFragment(); const errorSpan = errorFrag.createSpan({ cls: ["error", "enveloppe", "icons", "notification"], diff --git a/src/commands/share/unique_note.ts b/src/commands/share/unique_note.ts index 6cdaf237..f0c628f5 100644 --- a/src/commands/share/unique_note.ts +++ b/src/commands/share/unique_note.ts @@ -134,13 +134,13 @@ export async function shareOneNote( new ListChangedFiles(app, listEdited).open(); } } else { - plugin.console.notifError(prop); + plugin.console.noticeErrorUpload(prop); } } } catch (error) { if (!(error instanceof DOMException)) { - plugin.console.logs({ e: true }, error); - plugin.console.notifError(getProperties(plugin, repository, frontmatter, true)); + plugin.console.fatal(error); + plugin.console.noticeErrorUpload(getProperties(plugin, repository, frontmatter, true)); } } } diff --git a/src/conversion/compiler/dataview.ts b/src/conversion/compiler/dataview.ts index 198c5c9f..ea79bc28 100644 --- a/src/conversion/compiler/dataview.ts +++ b/src/conversion/compiler/dataview.ts @@ -196,7 +196,7 @@ export async function convertDataviewQueries( const { dataviewJsMatches, inlineMatches, inlineJsMatches } = compiler.matches(); if (!matches && !inlineMatches && !dataviewJsMatches && !inlineJsMatches) { - plugin.console.logs({}, "No dataview queries found"); + plugin.console.warn("No dataview queries found"); return replacedText; } const error = i18next.t("error.dataview"); @@ -210,8 +210,8 @@ export async function convertDataviewQueries( const markdown = await compiler.dataviewDQL(queryBlock[1]); replacedText = replacedText.replace(block, markdown); } catch (e) { - plugin.console.logs({ e: true }, e); - plugin.console.notif({}, error); + plugin.console.debug(e); + plugin.console.warn(error); return queryBlock[0]; } } @@ -222,8 +222,8 @@ export async function convertDataviewQueries( const markdown = await compiler.dataviewJS(queryBlock[1]); replacedText = replacedText.replace(block, markdown); } catch (e) { - plugin.console.logs({ e: true }, e); - plugin.console.notif({}, error); + plugin.console.debug(e); + plugin.console.warn(error); return queryBlock[0]; } } @@ -236,8 +236,8 @@ export async function convertDataviewQueries( const markdown = await compiler.inlineDQLDataview(query); replacedText = replacedText.replace(code, markdown); } catch (e) { - plugin.console.logs({ e: true }, e); - plugin.console.notif({}, error); + plugin.console.debug(e); + plugin.console.warn(error); return inlineQuery[0]; } } @@ -248,8 +248,8 @@ export async function convertDataviewQueries( const markdown = await compiler.inlineDataviewJS(inlineJsQuery[1].trim()); replacedText = replacedText.replace(code, markdown); } catch (e) { - plugin.console.logs({ e: true }, e); - plugin.console.notif({}, error); + plugin.console.debug(e); + plugin.console.warn(error); return inlineJsQuery[0]; } } diff --git a/src/conversion/file_path.ts b/src/conversion/file_path.ts index 79396297..a12f26f6 100644 --- a/src/conversion/file_path.ts +++ b/src/conversion/file_path.ts @@ -96,7 +96,7 @@ export async function createRelativePath( targetRepo ); const shared = isInternalShared(frontmatterTarget, properties, targetFile.linked); - properties.plugin.console.logs({}, `Shared: ${shared} for ${targetFile.linked.path}`); + properties.plugin.console.trace(`Shared: ${shared} for ${targetFile.linked.path}`); if ( targetFile.linked.extension === "md" && !targetFile.linked.name.includes("excalidraw") && diff --git a/src/conversion/find_and_replace_text.ts b/src/conversion/find_and_replace_text.ts index 7c6bd864..4950b37b 100644 --- a/src/conversion/find_and_replace_text.ts +++ b/src/conversion/find_and_replace_text.ts @@ -99,7 +99,7 @@ export function replaceText( const replaceWithParsed = JSON.parse(`"${replaceWith}"`); return match.replace(pattern, replaceWithParsed); } catch (e) { - plugin.console.logs({ e: true }, e); + plugin.console.debug(e); return match.replace(pattern, replaceWith); } } diff --git a/src/conversion/index.ts b/src/conversion/index.ts index f32860db..54236f58 100644 --- a/src/conversion/index.ts +++ b/src/conversion/index.ts @@ -56,7 +56,7 @@ export function addHardLineBreak( } return text.replace(/^\s*\\\s*$/gim, "
"); } catch (e) { - plugin.console.notif({ e: true }, e); + plugin.console.error(e); return text; } } @@ -72,7 +72,7 @@ function tagsToYaml(toAdd: string[], plugin: Enveloppe, yaml: any) { ]; delete yaml.tag; } catch (e) { - plugin.console.notif({ e: true }, e); + plugin.console.error(e); } } if (yaml.tags) { @@ -84,7 +84,7 @@ function tagsToYaml(toAdd: string[], plugin: Enveloppe, yaml: any) { ]), ]; } catch (e) { - plugin.console.notif({ e: true }, e); + plugin.console.error(e); } } else { yaml.tags = toAdd; diff --git a/src/main.ts b/src/main.ts index 7c6f1aaa..dd7fdbc7 100644 --- a/src/main.ts +++ b/src/main.ts @@ -179,7 +179,7 @@ export default class Enveloppe extends Plugin { return defaultToken; } } catch (e) { - this.console.notif({ e: true }, e); + this.console.error(e); return ""; } return ""; @@ -218,8 +218,7 @@ export default class Enveloppe extends Plugin { await this.loadSettings(); this.console = new Logs(this); - this.console.logs( - {}, + this.console.info( dedent(`[Obsidian Enveloppe] v.${this.manifest.version} (lang: ${translationLanguage}) loaded. * You can hide HTTP logs in the console with checking the "Hide network" in the console settings. * See here: https://developer.chrome.com/docs/devtools/console/reference#network`) diff --git a/src/settings.ts b/src/settings.ts index 2c853ed3..ac0d7ace 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1435,7 +1435,7 @@ export class EnveloppeSettingsTab extends PluginSettingTab { try { return klona(object); } catch (_e) { - this.plugin.console.logs({ e: true }, "error with stringify for", object); + this.plugin.console.debug("error with stringify for", object); } } } diff --git a/src/settings/migrate.ts b/src/settings/migrate.ts index a42fadc3..d05cd70b 100644 --- a/src/settings/migrate.ts +++ b/src/settings/migrate.ts @@ -83,8 +83,8 @@ async function migrateReplaceTitle(plugin: Enveloppe) { if (plugin.settings.upload.replaceTitle instanceof Array) { return; } - - plugin.console.logs({}, i18next.t("informations.migrating.fileReplace")); + + plugin.console.trace(i18next.t("informations.migrating.fileReplace")); plugin.settings.upload.replaceTitle = [plugin.settings.upload.replaceTitle]; await plugin.saveSettings(); } @@ -98,7 +98,7 @@ async function migrateSubFolder(plugin: Enveloppe) { (e) => e.regex === `/${plugin.settings.upload.subFolder}` ) ) { - plugin.console.logs({}, i18next.t("informations.migrating.subFolder")); + plugin.console.trace(i18next.t("informations.migrating.subFolder")); //@ts-ignore if (plugin.settings.upload.subFolder.length > 0) { plugin.settings.upload.replacePath.push({ @@ -127,7 +127,7 @@ async function migrateCensor(plugin: Enveloppe) { } async function migrateWorFlow(plugin: Enveloppe) { - plugin.console.logs({}, "Migrating workflow"); + plugin.console.trace("Migrating workflow"); //@ts-ignore if (!plugin.settings.github.worflow) { return; @@ -146,11 +146,11 @@ async function migrateWorFlow(plugin: Enveloppe) { } export async function migrateToken(plugin: Enveloppe, token?: string, repo?: string) { - plugin.console.logs({}, "migrating token"); + plugin.console.trace("migrating token"); const tokenPath = createTokenPath(plugin, plugin.settings.github.tokenPath); //@ts-ignore if (plugin.settings.github.token && !token) { - plugin.console.logs({}, `Moving the GitHub Token in the file : ${tokenPath}`); + plugin.console.trace(`Moving the GitHub Token in the file : ${tokenPath}`); //@ts-ignore token = plugin.settings.github.token; //@ts-ignore @@ -160,8 +160,7 @@ export async function migrateToken(plugin: Enveloppe, token?: string, repo?: str if (token === undefined) { return; } - plugin.console.logs( - {}, + plugin.console.trace( `Moving the GitHub Token in the file : ${tokenPath} for ${ repo ?? "default" } repository` @@ -216,7 +215,7 @@ export async function migrateToken(plugin: Enveloppe, token?: string, repo?: str } async function migrateOtherRepository(plugin: Enveloppe) { - plugin.console.logs({}, "Configuring other repositories"); + plugin.console.trace("Configuring other repositories"); const otherRepo = plugin.settings.github?.otherRepo ?? []; for (const repo of otherRepo) { const workflow = { @@ -266,7 +265,7 @@ async function migrateOldSettings(plugin: Enveloppe, old: OldSettings) { if (!Object.keys(old).includes("editorMenu")) { return; } - plugin.console.logs({}, i18next.t("informations.migrating.oldSettings")); + plugin.console.trace(i18next.t("informations.migrating.oldSettings")); plugin.settings = { github: { user: old.githubName diff --git a/src/settings/modals/import_export.ts b/src/settings/modals/import_export.ts index 113738cb..0af57b72 100644 --- a/src/settings/modals/import_export.ts +++ b/src/settings/modals/import_export.ts @@ -47,7 +47,7 @@ export class ImportModal extends Modal { } async censorRepositoryData(original: EnveloppeSettings) { - this.console.logs({}, "original settings:", original); + this.console.trace("original settings:", original); this.settings.plugin.dev = original.plugin.dev; this.settings.plugin.migrated = original.plugin.migrated; this.settings.plugin.displayModalRepoEditing = @@ -84,9 +84,9 @@ export class ImportModal extends Modal { //need to convert old settings to new settings const oldSettings = importedSettings as unknown as OldSettings; await migrateSettings(oldSettings, this.plugin, true); - this.console.logs({}, i18next.t("informations.migrating.oldSettings")); + this.console.trace(i18next.t("informations.migrating.oldSettings")); } else { - this.console.logs({}, i18next.t("informations.migrating.normalFormat")); + this.console.trace(i18next.t("informations.migrating.normalFormat")); importedSettings = importedSettings as unknown as EnveloppeSettings; //create a copy of actual settings const actualSettings = clone(this.plugin.settings); @@ -306,7 +306,7 @@ export class ExportModal extends Modal { `${this.app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json` ); } catch (e) { - this.console.logs({}, "Error while deleting temporary file", e); + this.console.debug("Error while deleting temporary file", e); } const { contentEl } = this; contentEl.empty(); @@ -348,7 +348,6 @@ export class ImportLoadPreset extends FuzzySuggestModal { // eslint-disable-next-line @typescript-eslint/no-unused-vars onChooseItem(item: Preset, _evt: MouseEvent | KeyboardEvent): void { const presetSettings = item.settings; - this.console.logs({}, "onChooseItem"); try { const original = clone(this.plugin.settings); @@ -381,7 +380,7 @@ export class ImportLoadPreset extends FuzzySuggestModal { this.page.renderSettingsPage("github-configuration"); } catch (e) { new Notice(i18next.t("modals.import.error.span") + e); - this.console.notif({}, "onChooseItem", e); + this.console.error(e); } } } @@ -406,7 +405,7 @@ export async function loadAllPresets( if (!Array.isArray(githubPreset.data)) { return presetList; } - plugin.console.logs({}, "LoadAllPreset", githubPreset); + plugin.console.trace("# LoadAllPreset", githubPreset); for (const preset of githubPreset.data) { if (preset.name.endsWith(".json")) { const presetName = preset.name.replace(".json", ""); @@ -418,7 +417,7 @@ export async function loadAllPresets( } return presetList; } catch (e) { - plugin.console.notif({ e: true }, "Couldn't load preset. Error:", e); + plugin.console.error("Couldn't load preset. Error:", e); return []; } } diff --git a/src/settings/modals/token_path.ts b/src/settings/modals/token_path.ts index a2957d03..f7be5cc5 100644 --- a/src/settings/modals/token_path.ts +++ b/src/settings/modals/token_path.ts @@ -97,7 +97,7 @@ export class TokenEditPath extends Modal { input.controlEl.querySelector("input")!.style.border = "1px solid red"; new Notice(i18next.t("error.reading-token-file")); this.tokenPath = "error"; - this.console.logs({ e: true }, e); + this.console.fatal(e); } }); }); diff --git a/src/utils/data_validation_test.ts b/src/utils/data_validation_test.ts index b9166f14..c2598039 100644 --- a/src/utils/data_validation_test.ts +++ b/src/utils/data_validation_test.ts @@ -278,7 +278,7 @@ export function checkIfRepoIsInAnother( * @param {Properties} target * @return {boolean} */ - const isSame = (source: Properties, target: Properties) => { + const isSame = (source: Properties, target: Properties): boolean => { return ( source.owner === target.owner && source.repo === target.repo && @@ -394,7 +394,7 @@ export async function checkRepositoryValidity( return true; } } catch (e) { - PublisherManager.console.notif({}, e); + PublisherManager.console.error(e); return false; } return false; @@ -434,7 +434,7 @@ export async function checkRepositoryValidityWithProperties( return true; } } catch (e) { - PublisherManager.console.notif({ e: true }, e); + PublisherManager.console.error(e); return false; } return false; @@ -519,7 +519,7 @@ export async function verifyRateLimitAPI( if (commands) { new Notice(message); } else { - plugin.console.notif({}, message); + plugin.console.info(message); } return remaining; @@ -532,7 +532,7 @@ export async function verifyRateLimitAPI( (error as any).name === "HttpError" ) return 5000; - plugin.console.notif({ e: true }, error); + plugin.console.error(error); return 0; } } diff --git a/src/utils/logs.ts b/src/utils/logs.ts index b0da27b3..d4faed7e 100644 --- a/src/utils/logs.ts +++ b/src/utils/logs.ts @@ -1,40 +1,68 @@ -import {Notice, Platform, setIcon, TFile} from "obsidian"; +import {Notice, Platform, sanitizeHTMLToDom, setIcon, TFile} from "obsidian"; import type Enveloppe from "../main"; import type {EnveloppeSettings, Properties} from "@interfaces"; import i18next from "i18next"; import type Publisher from "../GitHub/upload"; +import {Logger, type ILogObj} from "tslog"; -type Arguments = { - logs?: boolean; - e?: boolean; -}; export class Logs { plugin: Enveloppe; - + logger: Logger; constructor(plugin: Enveloppe) { this.plugin = plugin; + const minLevel = this.plugin.settings.plugin?.dev ? 0 : 2; + this.logger = new Logger({prefix: ["Enveloppe"], minLevel}); + if (this.plugin.settings.plugin?.dev) { + const logFile = `${this.plugin.manifest.dir}/logs.txt`; + this.logger.attachTransport(async (logObj) => { + await this.plugin.app.vault.adapter.append(logFile, JSON.stringify(logObj)); + }); + + } } /** * Create a notice message for the log */ - notif(args: Arguments, ...messages: unknown[]) { - const { logs, e } = args; + private notif(...messages: unknown[]) { const settings = this.plugin.settings; - if (settings.plugin?.noticeError) { - new Notice(messages.join(" ")); - return; - } - let stack: string = this.callFunction(); - if (stack.contains("logs")) { - stack = this.callFunction(true); - } - const date = new Date().toISOString().slice(11, 23); - const prefix = logs ? `DEV LOGS [${date}] ${stack}:\n` : `[Enveloppe](${stack}):\n`; - if (e) console.error(prefix, ...messages); - else console.log(prefix, ...messages); - this.writeToLog(stack, e, ...messages); + if (settings.plugin?.noticeError) new Notice(messages.join(" ")); + } + + error(...messages: unknown[]) { + this.logger.error(...messages); + this.notif(messages); + } + + warn(...messages: unknown[]) { + this.logger.warn(...messages); + this.notif(messages); + } + + info(...messages: unknown[]) { + this.logger.info(...messages); + this.notif(messages); + } + + debug(...messages: unknown[]) { + this.logger.debug(...messages); + this.notif(messages); + } + + trace(...messages: unknown[]) { + this.logger.trace(...messages); + this.notif(messages); + } + + silly(...messages: unknown[]) { + this.logger.silly(...messages); + this.notif(messages); + } + + fatal(...messages: unknown[]) { + this.logger.fatal(...messages); + this.notif(messages); } /** @@ -64,69 +92,19 @@ export class Logs { }).innerHTML = message; return new Notice(noticeFrag, 0); } - - /** - * Detect the function that call the function - * @param type {boolean} if true, return the function that call the function that call the function - * @returns {string} - */ - callFunction(type?: boolean): string { - const index = type ? 4 : 3; - let callFunction = new Error().stack?.split("\n")[index].trim(); - callFunction = callFunction?.substring( - callFunction.indexOf("at ") + 3, - callFunction.lastIndexOf(" (") - ); - callFunction = callFunction?.replace("Object.callback", ""); - callFunction = callFunction ? callFunction : "main"; - callFunction = callFunction === "eval" ? "main" : callFunction; - return callFunction; - } - - /** - * Add a new option in settings "dev" - * Will make appear ALL the logs in the console - * Not just the logs for normal process - * For advanced users only - */ - logs(args: Arguments, ...messages: unknown[]) { - // noinspection JSUnusedAssignment - let { logs, e } = args; - const settings = this.plugin.settings; - logs = true; - if (e) { - this.notif({ logs, e }, ...messages); - return; - } - if (settings.plugin?.dev) { - this.notif({ logs }, ...messages); - } - } - - async writeToLog(stack: string, e?: boolean, ...messages: unknown[]) { - const settings = this.plugin.settings; - if (!settings.plugin?.dev) return; - const logs: string[] = []; - logs.push(`\n[${e ? "error" : "logs"} - ${stack}]`); - for (const message of messages) { - logs.push(String(message)); - } - const logFile = `${this.plugin.manifest.dir}/logs.txt`; - - await this.plugin.app.vault.adapter.append(logFile, logs.join(" ")); - } - - notifError(properties: Properties | Properties[]) { + + noticeErrorUpload(properties: Properties | Properties[]) { const repo = Array.isArray(properties) ? properties : [properties]; for (const repository of repo) { const notif = document.createDocumentFragment(); const notifSpan = notif.createSpan({ cls: ["error", "enveloppe", "icons", "notification"], }); + const html = sanitizeHTMLToDom(i18next.t("error.errorPublish", {repo: repository})); setIcon(notifSpan, "mail-warning"); notif.createSpan({ cls: ["error", "enveloppe", "notification"], - }).innerHTML = i18next.t("error.errorPublish", { repo: repository }); + }).appendChild(html); new Notice(notif); } }