From 98343935d98f8dff44721d11d342c199734e530b Mon Sep 17 00:00:00 2001 From: Mara Date: Mon, 28 Aug 2023 18:58:04 +0200 Subject: [PATCH] refactor(logs): refactors logs handle also fix #213 --- src/GitHub/branch.ts | 28 ++++++------- src/GitHub/delete.ts | 12 +++--- src/GitHub/files.ts | 28 ++++++------- src/GitHub/upload.ts | 17 ++++---- src/commands/commands.ts | 3 +- .../suggest_other_repo_commands_modal.ts | 4 +- src/conversion/convert_text.ts | 10 ++--- src/i18n/locales/en.json | 11 ++++++ src/i18n/locales/fr.json | 11 ++++++ src/main.ts | 4 +- src/settings.ts | 34 +++++++++++++--- src/settings/interface.ts | 1 + src/settings/migrate.ts | 18 ++++----- src/settings/modals/import_export.ts | 14 +++---- src/utils/data_validation_test.ts | 6 +-- src/utils/index.ts | 39 ++++++++++--------- 16 files changed, 146 insertions(+), 94 deletions(-) diff --git a/src/GitHub/branch.ts b/src/GitHub/branch.ts index 885efe54..a04809ca 100644 --- a/src/GitHub/branch.ts +++ b/src/GitHub/branch.ts @@ -7,7 +7,7 @@ import { GitHubPublisherSettings, RepoFrontmatter, } from "../settings/interface"; -import { noticeLog } from "../utils"; +import { logs, noticeLog } from "../utils"; import { FilesManagement } from "./files"; @@ -79,14 +79,15 @@ export class GithubBranch extends FilesManagement { sha: shaMainBranch, } ); - noticeLog(i18next.t("publish.branch.success", {branchStatus: branch.status, repo: repoFrontmatter}), - this.settings + noticeLog( + this.settings, + i18next.t("publish.branch.success", {branchStatus: branch.status, repo: repoFrontmatter}) ); return branch.status === 201; } catch (e) { // catch the old branch try { - noticeLog(e, this.settings); + logs(this.settings, e); const allBranch = await this.octokit.request( "GET /repos/{owner}/{repo}/branches", { @@ -97,10 +98,10 @@ export class GithubBranch extends FilesManagement { const mainBranch = allBranch.data.find( (branch: { name: string }) => branch.name === branchName ); - noticeLog(i18next.t("publish.branch.alreadyExists", {branchName, repo: repoFrontmatter}), this.settings); + noticeLog(this.settings, i18next.t("publish.branch.alreadyExists", {branchName, repo: repoFrontmatter})); return !!mainBranch; } catch (e) { - noticeLog(e, this.settings); + logs(this.settings, e); return false; } } @@ -132,10 +133,10 @@ export class GithubBranch extends FilesManagement { ); return PR.data.number; } catch (e) { - noticeLog(e, this.settings); + logs(this.settings, e); try { const PR = await this.octokit.request( - "GET" + " /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls", { owner: repoFrontmatter.owner, repo: repoFrontmatter.repo, @@ -145,9 +146,10 @@ export class GithubBranch extends FilesManagement { return PR.data[0].number; } catch (e) { noticeLog( - i18next.t("publish.branch.error", {error: e, repo: repoFrontmatter}), - this.settings + this.settings, + i18next.t("publish.branch.error", {error: e, repo: repoFrontmatter}) ); + logs(this.settings, e); return 0; } } @@ -207,7 +209,7 @@ export class GithubBranch extends FilesManagement { ); return branch.status === 200; } catch (e) { - noticeLog(e, this.settings); + logs(this.settings, e); new Notice(i18next.t("error.mergeconflic")); return false; } @@ -262,7 +264,7 @@ export class GithubBranch extends FilesManagement { } return true; } catch (e) { - noticeLog(e, this.settings); + logs(this.settings, e); new Notice(i18next.t("error.errorConfig", {repo: repoFrontmatter}) ); return false; @@ -311,7 +313,7 @@ export class GithubBranch extends FilesManagement { }); //@ts-ignore if (repoExist.status === 200) { - noticeLog(i18next.t("commands.checkValidity.repoExistsTestBranch", {repo: repo}), this.settings); + noticeLog(this.settings, i18next.t("commands.checkValidity.repoExistsTestBranch", {repo})); const branchExist = await this.octokit.request("GET /repos/{owner}/{repo}/branches/{branch}", { owner: repo.owner, diff --git a/src/GitHub/delete.ts b/src/GitHub/delete.ts index 47d9ed95..71045c34 100644 --- a/src/GitHub/delete.ts +++ b/src/GitHub/delete.ts @@ -11,7 +11,7 @@ import { MonoRepoProperties, RepoFrontmatter, } from "../settings/interface"; -import { noticeLog, trimObject, verifyRateLimitAPI} from "../utils"; +import { logs, noticeLog, trimObject, verifyRateLimitAPI} from "../utils"; import {isAttachment} from "../utils/data_validation_test"; import { FilesManagement } from "./files"; @@ -128,11 +128,11 @@ async function deleteFromGithubOneRepo( try { if (!checkingIndex) { noticeLog( - `trying to delete file : ${file.file} from ${repo.owner}/${repo.repo}`, - settings + settings, + `trying to delete file : ${file.file} from ${repo.owner}/${repo.repo}` ); const reponse = await octokit.request( - "DELETE" + " /repos/{owner}/{repo}/contents/{path}", + "DELETE /repos/{owner}/{repo}/contents/{path}", { owner: repo.owner, repo: repo.repo, @@ -151,7 +151,7 @@ async function deleteFromGithubOneRepo( } } } catch (e) { - if (!(e instanceof DOMException)) noticeLog(e, settings); + if (!(e instanceof DOMException)) logs(settings, e); } } } @@ -300,7 +300,7 @@ async function checkIndexFiles( } } catch (e) { if (!(e instanceof DOMException)) { - noticeLog(e, settings); + logs(settings, e); return false; } } diff --git a/src/GitHub/files.ts b/src/GitHub/files.ts index 4813b21a..174f72c1 100644 --- a/src/GitHub/files.ts +++ b/src/GitHub/files.ts @@ -14,7 +14,7 @@ import { LinkedNotes, RepoFrontmatter, Repository, } from "../settings/interface"; -import {getRepoFrontmatter, log, noticeLog} from "../utils"; +import {getRepoFrontmatter, logs} from "../utils"; import { isAttachment, isShared } from "../utils/data_validation_test"; import Publisher from "./upload"; @@ -85,7 +85,7 @@ export class FilesManagement extends Publisher { } } - log(files); + logs(this.settings, files); return files; } @@ -228,10 +228,10 @@ export class FilesManagement extends Publisher { embedList.push(thisEmbed); } } catch (e) { - noticeLog(e, this.settings); - noticeLog( - `Error with this links : ${embedCache.link}`, - this.settings + logs(this.settings, e); + logs( + this.settings, + `Error with this links : ${embedCache.link}` ); } } @@ -264,10 +264,10 @@ export class FilesManagement extends Publisher { ); if (imageLink) imageList.push(this.imageSharedOrNote(imageLink as TFile, frontmatterSourceFile) as TFile); } catch (e) { - noticeLog(e, this.settings); - noticeLog( - `Error with this file : ${embed.displayText}`, - this.settings + logs(this.settings, e); + logs( + this.settings, + `Error with this file : ${embed.displayText}` ); } } @@ -337,7 +337,7 @@ export class FilesManagement extends Publisher { } } } catch (e) { - noticeLog(e, this.settings); + logs(this.settings, e); } return filesInRepo; } @@ -525,9 +525,9 @@ export class FilesManagement extends Publisher { ) { const vaultEditedTime = new Date(fileInVault.stat.mtime); if (repoEditedTime && vaultEditedTime > repoEditedTime) { - noticeLog( - `edited file : ${fileInVault.path} / ${vaultEditedTime} vs ${repoEditedTime}`, - this.settings + logs( + this.settings, + `edited file : ${fileInVault.path} / ${vaultEditedTime} vs ${repoEditedTime}` ); newFiles.push(fileInVault); } diff --git a/src/GitHub/upload.ts b/src/GitHub/upload.ts index ae9dc60d..12305a39 100644 --- a/src/GitHub/upload.ts +++ b/src/GitHub/upload.ts @@ -27,6 +27,7 @@ import { import { getFrontmatterSettings, getRepoFrontmatter, + logs, noticeLog, } from "../utils"; import { @@ -141,7 +142,7 @@ export default class Publisher { } statusBar.finish(8000); } catch (e) { - noticeLog(e, this.settings); + logs(this.settings, e); new Notice( (i18next.t("error.errorPublish", {repo: repoFrontmatter})) ); @@ -225,7 +226,7 @@ export default class Publisher { return false; } try { - noticeLog("Publishing file: " + file.path, this.settings); + noticeLog(this.settings, `Publishing file: ${file.path}`); fileHistory.push(file); const frontmatterSettings = getFrontmatterSettings( frontmatter, @@ -262,7 +263,7 @@ export default class Publisher { multiRepMsg += `[${repo.owner}/${repo.repo}/${repo.branch}] `; } const msg = `Publishing ${file.name} to ${multiRepMsg}`; - noticeLog(msg, this.settings); + noticeLog(this.settings, msg); const fileDeleted: Deleted[] = []; const updated: UploadedFiles[][] = []; const fileError: string[] = []; @@ -295,7 +296,7 @@ export default class Publisher { } return {deleted: fileDeleted[0], uploaded: updated[0], error: fileError}; } catch (e) { - noticeLog(e, this.settings); + logs(this.settings, e); return false; } } @@ -328,8 +329,8 @@ export default class Publisher { ) { const repo = properties.frontmatter.repo; noticeLog( - `Upload ${file.name}:${path} on ${repo.owner}/${repo.repo}:${branchName}`, - this.settings + this.settings, + `Upload ${file.name}:${path} on ${repo.owner}/${repo.repo}:${branchName}` ); let deleted: Deleted = { success: false, @@ -437,8 +438,8 @@ export default class Publisher { } } catch { noticeLog( - i18next.t("error.normal"), - this.settings + this.settings, + i18next.t("error.normal") ); } diff --git a/src/commands/commands.ts b/src/commands/commands.ts index e27a44da..342748f2 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -10,6 +10,7 @@ import { createListEdited, getRepoFrontmatter, getSettingsOfMetadataExtractor, + logs, noticeLog, noticeMessage} from "../utils"; import {checkRepositoryValidityWithRepoFrontmatter} from "../utils/data_validation_test"; @@ -232,7 +233,7 @@ export async function shareOneNote( } } catch (error) { if (!(error instanceof DOMException)) { - noticeLog(error, settings); + logs(settings, error); new Notice( (i18next.t("error.errorPublish", {repo: getRepoFrontmatter(settings, repository, metadataCache.getFileCache(file)?.frontmatter)})) ); diff --git a/src/commands/suggest_other_repo_commands_modal.ts b/src/commands/suggest_other_repo_commands_modal.ts index b025f14d..d3762850 100644 --- a/src/commands/suggest_other_repo_commands_modal.ts +++ b/src/commands/suggest_other_repo_commands_modal.ts @@ -4,7 +4,7 @@ import { defaultRepo } from "src/utils/data_validation_test"; import GithubPublisherPlugin from "../main"; import {FolderSettings, Repository} from "../settings/interface"; -import {noticeLog} from "../utils"; +import {logs} from "../utils"; import { createLinkOnActiveFile, deleteCommands, repositoryValidityActiveFile, shareActiveFile, @@ -188,7 +188,7 @@ export class SuggestOtherRepoCommandsModal extends FuzzySuggestModal + toggle + .setValue(pluginSettings.displayModalRepoEditing) + .onChange(async (value) => { + pluginSettings.displayModalRepoEditing = value; + await this.plugin.saveSettings(); + }) + ); + + this.settingsPage.createEl("h4", i18next.t("settings.plugin.head.log")); + new Setting(this.settingsPage) .setName(i18next.t("settings.plugin.logNoticeHeader.title")) .setDesc(i18next.t("settings.plugin.logNoticeHeader.desc")) @@ -1081,14 +1104,15 @@ export class GithubPublisherSettingsTab extends PluginSettingTab { await this.plugin.saveSettings(); }) ); + new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.embedEditRepo.title")) - .setDesc(i18next.t("settings.plugin.embedEditRepo.desc")) + .setName(i18next.t("settings.plugin.dev.title")) + .setDesc(i18next.t("settings.plugin.dev.desc")) .addToggle((toggle) => toggle - .setValue(pluginSettings.displayModalRepoEditing) + .setValue(pluginSettings.dev ?? false) .onChange(async (value) => { - pluginSettings.displayModalRepoEditing = value; + pluginSettings.dev = value; await this.plugin.saveSettings(); }) ); diff --git a/src/settings/interface.ts b/src/settings/interface.ts index 93068885..367009ea 100644 --- a/src/settings/interface.ts +++ b/src/settings/interface.ts @@ -139,6 +139,7 @@ export interface GitHubPublisherSettings { addCmd: boolean; } noticeError: boolean; + dev?: boolean; displayModalRepoEditing: boolean; } } diff --git a/src/settings/migrate.ts b/src/settings/migrate.ts index d2af035d..2f8b5c99 100644 --- a/src/settings/migrate.ts +++ b/src/settings/migrate.ts @@ -1,7 +1,7 @@ import i18next from "i18next"; import GithubPublisher from "../main"; -import {createTokenPath, log, noticeLog} from "../utils"; +import {createTokenPath, logs, noticeLog} from "../utils"; import {FolderSettings, GithubTiersVersion, TextCleaner, TOKEN_PATH, TypeOfEditRegex} from "./interface"; export interface OldSettings { @@ -64,7 +64,7 @@ export async function migrateSettings(old: OldSettings, plugin: GithubPublisher) async function migrateReplaceTitle(plugin: GithubPublisher) { if (!(plugin.settings.upload.replaceTitle instanceof Array)) { - noticeLog(i18next.t("informations.migrating.fileReplace"), plugin.settings); + noticeLog(plugin.settings, i18next.t("informations.migrating.fileReplace")); plugin.settings.upload.replaceTitle = [plugin.settings.upload.replaceTitle]; await plugin.saveSettings(); } @@ -73,7 +73,7 @@ async function migrateReplaceTitle(plugin: GithubPublisher) { async function migrateSubFolder(plugin: GithubPublisher) { //@ts-ignore if (plugin.settings.upload.subFolder && (!plugin.settings.upload.replacePath.find((e) => e.regex === "/" + plugin.settings.upload.subFolder))) { - noticeLog(i18next.t("informations.migrating.subFolder"), plugin.settings); + noticeLog(plugin.settings, i18next.t("informations.migrating.subFolder")); //@ts-ignore if (plugin.settings.upload.subFolder.length > 0) { plugin.settings.upload.replacePath.push({ @@ -104,7 +104,7 @@ async function migrateCensor(plugin: GithubPublisher) { } async function migrateWorFlow(plugin: GithubPublisher) { - log("Migrating workflow"); + logs(plugin.settings, "Migrating workflow"); //@ts-ignore if (plugin.settings.github.worflow) { //@ts-ignore @@ -122,11 +122,11 @@ async function migrateWorFlow(plugin: GithubPublisher) { } export async function migrateToken(plugin: GithubPublisher, token?: string) { - log("migrating token"); + logs(plugin.settings, "migrating token"); const tokenPath = createTokenPath(plugin, plugin.settings.github.tokenPath); //@ts-ignore if (plugin.settings.github.token && !token) { - noticeLog(`Moving the GitHub Token in the file : ${tokenPath}`, plugin.settings); + logs(plugin.settings, `Moving the GitHub Token in the file : ${tokenPath}`); //@ts-ignore token = plugin.settings.github.token; //@ts-ignore @@ -136,14 +136,14 @@ export async function migrateToken(plugin: GithubPublisher, token?: string) { if (token === undefined) { return; } - noticeLog(`Moving the GitHub Token in the file : ${tokenPath}`, plugin.settings); + logs(plugin.settings, `Moving the GitHub Token in the file : ${tokenPath}`); const envToken = `GITHUB_TOKEN=${token}`; await plugin.app.vault.adapter.write(tokenPath, envToken); } async function migrateOtherRepository(plugin: GithubPublisher) { - log("Configuring other repositories"); + logs(plugin.settings, "Configuring other repositories"); const otherRepo = plugin.settings.github?.otherRepo ?? []; for (const repo of otherRepo) { const workflow = { @@ -182,7 +182,7 @@ async function migrateOtherRepository(plugin: GithubPublisher) { async function migrateOldSettings(plugin: GithubPublisher, old: OldSettings) { if (Object.keys(old).includes("editorMenu")) { - noticeLog(i18next.t("informations.migrating.oldSettings"), plugin.settings); + noticeLog(plugin.settings, i18next.t("informations.migrating.oldSettings")); plugin.settings = { github: { diff --git a/src/settings/modals/import_export.ts b/src/settings/modals/import_export.ts index cd532299..89e6f509 100644 --- a/src/settings/modals/import_export.ts +++ b/src/settings/modals/import_export.ts @@ -12,7 +12,7 @@ import { import GithubPublisher from "../../main"; import {GithubPublisherSettingsTab} from "../../settings"; -import {log, noticeLog} from "../../utils"; +import {logs} from "../../utils"; import {GitHubPublisherSettings, Preset} from "../interface"; import { migrateSettings,OldSettings } from "../migrate"; @@ -40,7 +40,7 @@ export class ImportModal extends Modal { } async censorRepositoryData(original: GitHubPublisherSettings) { - log("original settings", original); + logs(original, "original settings:", original); this.plugin.settings.plugin = original.plugin; this.plugin.settings.github.repo = original.github.repo; this.plugin.settings.github.user = original.github.user; @@ -70,9 +70,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); - noticeLog(i18next.t("informations.migrating.oldSettings"), this.plugin.settings); + logs(this.plugin.settings, i18next.t("informations.migrating.oldSettings")); } else { - noticeLog(i18next.t("informations.migrating.normalFormat"), this.plugin.settings); + logs(this.plugin.settings, i18next.t("informations.migrating.normalFormat")); importedSettings = importedSettings as unknown as GitHubPublisherSettings; //create a copy of actual settings const actualSettings = clone(this.plugin.settings); @@ -298,7 +298,7 @@ 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; - log("onChooseItem", presetSettings); + logs(presetSettings,"onChooseItem"); try { const original = clone(this.plugin.settings); if (!(presetSettings.upload.replaceTitle instanceof Array)) { @@ -319,7 +319,7 @@ export class ImportLoadPreset extends FuzzySuggestModal { } catch (e) { new Notice(i18next.t("modals.import.error.span") + e); - log("onChooseItem", e); + logs(this.plugin.settings, "onChooseItem", e); } } } @@ -338,7 +338,7 @@ export async function loadAllPresets(octokit: Octokit, plugin: GithubPublisher): if (!Array.isArray(githubPreset.data)) { return presetList; } - log("LoadAllPreset", githubPreset); + logs(plugin.settings, "LoadAllPreset", githubPreset); for (const preset of githubPreset.data) { if (preset.name.endsWith(".json")) { const presetName = preset.name.replace(".json", ""); diff --git a/src/utils/data_validation_test.ts b/src/utils/data_validation_test.ts index ee9744ef..49cbe8e1 100644 --- a/src/utils/data_validation_test.ts +++ b/src/utils/data_validation_test.ts @@ -4,7 +4,7 @@ import GithubPublisher from "src/main"; import {GithubBranch} from "../GitHub/branch"; import {FrontmatterConvert, GitHubPublisherSettings, MultiProperties, RepoFrontmatter, Repository} from "../settings/interface"; -import {getRepoFrontmatter, noticeLog, verifyRateLimitAPI} from "."; +import {getRepoFrontmatter, logs, verifyRateLimitAPI} from "."; /** * Check if the file is a valid file to publish @@ -287,7 +287,7 @@ export async function checkRepositoryValidity( } } catch (e) { - noticeLog(e, settings); + logs(settings, e); return false; } return false; @@ -330,7 +330,7 @@ export async function checkRepositoryValidityWithRepoFrontmatter( } } catch (e) { - noticeLog(e, settings); + logs(settings, e); return false; } return false; diff --git a/src/utils/index.ts b/src/utils/index.ts index dfc429fd..e19930ec 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -22,27 +22,28 @@ import { * @param {GithubPublisher} settings to know if it should use the notice or the log */ //eslint-disable-next-line @typescript-eslint/no-explicit-any -export function noticeLog(message: any, settings: GitHubPublisherSettings) { +export function noticeLog(settings: GitHubPublisherSettings, ...messages: unknown[]) { if (settings.plugin.noticeError) { - new Notice(message); - } else { - console.log("[GITHUB PUBLISHER]" , message); + new Notice(messages.join(" ")); + return; } + let callFunction = new Error().stack?.split("\n")[2].trim(); + callFunction = callFunction?.substring(callFunction.indexOf("at ") + 3, callFunction.lastIndexOf(" (")); + callFunction = callFunction?.replace("Object.callback", ""); + callFunction = callFunction ? callFunction : "main"; + const date = new Date().toISOString().slice(11, 23); + console.log(`[${date}](${callFunction}):\n`, ...messages); } /** - * Create a debug message for the log - * Only display if debug is enabled - * @param {unknown[]} args + * 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 */ -export function log(...args: unknown[]) { - if (process.env.BUILD_ENV && process.env.BUILD_ENV==="development" && Platform.isDesktop) { - let callFunction = new Error().stack?.split("\n")[2].trim(); - callFunction = callFunction?.substring(callFunction.indexOf("at ") + 3, callFunction.lastIndexOf(" (")); - callFunction = callFunction?.replace("Object.callback", ""); - callFunction = callFunction ? callFunction : "main"; - const date = new Date().toISOString().slice(11, 23); - console.log(`[${date}](${callFunction}):\n`, ...args); +export function logs(settings: GitHubPublisherSettings, ...messages: unknown[]) { + if (settings.plugin?.dev) { + noticeLog(settings, ...messages); } } @@ -53,7 +54,7 @@ export function log(...args: unknown[]) { * @param {string[]} fileError * @return {ListEditedFiles} */ -export function createListEdited(listUploaded: UploadedFiles[], deleted: Deleted, fileError: string[]) { +export function createListEdited(listUploaded: UploadedFiles[], deleted: Deleted, fileError: string[]): ListEditedFiles { const listEdited: ListEditedFiles = { added: [], edited: [], @@ -237,7 +238,7 @@ async function noticeMessageOneRepo( if (file instanceof String) { successMsg = i18next.t("informations.successfulPublish", { nbNotes: noticeValue, repo: repo }); } else { - log("file published :", noticeValue); + logs(settings, "file published :", noticeValue); successMsg = i18next.t("informations.successPublishOneNote", { file: noticeValue, repo: repo }); } if (settings.github.workflow.name.length > 0) { @@ -661,10 +662,10 @@ export async function verifyRateLimitAPI(octokit: Octokit, settings: GitHubPubli return 0; } if (!commands) { - noticeLog(i18next.t("commands.checkValidity.rateLimit.notLimited", { + noticeLog(settings, i18next.t("commands.checkValidity.rateLimit.notLimited", { remaining: remaining, resetTime: time - }), settings); + })); } else { new Notice(i18next.t("commands.checkValidity.rateLimit.notLimited", { remaining: remaining,