From b68d95abf1b246de1b6050fdd4a96c2728d6f2ea Mon Sep 17 00:00:00 2001 From: Mara Date: Wed, 8 May 2024 05:21:38 +0200 Subject: [PATCH] refactor: rename repoFrontmatter & remove checking for validity if already validated docs: add comments for loadsettings --- src/GitHub/branch.ts | 120 +++++++++++++-------------- src/GitHub/delete.ts | 54 ++++++------- src/GitHub/files.ts | 10 +-- src/GitHub/upload.ts | 130 +++++++++++++++--------------- src/commands/callback.ts | 10 +-- src/commands/file_menu.ts | 20 ++--- src/commands/index.ts | 68 ++++++++-------- src/commands/plugin_commands.ts | 36 ++++----- src/conversion/file_path.ts | 42 +++++----- src/interfaces/index.ts | 2 +- src/interfaces/main.ts | 10 +-- src/interfaces/properties.ts | 12 +-- src/main.ts | 40 ++++----- src/utils/data_validation_test.ts | 55 +++++++------ src/utils/index.ts | 60 +++++++++----- src/utils/parse_frontmatter.ts | 98 +++++++++++----------- src/utils/status_bar.ts | 4 +- 17 files changed, 399 insertions(+), 372 deletions(-) diff --git a/src/GitHub/branch.ts b/src/GitHub/branch.ts index 042d316e..ddbbcbd8 100644 --- a/src/GitHub/branch.ts +++ b/src/GitHub/branch.ts @@ -20,17 +20,17 @@ export class GithubBranch extends FilesManagement { } /** - * Check if RepoFrontmatter is an array or not and run the newBranchOnRepo function on each repo - * @param {Properties[] | Properties} repoFrontmatter The repo to use + * Check if Properties is an array or not and run the newBranchOnRepo function on each repo + * @param {Properties[] | Properties} prop The repo to use */ async newBranch( - repoFrontmatter: Properties[] | Properties + prop: Properties[] | Properties ) { - repoFrontmatter = Array.isArray(repoFrontmatter) - ? repoFrontmatter - : [repoFrontmatter]; - for (const repo of repoFrontmatter) { + prop = Array.isArray(prop) + ? prop + : [prop]; + for (const repo of prop) { await this.newBranchOnRepo(repo); } } @@ -38,23 +38,23 @@ export class GithubBranch extends FilesManagement { /** * Create a new branch on the repo named "Vault-date" * Pass if the branch already exists - * Run in a loop in the newBranch function if RepoFrontmatter[] is passed - * @param {Properties} repoFrontmatter The repo to use + * Run in a loop in the newBranch function if Properties[] is passed + * @param {Properties} prop The repo to use * @return {Promise} True if the branch is created */ async newBranchOnRepo( - repoFrontmatter: Properties + prop: Properties ): Promise { const allBranch = await this.octokit.request( "GET /repos/{owner}/{repo}/branches", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, } ); const mainBranch = allBranch.data.find( - (branch: { name: string }) => branch.name === repoFrontmatter.branch + (branch: { name: string }) => branch.name === prop.branch ); if (!mainBranch) return false; try { @@ -62,15 +62,15 @@ export class GithubBranch extends FilesManagement { const branch = await this.octokit.request( "POST /repos/{owner}/{repo}/git/refs", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, ref: `refs/heads/${this.branchName}`, sha: shaMainBranch, } ); notif( {settings: this.settings}, - i18next.t("publish.branch.success", {branchStatus: branch.status, repo: repoFrontmatter}) + i18next.t("publish.branch.success", {branchStatus: branch.status, repo: prop}) ); return branch.status === 201; } catch (e) { @@ -79,14 +79,14 @@ export class GithubBranch extends FilesManagement { const allBranch = await this.octokit.request( "GET /repos/{owner}/{repo}/branches", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, } ); const mainBranch = allBranch.data.find( (branch: { name: string }) => branch.name === this.branchName ); - notif({settings: this.settings}, i18next.t("publish.branch.alreadyExists", {branchName:this.branchName, repo: repoFrontmatter})); + notif({settings: this.settings}, i18next.t("publish.branch.alreadyExists", {branchName:this.branchName, repo: prop})); return !!mainBranch; } catch (e) { notif({settings: this.settings, e: true}, e); @@ -96,25 +96,25 @@ export class GithubBranch extends FilesManagement { } /** - * Create a pull request on repoFrontmatter.branch with the branchName - * Run in a loop in the pullRequest function if RepoFrontmatter[] is passed - * @param {Properties} repoFrontmatter The repo to use + * Create a pull request on prop.branch with the branchName + * Run in a loop in the pullRequest function if Properties[] is passed + * @param {Properties} prop The repo to use * @return {Promise} False in case of error, the pull request number otherwise */ async pullRequestOnRepo( - repoFrontmatter: Properties, + prop: Properties, ): Promise { try { const PR = await this.octokit.request( "POST /repos/{owner}/{repo}/pulls", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, title: i18next.t("publish.branch.prMessage", {branchName:this.branchName}), body: "", head: this.branchName, - base: repoFrontmatter.branch, + base: prop.branch, } ); return PR.data.number; @@ -125,8 +125,8 @@ export class GithubBranch extends FilesManagement { const PR = await this.octokit.request( "GET /repos/{owner}/{repo}/pulls", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, state: "open", } ); @@ -135,7 +135,7 @@ export class GithubBranch extends FilesManagement { // there is no open PR and impossible to create a new one notif( {settings: this.settings, e: true}, - i18next.t("publish.branch.error", {error: e, repo: repoFrontmatter}) + i18next.t("publish.branch.error", {error: e, repo: prop}) ); return 0; } @@ -144,13 +144,13 @@ export class GithubBranch extends FilesManagement { /** * After the merge, delete the new branch on the repo - * Run in a loop in the updateRepository function if RepoFrontmatter[] is passed - * @param {Properties} repoFrontmatter The repo to use + * Run in a loop in the updateRepository function if Properties[] is passed + * @param {Properties} prop The repo to use * @return {Promise} true if the branch is deleted */ async deleteBranchOnRepo( - repoFrontmatter: Properties + prop: Properties ): Promise { try { const branch = await this.octokit.request( @@ -158,8 +158,8 @@ export class GithubBranch extends FilesManagement { " /repos/{owner}/{repo}/git/refs/heads/" + this.branchName, { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, } ); return branch.status === 200; @@ -171,22 +171,22 @@ export class GithubBranch extends FilesManagement { /** * Automatically merge pull request from the plugin (only if the settings allow it) - * Run in a loop in the updateRepository function if RepoFrontmatter[] is passed + * Run in a loop in the updateRepository function if Properties[] is passed * @param {number} pullRequestNumber number of the new pullrequest - * @param {Properties} repoFrontmatter The repo to use + * @param {Properties} prop The repo to use */ async mergePullRequestOnRepo( pullRequestNumber: number, - repoFrontmatter: Properties + prop: Properties ) { - const commitMsg = repoFrontmatter.commitMsg || repoFrontmatter.commitMsg.trim().length > 0 ? `${repoFrontmatter.commitMsg} #${pullRequestNumber}` : `[PUBLISHER] Merge #${pullRequestNumber}`; + const commitMsg = prop.commitMsg || prop.commitMsg.trim().length > 0 ? `${prop.commitMsg} #${pullRequestNumber}` : `[PUBLISHER] Merge #${pullRequestNumber}`; try { const branch = await this.octokit.request( "PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, pull_number: pullRequestNumber, commit_title: commitMsg, merge_method: "squash", @@ -201,19 +201,19 @@ export class GithubBranch extends FilesManagement { } /** * Update the repository with the new branch : PR, merging and deleting the branch if allowed by the global settings - * @param {Properties | Properties[]} repoFrontmatter The repo to use + * @param {Properties | Properties[]} prop The repo to use * @returns {Promise} True if the update is successful */ async updateRepository( - repoFrontmatter: Properties | Properties[], + prop: Properties | Properties[], dryRun = false ): Promise { if (dryRun) return true; - repoFrontmatter = Array.isArray(repoFrontmatter) - ? repoFrontmatter - : [repoFrontmatter]; + prop = Array.isArray(prop) + ? prop + : [prop]; const success: boolean[] = []; - for (const repo of repoFrontmatter) { + for (const repo of prop) { success.push(await this.updateRepositoryOnOne(repo)); } return !success.every((value) => value === false); @@ -221,26 +221,26 @@ export class GithubBranch extends FilesManagement { /** * Run merging + deleting branch in once, for one repo - * Run in a loop in the updateRepository function if RepoFrontmatter[] is passed - * @param {Properties} repoFrontmatter The repo to use + * Run in a loop in the updateRepository function if Properties[] is passed + * @param {Properties} prop The repo to use * @returns {Promise} true if the update is successful */ async updateRepositoryOnOne( - repoFrontmatter: Properties + prop: Properties ): Promise { if (this.settings.github.dryRun.enable) return true; try { const pullRequest = await this.pullRequestOnRepo( - repoFrontmatter + prop ); - if (repoFrontmatter.automaticallyMergePR && pullRequest !== 0) { + if (prop.automaticallyMergePR && pullRequest !== 0) { const PRSuccess = await this.mergePullRequestOnRepo( pullRequest, - repoFrontmatter + prop ); if (PRSuccess) { - await this.deleteBranchOnRepo(repoFrontmatter); + await this.deleteBranchOnRepo(prop); return true; } return false; @@ -248,7 +248,7 @@ export class GithubBranch extends FilesManagement { return true; } catch (e) { logs({settings: this.settings, e: true}, e); - new Notice(i18next.t("error.errorConfig", {repo: repoFrontmatter}) + new Notice(i18next.t("error.errorConfig", {repo: prop}) ); return false; } @@ -262,18 +262,18 @@ export class GithubBranch extends FilesManagement { * - the main branch exists * Send a notice if the repo doesn't exist or if the main branch doesn't exist * Note: If one of the repo defined in the list doesn't exist, the rest of the list will not be checked because the octokit request throws an error - * @param {Properties | Properties[]} repoFrontmatter + * @param {Properties | Properties[]} prop * @param silent Send a notice if the repo is valid * @return {Promise} */ async checkRepository( - repoFrontmatter: Properties | Properties[], + prop: Properties | Properties[], silent= true): Promise { - repoFrontmatter = Array.isArray(repoFrontmatter) - ? repoFrontmatter - : [repoFrontmatter]; - for (const repo of repoFrontmatter) { + prop = Array.isArray(prop) + ? prop + : [prop]; + for (const repo of prop) { try { const repoExist = await this.octokit.request("GET /repos/{owner}/{repo}", { owner: repo.owner, diff --git a/src/GitHub/delete.ts b/src/GitHub/delete.ts index c2508644..5447ede2 100644 --- a/src/GitHub/delete.ts +++ b/src/GitHub/delete.ts @@ -10,7 +10,7 @@ import { GitHubPublisherSettings, GithubRepo, MonoRepoProperties, - RepoFrontmatter, + Properties, } from "../interfaces"; import { logs, notif, trimObject} from "../utils"; import {isAttachment, verifyRateLimitAPI} from "../utils/data_validation_test"; @@ -22,7 +22,7 @@ import { FilesManagement } from "./files"; * @param {boolean} silent - default false, if true, no notice will be displayed * @param {string} branchName * @param {FilesManagement} filesManagement - * @param {MonoRepoProperties} repoProperties - frontmatter can be an array of RepoFrontmatter or a single RepoFrontmatter + * @param {MonoRepoProperties} repoProperties - frontmatter can be an array of Properties or a single Properties * @return {Promise} deleted : list of deleted file, undeleted : list of undeleted file, success : true if all file are deleted */ export async function deleteFromGithub( @@ -32,14 +32,14 @@ export async function deleteFromGithub( repoProperties: MonoRepoProperties, ): Promise { - const repoFrontmatter = Array.isArray(repoProperties.frontmatter) + const prop = Array.isArray(repoProperties.frontmatter) ? repoProperties.frontmatter : [repoProperties.frontmatter]; const deleted: Deleted[] = []; - for (const repo of repoFrontmatter) { + for (const repo of prop) { const monoProperties: MonoRepoProperties = { frontmatter: repo, - repo: repoProperties.repo, + repository: repoProperties.repository, convert: frontmatterSettingsRepository(filesManagement.plugin, repo), }; deleted.push(await deleteFromGithubOneRepo( @@ -57,7 +57,7 @@ export async function deleteFromGithub( * @param {boolean} silent - default false, if true, no notice will be displayed * @param {string} branchName * @param {FilesManagement} filesManagement - * @param {MonoRepoProperties} repoProperties - frontmatter must be a single RepoFrontmatter so we use the MonoRepoProperties interface + * @param {MonoRepoProperties} repoProperties - frontmatter must be a single Properties so we use the MonoRepoProperties interface */ async function deleteFromGithubOneRepo( @@ -87,9 +87,9 @@ async function deleteFromGithubOneRepo( logs({settings}, `No file to delete in ${repo.owner}/${repo.repo}`); return {success: false, deleted: [], undeleted: []}; } - const allSharedFiles = filesManagement.getAllFileWithPath(repoProperties.repo, repoProperties.convert); + const allSharedFiles = filesManagement.getAllFileWithPath(repoProperties.repository, repoProperties.convert); const allSharedConverted = allSharedFiles.map((file) => { - return { converted: file.converted, repo: file.repoFrontmatter }; + return { converted: file.converted, repo: file.prop }; }); let deletedSuccess = 0; let deletedFailed = 0; @@ -105,10 +105,10 @@ async function deleteFromGithubOneRepo( const isMarkdownForAnotherRepo = file.file.trim().endsWith(".md") ? !allSharedConverted.some( (f) => { - let repoFrontmatter = f.repo; - if (Array.isArray(repoFrontmatter)) { - repoFrontmatter = repoFrontmatter.find((r) => JSON.stringify(r.repo) === JSON.stringify(repo.repo)); - } return f.converted === file.file && repoFrontmatter; + let prop = f.repo; + if (Array.isArray(prop)) { + prop = prop.find((r) => JSON.stringify(r.repo) === JSON.stringify(repo.repo)); + } return f.converted === file.file && prop; }) : false; const isNeedToBeDeleted = isInObsidian @@ -205,14 +205,14 @@ function excludedFileFromDelete( export async function filterGithubFile( fileInRepo: GithubRepo[], settings: GitHubPublisherSettings, - repoFrontmatter: RepoFrontmatter + prop: Properties ): Promise { const sharedFilesInRepo: GithubRepo[] = []; for (const file of fileInRepo) { - const behavior = repoFrontmatter.path?.type ?? settings.upload.behavior; - const root = repoFrontmatter.path?.rootFolder ?? settings.upload.rootFolder; - const defaultName = repoFrontmatter.path?.defaultName ?? settings.upload.defaultName; - const attachmentFolder = repoFrontmatter.path?.attachment?.folder ?? settings.embed.folder; + const behavior = prop.path?.type ?? settings.upload.behavior; + const root = prop.path?.rootFolder ?? settings.upload.rootFolder; + const defaultName = prop.path?.defaultName ?? settings.upload.defaultName; + const attachmentFolder = prop.path?.attachment?.folder ?? settings.embed.folder; if ( (file.file.includes(defaultName) || (behavior === FolderSettings.yaml && @@ -249,7 +249,7 @@ function parseYamlFrontmatter(contents: string): unknown { * @param {Octokit} octokit GitHub API * @param {GitHubPublisherSettings} settings Settings of the plugin * @param {string} path path of the file to check - * @param {RepoFrontmatter} repoFrontmatter repository informations + * @param {Properties} prop repository informations * @return {Promise} true if the file must be deleted */ @@ -257,14 +257,14 @@ async function checkIndexFiles( octokit: Octokit, settings: GitHubPublisherSettings, path: string, - repoFrontmatter: RepoFrontmatter + prop: Properties ): Promise { try { const fileRequest = await octokit.request( "GET /repos/{owner}/{repo}/contents/{path}", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, path, } ); @@ -309,8 +309,8 @@ function cleanDryRun( Vault.recurseChildren(dryRunFolder as TFolder, (file: TAbstractFile) => { if (!excludedFileFromDelete(normalizePath(file.path.replace(dryRunFolderPath, "")), settings) && (isAttachment(file.path, settings.embed.unHandledObsidianExt) || file.path.match("md$")) && file instanceof TFile) dryRunFiles.push(file); }); - const allSharedFiles = filesManagement.getAllFileWithPath(repoProperties.repo, repoProperties.convert).map((file) => { - return { converted: file.converted, repo: file.repoFrontmatter }; + const allSharedFiles = filesManagement.getAllFileWithPath(repoProperties.repository, repoProperties.convert).map((file) => { + return { converted: file.converted, repo: file.prop }; }); let deletedSuccess = 0; const result: Deleted = { @@ -327,10 +327,10 @@ function cleanDryRun( const isMarkdownForAnotherRepo = file.path.trim().endsWith(".md") ? !allSharedFiles.some( (f) => { - let repoFrontmatter = f.repo; - if (Array.isArray(repoFrontmatter)) { - repoFrontmatter = repoFrontmatter.find((r) => JSON.stringify(r.repo) === JSON.stringify(repo.repo)); - } return f.converted === convertedPath && repoFrontmatter; + let prop = f.repo; + if (Array.isArray(prop)) { + prop = prop.find((r) => JSON.stringify(r.repo) === JSON.stringify(repo.repo)); + } return f.converted === convertedPath && prop; }) : false; const isNeedToBeDeleted = isInObsidian ? isMarkdownForAnotherRepo : true; diff --git a/src/GitHub/files.ts b/src/GitHub/files.ts index b6cc6427..9f2f8e30 100644 --- a/src/GitHub/files.ts +++ b/src/GitHub/files.ts @@ -16,7 +16,7 @@ import { import GithubPublisher from "../main"; import {logs} from "../utils"; import { isAttachment, isShared } from "../utils/data_validation_test"; -import { frontmatterFromFile, getRepoFrontmatter } from "../utils/parse_frontmatter"; +import { frontmatterFromFile, getProperties } from "../utils/parse_frontmatter"; import Publisher from "./upload"; export class FilesManagement extends Publisher { @@ -99,7 +99,7 @@ export class FilesManagement extends Publisher { getAllFileWithPath(repo: Repository | null, convert: PropertiesConversion): ConvertedLink[] { const files = this.vault.getFiles().filter((x) => !x.path.startsWith(this.settings.github.dryRun.folderName)); const allFileWithPath: ConvertedLink[] = []; - const sourceFrontmatter = getRepoFrontmatter(this.plugin, repo, null, true); + const sourceFrontmatter = getProperties(this.plugin, repo, null, true); for (const file of files) { if (isAttachment(file.name, this.settings.embed.unHandledObsidianExt)) { const filepath = getImagePath(file, this.plugin, convert, sourceFrontmatter ); @@ -110,16 +110,16 @@ export class FilesManagement extends Publisher { } else if (file.extension == "md") { const frontMatter = frontmatterFromFile(file, this.plugin, repo); if (isShared(frontMatter, this.settings, file, repo)) { - const repoFrontmatter = getRepoFrontmatter( + const prop = getProperties( this.plugin, repo, frontMatter ); - const filepath = getReceiptFolder(file, repo, this.plugin, repoFrontmatter); + const filepath = getReceiptFolder(file, repo, this.plugin, prop); allFileWithPath.push({ converted: filepath, real: file.path, - repoFrontmatter, + prop, }); } } diff --git a/src/GitHub/upload.ts b/src/GitHub/upload.ts index ea61e991..df1303dc 100644 --- a/src/GitHub/upload.ts +++ b/src/GitHub/upload.ts @@ -26,7 +26,7 @@ import { MonoRepoProperties, MultiProperties, MultiRepoProperties, - RepoFrontmatter, UploadedFiles, + Properties, UploadedFiles, } from "../interfaces"; import GithubPublisher from "../main"; import { @@ -43,7 +43,7 @@ import { isShared, } from "../utils/data_validation_test"; import { LOADING_ICON } from "../utils/icons"; -import { frontmatterFromFile, frontmatterSettingsRepository, getFrontmatterSettings, getRepoFrontmatter } from "../utils/parse_frontmatter"; +import { frontmatterFromFile, frontmatterSettingsRepository, getFrontmatterSettings, getProperties } from "../utils/parse_frontmatter"; import { ShareStatusBar } from "../utils/status_bar"; import { deleteFromGithub } from "./delete"; import { FilesManagement } from "./files"; @@ -101,10 +101,10 @@ export default class Publisher { linkedFiles.length, true ); - const repoFrontmatter = properties.frontmatter.repo; + const prop = properties.frontmatter.prop; const repoProperties: MonoRepoProperties = { - frontmatter: properties.frontmatter.repo, - repo: properties.repository, + frontmatter: properties.frontmatter.prop, + repository: properties.repository, convert: properties.frontmatter.general, }; try { @@ -152,8 +152,8 @@ export default class Publisher { statusBar.finish(8000); } catch (e) { logs({ settings: this.settings, e: true }, e); - notifError(repoFrontmatter); - statusBar.error(repoFrontmatter); + notifError(prop); + statusBar.error(prop); } } return { @@ -185,14 +185,14 @@ export default class Publisher { ); let frontmatter = frontmatterFromFile(file, this.plugin, null); if (sourceFrontmatter && frontmatter) frontmatter = merge(frontmatter, sourceFrontmatter); - const repoFrontmatter = getRepoFrontmatter(this.plugin, repo.repo, frontmatter); - const isNotEmpty = await checkEmptyConfiguration(repoFrontmatter, this.plugin); - repo.frontmatter = repoFrontmatter; + const prop = getProperties(this.plugin, repo.repository, frontmatter); + const isNotEmpty = await checkEmptyConfiguration(prop, this.plugin); + repo.frontmatter = prop; if ( - !isShared(frontmatter, this.settings, file, repo.repo) || + !isShared(frontmatter, this.settings, file, repo.repository) || fileHistory.includes(file) || !checkIfRepoIsInAnother( - repoFrontmatter, + prop, repo.frontmatter ) || !isNotEmpty ) { @@ -204,9 +204,9 @@ export default class Publisher { const frontmatterSettingsFromFile = getFrontmatterSettings( frontmatter, this.settings, - repo.repo + repo.repository ); - const frontmatterRepository = frontmatterSettingsRepository(this.plugin, repo.repo); + const frontmatterRepository = frontmatterSettingsRepository(this.plugin, repo.repository); const frontmatterSettings = merge(frontmatterRepository, frontmatterSettingsFromFile); let embedFiles = shareFiles.getSharedEmbed( file, @@ -224,18 +224,18 @@ export default class Publisher { plugin: this.plugin, frontmatter: { general: frontmatterSettings, - repo: repo.frontmatter, + prop: repo.frontmatter, }, - repository: repo.repo, - filepath: getReceiptFolder(file, repo.repo, this.plugin, repo.frontmatter), + repository: repo.repository, + filepath: getReceiptFolder(file, repo.repository, this.plugin, repo.frontmatter), }; text = await mainConverting(text, file, frontmatter, linkedFiles, multiProperties); const path = multiProperties.filepath; - const repoFrontmatter = Array.isArray(repo.frontmatter) + const prop = Array.isArray(repo.frontmatter) ? repo.frontmatter : [repo.frontmatter]; let multiRepMsg = ""; - for (const repo of repoFrontmatter) { + for (const repo of prop) { multiRepMsg += `[${repo.owner}/${repo.repo}/${repo.branch}] `; } const msg = `Publishing ${file.name} to ${multiRepMsg}`; @@ -243,12 +243,12 @@ export default class Publisher { const fileDeleted: Deleted[] = []; const updated: UploadedFiles[][] = []; const fileError: string[] = []; - for (const repo of repoFrontmatter) { + for (const repo of prop) { const monoProperties: MonoProperties = { plugin: this.plugin, frontmatter: { general: frontmatterSettings, - repo, + prop: repo, source: sourceFrontmatter }, repository: multiProperties.repository, @@ -307,7 +307,7 @@ export default class Publisher { load.createEl("span", { cls: ["obsidian-publisher", "loading", "icons"] }).innerHTML = LOADING_ICON; load.createEl("span", { text: i18next.t("statusBar.loading"), cls: ["obsidian-publisher", "loading", "icons"] }); embedFiles = await this.cleanLinkedImageIfAlreadyInRepo(embedFiles, properties); - const repo = properties.frontmatter.repo; + const repo = properties.frontmatter.prop; notif( { settings: this.settings }, `Upload ${file.name}:${path} on ${repo.owner}/${repo.repo}:${this.branchName}` @@ -344,7 +344,7 @@ export default class Publisher { shareFiles, { frontmatter: repo, - repo: properties.repository, + repository: properties.repository, convert: properties.frontmatter.general, } ); @@ -361,22 +361,22 @@ export default class Publisher { * @param {string} content Contents of the file sent * @param {string} title for commit message, name of the file * @param {string} path path in GitHub - * @param {RepoFrontmatter} repoFrontmatter frontmatter settings + * @param {Properties} prop frontmatter settings */ async upload( content: string, path: string, title: string = "", - repoFrontmatter: RepoFrontmatter + prop: Properties ) { - if (!repoFrontmatter.repo) { + if (!prop.repo) { new Notice( "Config error : You need to define a github repo in the plugin settings" ); throw {}; } - if (!repoFrontmatter.owner) { + if (!prop.owner) { new Notice( "Config error : You need to define your github username in the plugin settings" ); @@ -389,8 +389,8 @@ export default class Publisher { msg = `PUSH ATTACHMENT : ${title}`; } const payload = { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, path, message: `Adding ${title}`, content, @@ -405,8 +405,8 @@ export default class Publisher { const response = await octokit.request( "GET /repos/{owner}/{repo}/contents/{path}", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, path, ref: this.branchName, } @@ -441,7 +441,7 @@ export default class Publisher { properties: MonoProperties, ) { let imageBin = await this.vault.readBinary(imageFile); - const repoFrontmatter = properties.frontmatter.repo; + const prop = properties.frontmatter.prop; let image64 = arrayBufferToBase64(imageBin); if (imageFile.name.includes("excalidraw")) { const svg = await convertToHTMLSVG(imageFile, this.plugin.app); @@ -455,13 +455,13 @@ export default class Publisher { imageFile, this.plugin, properties.frontmatter.general, - properties.frontmatter.repo + properties.frontmatter.prop ); if (this.settings.github.dryRun.enable) { const folderName = this.settings.github.dryRun.folderName - .replace("{{repo}}", repoFrontmatter.repo) - .replace("{{branch}}", repoFrontmatter.branch) - .replace("{{owner}}", repoFrontmatter.owner); + .replace("{{repo}}", prop.repo) + .replace("{{branch}}", prop.branch) + .replace("{{owner}}", prop.owner); const dryRunPath = normalizePath(`${folderName}/${path}`); const isAlreadyExist = this.vault.getAbstractFileByPath(dryRunPath); if (isAlreadyExist && isAlreadyExist instanceof TFile) { @@ -484,7 +484,7 @@ export default class Publisher { file: imageFile.name }; } - return await this.upload(image64, path, "", properties.frontmatter.repo); + return await this.upload(image64, path, "", properties.frontmatter.prop); } @@ -493,7 +493,7 @@ export default class Publisher { * @param {string} text contents of the note * @param {string} path new Path in GitHub * @param {string} title name note for message commit - * @param {RepoFrontmatter} repoFrontmatter frontmatter settings + * @param {Properties} prop frontmatter settings * @return {Promise} */ @@ -501,14 +501,14 @@ export default class Publisher { text: string, path: string, title: string = "", - repoFrontmatter: RepoFrontmatter, + prop: Properties, ): Promise { if (this.settings.github.dryRun.enable) { //create a new file in the vault const folderName = this.settings.github.dryRun.folderName - .replace("{{repo}}", repoFrontmatter.repo) - .replace("{{branch}}", repoFrontmatter.branch) - .replace("{{owner}}", repoFrontmatter.owner); + .replace("{{repo}}", prop.repo) + .replace("{{branch}}", prop.branch) + .replace("{{owner}}", prop.owner); const newPath = normalizePath(`${folderName}/${path}`); const isAlreadyExist = this.vault.getAbstractFileByPath(newPath); @@ -536,7 +536,7 @@ export default class Publisher { contentBase64, path, title, - repoFrontmatter + prop ); } catch (e) { notif({ settings: this.settings, e: true }, e); @@ -547,13 +547,13 @@ export default class Publisher { /** * Upload the metadataExtractor json file * @param {MetadataExtractor} metadataExtractor metadataExtractor - * @param {RepoFrontmatter | RepoFrontmatter[]} repoFrontmatter frontmatter settings + * @param {Properties | Properties[]} prop frontmatter settings * @return {Promise} */ async uploadMetadataExtractorFiles( metadataExtractor: MetadataExtractor, - repoFrontmatter: RepoFrontmatter | RepoFrontmatter[] + prop: Properties | Properties[] ): Promise { if (metadataExtractor) { if (this.settings.github.dryRun.enable) return; @@ -564,10 +564,10 @@ export default class Publisher { this.settings.upload.metadataExtractorPath + "/" + file.split("/").pop(); - repoFrontmatter = Array.isArray(repoFrontmatter) - ? repoFrontmatter - : [repoFrontmatter]; - for (const repo of repoFrontmatter) { + prop = Array.isArray(prop) + ? prop + : [prop]; + for (const repo of prop) { await this.uploadText( contents, path, @@ -582,24 +582,24 @@ export default class Publisher { /** * Allow to activate a workflow dispatch github actions - * @param {RepoFrontmatter} repoFrontmatter frontmatter settings + * @param {Properties} prop frontmatter settings * @return {Promise} */ - async workflowGestion(repoFrontmatter: RepoFrontmatter): Promise { + async workflowGestion(prop: Properties): Promise { if (this.settings.github.dryRun.enable) return false; let finished = false; - if (repoFrontmatter.workflowName.length === 0) { + if (prop.workflowName.length === 0) { return false; } const octokit = this.octokit; await octokit.request( "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, - workflow_id: repoFrontmatter.workflowName, - ref: repoFrontmatter.branch, + owner: prop.owner, + repo: prop.repo, + workflow_id: prop.workflowName, + ref: prop.branch, } ); while (!finished) { @@ -607,15 +607,15 @@ export default class Publisher { const workflowGet = await octokit.request( "GET /repos/{owner}/{repo}/actions/runs", { - owner: repoFrontmatter.owner, - repo: repoFrontmatter.repo, + owner: prop.owner, + repo: prop.repo, } ); if (workflowGet.data.workflow_runs.length > 0) { const build = workflowGet.data.workflow_runs.find( (run) => run.name === - repoFrontmatter.workflowName.replace(".yml", "").replace(".yaml", "") + prop.workflowName.replace(".yml", "").replace(".yaml", "") ); if (build && build.status === "completed") { finished = true; @@ -645,9 +645,9 @@ export default class Publisher { file, this.plugin, properties.frontmatter.general, - properties.frontmatter.repo + properties.frontmatter.prop ); - const repoFrontmatter = properties.frontmatter; + const prop = properties.frontmatter; if (this.settings.github.dryRun.enable) { newLinkedFiles.push(file); continue; @@ -661,8 +661,8 @@ export default class Publisher { const response = await this.octokit.request( "GET /repos/{owner}/{repo}/contents/{path}", { - owner: repoFrontmatter.repo.owner, - repo: repoFrontmatter.repo.repo, + owner: prop.prop.owner, + repo: prop.prop.repo, path: imagePath, ref: this.branchName, }); @@ -670,8 +670,8 @@ export default class Publisher { const reply = await this.octokit.request( "GET /repos/{owner}/{repo}/commits", { - owner: repoFrontmatter.repo.owner, - repo: repoFrontmatter.repo.repo, + owner: prop.prop.owner, + repo: prop.prop.repo, path: imagePath, sha: this.branchName, }); diff --git a/src/commands/callback.ts b/src/commands/callback.ts index 899bc736..6821620e 100644 --- a/src/commands/callback.ts +++ b/src/commands/callback.ts @@ -11,7 +11,7 @@ import {MonoRepoProperties,MultiRepoProperties,Repository} from "../interfaces"; import GithubPublisher from "../main"; import {createLink} from "../utils"; import {checkRepositoryValidity, isShared} from "../utils/data_validation_test"; -import { frontmatterFromFile, frontmatterSettingsRepository, getRepoFrontmatter } from "../utils/parse_frontmatter"; +import { frontmatterFromFile, frontmatterSettingsRepository, getProperties } from "../utils/parse_frontmatter"; import {purgeNotesRemote, shareOneNote} from "."; import {shareEditedOnly, uploadAllEditedNotes, uploadAllNotes, uploadNewNotes} from "./plugin_commands"; @@ -38,8 +38,8 @@ export async function createLinkCallback(repo: Repository | null, plugin: Github ) { if (!checking) { const multiRepo: MultiRepoProperties = { - frontmatter: getRepoFrontmatter(plugin, repo, frontmatter, true), - repo, + frontmatter: getProperties(plugin, repo, frontmatter, true), + repository: repo, }; createLink( file, @@ -76,10 +76,10 @@ export async function purgeNotesRemoteCallback(plugin: GithubPublisher, repo: Re hotkeys: [], //@ts-ignore callback: async () => { - const frontmatter = getRepoFrontmatter(plugin, repo, undefined, true); + const frontmatter = getProperties(plugin, repo, undefined, true); const monoRepo: MonoRepoProperties = { frontmatter: Array.isArray(frontmatter) ? frontmatter[0] : frontmatter, - repo, + repository: repo, convert: frontmatterSettingsRepository(plugin, repo) }; const publisher = await plugin.reloadOctokit(repo?.smartKey); diff --git a/src/commands/file_menu.ts b/src/commands/file_menu.ts index 401d1959..2a2493ee 100644 --- a/src/commands/file_menu.ts +++ b/src/commands/file_menu.ts @@ -4,7 +4,7 @@ import { Menu, MenuItem, Platform, TFile, TFolder} from "obsidian"; import {MonoRepoProperties, Repository} from "../interfaces"; import GithubPublisher from "../main"; import {defaultRepo, getRepoSharedKey, isExcludedPath, isInDryRunFolder, isShared, multipleSharedKey} from "../utils/data_validation_test"; -import { frontmatterFromFile, frontmatterSettingsRepository, getRepoFrontmatter } from "../utils/parse_frontmatter"; +import { frontmatterFromFile, frontmatterSettingsRepository, getProperties } from "../utils/parse_frontmatter"; import {shareAllMarkedNotes, shareOneNote} from "."; import {ChooseRepoToRun} from "./suggest_other_repo_commands_modal"; @@ -18,10 +18,10 @@ import {ChooseRepoToRun} from "./suggest_other_repo_commands_modal"; export async function shareFolderRepo(plugin: GithubPublisher, folder: TFolder, branchName: string, repo: Repository | null) { const publisher = await plugin.reloadOctokit(repo?.smartKey); const statusBarItems = plugin.addStatusBarItem(); - const repoFrontmatter = getRepoFrontmatter(plugin, repo, null, true); + const prop = getProperties(plugin, repo, null, true); const monoProperties: MonoRepoProperties = { - frontmatter: Array.isArray(repoFrontmatter) ? repoFrontmatter[0] : repoFrontmatter, - repo, + frontmatter: Array.isArray(prop) ? prop[0] : prop, + repository: repo, convert: frontmatterSettingsRepository(plugin, repo) }; await shareAllMarkedNotes( @@ -109,14 +109,14 @@ export function addMenuFile(plugin: GithubPublisher, file: TFile, branchName: st plugin.settings.plugin.fileMenu) ) return; - const repoFrontmatter = getRepoFrontmatter(plugin, getSharedKey, frontmatter, true); + const prop = getProperties(plugin, getSharedKey, frontmatter, true); menu.addItem((item) => { /** * Create a submenu if multiple repo exists in the settings & platform is desktop */ - if (allKeysFromFile.length > 1 || (repoFrontmatter instanceof Array && repoFrontmatter.length > 1)) { + if (allKeysFromFile.length > 1 || (prop instanceof Array && prop.length > 1)) { if (Platform.isDesktop) { item .setTitle("Github Publisher") @@ -178,8 +178,8 @@ export function subMenuCommandsFile(plugin: GithubPublisher, item: MenuItem, fil const fileName = plugin.getTitleFieldForCommand(file, frontmatter).replace(".md", ""); //@ts-ignore const subMenu = Platform.isDesktop ? item.setSubmenu() as Menu : originalMenu; - let repoFrontmatter = getRepoFrontmatter(plugin, repo, frontmatter, true); - repoFrontmatter = repoFrontmatter instanceof Array ? repoFrontmatter : [repoFrontmatter]; + let prop = getProperties(plugin, repo, frontmatter, true); + prop = prop instanceof Array ? prop : [prop]; /** * default repo */ @@ -228,8 +228,8 @@ export function subMenuCommandsFile(plugin: GithubPublisher, item: MenuItem, fil } }); } - if (repoFrontmatter.length > 1) { - repoFrontmatter.forEach((repoFront) => { + if (prop.length > 1) { + prop.forEach((repoFront) => { subMenu.addItem((item) => { item .setTitle(i18next.t("commands.shareViewFiles.multiple.on", { diff --git a/src/commands/index.ts b/src/commands/index.ts index 692eb821..2ef4a135 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -13,8 +13,8 @@ import { getSettingsOfMetadataExtractor, logs, notif, notifError, publisherNotification} from "../utils"; -import {checkRepositoryValidityWithRepoFrontmatter} from "../utils/data_validation_test"; -import { frontmatterFromFile, getRepoFrontmatter } from "../utils/parse_frontmatter"; +import {checkRepositoryValidityWithProperties} from "../utils/data_validation_test"; +import { frontmatterFromFile, getProperties } from "../utils/parse_frontmatter"; import { ShareStatusBar } from "../utils/status_bar"; @@ -37,15 +37,15 @@ export async function shareAllMarkedNotes( sourceFrontmatter: FrontMatterCache | undefined | null = null, ) { const statusBar = new ShareStatusBar(statusBarItems, sharedFiles.length); - const repoFrontmatter = monoRepo.frontmatter; + const prop = monoRepo.frontmatter; try { const fileError : string[] = []; const listStateUploaded: UploadedFiles[] = []; if (sharedFiles.length > 0) { if (createGithubBranch) { - const isValid = await checkRepositoryValidityWithRepoFrontmatter(PublisherManager, repoFrontmatter, sharedFiles.length); + const isValid = await checkRepositoryValidityWithProperties(PublisherManager, prop, sharedFiles.length); if (!isValid) return false; - await PublisherManager.newBranch(repoFrontmatter); + await PublisherManager.newBranch(prop); } for (const sharedFile of sharedFiles) { try { @@ -88,26 +88,26 @@ export async function shareAllMarkedNotes( if (metadataExtractor) { await PublisherManager.uploadMetadataExtractorFiles( metadataExtractor, - repoFrontmatter + prop ); } } const update = await PublisherManager.updateRepository( - repoFrontmatter + prop ); if (update) { await publisherNotification( PublisherManager, noticeValue, settings, - repoFrontmatter + prop ); if (settings.plugin.displayModalRepoEditing) { const listEdited = createListEdited(listStateUploaded, deleted, fileError); new ListChangedFiles(PublisherManager.plugin.app, listEdited).open(); } } else { - notifError(repoFrontmatter); + notifError(prop); } } } catch (error) { @@ -115,7 +115,7 @@ export async function shareAllMarkedNotes( const errorFrag = document.createDocumentFragment(); errorFrag.createSpan({ cls: ["error", "obsidian-publisher", "icons", "notification"] }).innerHTML = ERROR_ICONS; errorFrag.createSpan({ cls: ["error", "obsidian-publisher", "notification"], text: i18next.t("error.unablePublishMultiNotes") }); - statusBar.error(repoFrontmatter); + statusBar.error(prop); } } @@ -137,7 +137,7 @@ export async function purgeNotesRemote( new Notice( noticeFragment ); - const isValid = await checkRepositoryValidityWithRepoFrontmatter(PublisherManager, monoRepo.frontmatter); + const isValid = await checkRepositoryValidityWithProperties(PublisherManager, monoRepo.frontmatter); if (!isValid) return false; if (!PublisherManager.settings.github.dryRun.enable) await PublisherManager.newBranch(monoRepo.frontmatter); @@ -176,23 +176,23 @@ export async function shareOneNote( let frontmatter = frontmatterFromFile(file, PublisherManager.plugin, null); if (sourceFrontmatter && frontmatter) frontmatter = merge(sourceFrontmatter, frontmatter); try { - const repoFrontmatter = getRepoFrontmatter(plugin, repository, frontmatter); + const prop = getProperties(plugin, repository, frontmatter); let isValid: boolean; - if (repoFrontmatter instanceof Array) { + if (prop instanceof Array) { const isValidArray = []; - for (const repo of repoFrontmatter) { - isValidArray.push(await checkRepositoryValidityWithRepoFrontmatter(PublisherManager, repo)); + for (const repo of prop) { + isValidArray.push(await checkRepositoryValidityWithProperties(PublisherManager, repo)); } isValid = isValidArray.every((v) => v === true); - } else isValid = await checkRepositoryValidityWithRepoFrontmatter(PublisherManager, repoFrontmatter); + } else isValid = await checkRepositoryValidityWithProperties(PublisherManager, prop); const multiRepo: MultiRepoProperties = { - frontmatter: repoFrontmatter, - repo: repository + frontmatter: prop, + repository: repository }; if (!isValid) return false; if (!settings.github.dryRun.enable) - await PublisherManager.newBranch(repoFrontmatter); + await PublisherManager.newBranch(prop); const publishSuccess = await PublisherManager.publish( file, true, @@ -213,19 +213,19 @@ export async function shareOneNote( if (metadataExtractor) { await PublisherManager.uploadMetadataExtractorFiles( metadataExtractor, - repoFrontmatter + prop ); } } const update = await PublisherManager.updateRepository( - repoFrontmatter, settings.github.dryRun.enable + prop, settings.github.dryRun.enable ); if (update) { await publisherNotification( PublisherManager, title, settings, - repoFrontmatter + prop ); await createLink( file, @@ -238,13 +238,13 @@ export async function shareOneNote( } } else { - notifError(repoFrontmatter); + notifError(prop); } } } catch (error) { if (!(error instanceof DOMException)) { logs({settings, e: true}, error); - notifError(getRepoFrontmatter(plugin, repository, frontmatter, true)); + notifError(getProperties(plugin, repository, frontmatter, true)); } } } @@ -263,7 +263,7 @@ export async function shareNewNote( ): Promise { const plugin = PublisherManager.plugin; new Notice(i18next.t("informations.scanningRepo") ); - const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(monoRepo.repo, monoRepo.convert); + const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(monoRepo.repository, monoRepo.convert); // Get all file in the repo before the creation of the branch const githubSharedNotes = await PublisherManager.getAllFileFromRepo( monoRepo.frontmatter.branch, // we need to take the master branch because the branch to create doesn't exist yet @@ -280,7 +280,7 @@ export async function shareNewNote( ); const statusBarElement = plugin.addStatusBarItem(); - const isValid = await checkRepositoryValidityWithRepoFrontmatter(PublisherManager, monoRepo.frontmatter, newlySharedNotes.length); + const isValid = await checkRepositoryValidityWithProperties(PublisherManager, monoRepo.frontmatter, newlySharedNotes.length); if (!isValid) return false; await PublisherManager.newBranch(monoRepo.frontmatter); await shareAllMarkedNotes( @@ -309,7 +309,7 @@ export async function shareAllEditedNotes( ) { const plugin = PublisherManager.plugin; new Notice(i18next.t("informations.scanningRepo") ); - const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(monoRepo.repo, monoRepo.convert); + const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(monoRepo.repository, monoRepo.convert); const githubSharedNotes = await PublisherManager.getAllFileFromRepo( monoRepo.frontmatter.branch, monoRepo.frontmatter @@ -330,7 +330,7 @@ export async function shareAllEditedNotes( ); const statusBarElement = plugin.addStatusBarItem(); - const isValid = await checkRepositoryValidityWithRepoFrontmatter(PublisherManager, monoRepo.frontmatter, newlySharedNotes.length); + const isValid = await checkRepositoryValidityWithProperties(PublisherManager, monoRepo.frontmatter, newlySharedNotes.length); if (!isValid) return false; await PublisherManager.newBranch(monoRepo.frontmatter); await shareAllMarkedNotes( @@ -357,13 +357,13 @@ export async function shareOnlyEdited( branchName: string, monoRepo: MonoRepoProperties, ) { - const shortRepo = monoRepo.repo; - const repoFrontmatter = monoRepo.frontmatter; + const shortRepo = monoRepo.repository; + const prop = monoRepo.frontmatter; new Notice(i18next.t("informations.scanningRepo") ); const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(shortRepo, monoRepo.convert); const githubSharedNotes = await PublisherManager.getAllFileFromRepo( - repoFrontmatter.branch, - repoFrontmatter + prop.branch, + prop ); const newSharedFiles: TFile[] = []; const newlySharedNotes = await PublisherManager.getEditedFiles( @@ -376,9 +376,9 @@ export async function shareOnlyEdited( (i18next.t("informations.foundNoteToSend", {nbNotes: newlySharedNotes.length})) ); const statusBarElement = PublisherManager.plugin.addStatusBarItem(); - const isValid = await checkRepositoryValidityWithRepoFrontmatter(PublisherManager, repoFrontmatter, newlySharedNotes.length); + const isValid = await checkRepositoryValidityWithProperties(PublisherManager, prop, newlySharedNotes.length); if (!isValid) return false; - await PublisherManager.newBranch(repoFrontmatter); + await PublisherManager.newBranch(prop); await shareAllMarkedNotes( PublisherManager, statusBarElement, diff --git a/src/commands/plugin_commands.ts b/src/commands/plugin_commands.ts index ef9af857..8407832c 100644 --- a/src/commands/plugin_commands.ts +++ b/src/commands/plugin_commands.ts @@ -10,7 +10,7 @@ import {MonoRepoProperties, MultiRepoProperties, Repository} from "../interfaces import GithubPublisher from "../main"; import {createLink} from "../utils"; import {checkRepositoryValidity, isShared} from "../utils/data_validation_test"; -import { frontmatterFromFile, frontmatterSettingsRepository, getRepoFrontmatter } from "../utils/parse_frontmatter"; +import { frontmatterFromFile, frontmatterSettingsRepository, getProperties } from "../utils/parse_frontmatter"; import { purgeNotesRemote, shareAllEditedNotes, @@ -34,8 +34,8 @@ export async function createLinkOnActiveFile(repo: Repository | null, plugin: Gi file && frontmatter && isShared(frontmatter, plugin.settings, file, repo) ) { const multiRepo: MultiRepoProperties = { - frontmatter: getRepoFrontmatter(plugin, repo, frontmatter), - repo + frontmatter: getProperties(plugin, repo, frontmatter), + repository: repo }; await createLink( file, @@ -80,11 +80,11 @@ export async function shareActiveFile(plugin: GithubPublisher, repo: Repository * @return {Promise} */ export async function deleteCommands(plugin : GithubPublisher, repo: Repository | null, branchName: string): Promise { - const repoFrontmatter = getRepoFrontmatter(plugin, repo, null, true); + const prop = getProperties(plugin, repo, null, true); const publisher = await plugin.reloadOctokit(repo?.smartKey); const mono: MonoRepoProperties = { - frontmatter: Array.isArray(repoFrontmatter) ? repoFrontmatter[0] : repoFrontmatter, - repo, + frontmatter: Array.isArray(prop) ? prop[0] : prop, + repository: repo, convert: frontmatterSettingsRepository(plugin, repo) }; await purgeNotesRemote( @@ -107,10 +107,10 @@ export async function uploadAllNotes(plugin: GithubPublisher, repo: Repository | const statusBarItems = plugin.addStatusBarItem(); const publisher = await plugin.reloadOctokit(repo?.smartKey); const sharedFiles = publisher.getSharedFiles(repo); - const repoFrontmatter = getRepoFrontmatter(plugin, repo, undefined, true); + const prop = getProperties(plugin, repo, undefined, true); const mono: MonoRepoProperties = { - frontmatter: Array.isArray(repoFrontmatter) ? repoFrontmatter[0] : repoFrontmatter, - repo, + frontmatter: Array.isArray(prop) ? prop[0] : prop, + repository: repo, convert: frontmatterSettingsRepository( plugin, repo @@ -137,13 +137,13 @@ export async function uploadAllNotes(plugin: GithubPublisher, repo: Repository | export async function uploadNewNotes(plugin: GithubPublisher, branchName: string, repo: Repository|null): Promise { const publisher = await plugin.reloadOctokit(repo?.smartKey); - const repoFrontmatter = getRepoFrontmatter(plugin, repo, null, true); + const prop = getProperties(plugin, repo, null, true); await shareNewNote( publisher, branchName, { - frontmatter: Array.isArray(repoFrontmatter) ? repoFrontmatter[0] : repoFrontmatter, - repo, + frontmatter: Array.isArray(prop) ? prop[0] : prop, + repository: repo, convert: frontmatterSettingsRepository(plugin, repo) }, ); @@ -179,14 +179,14 @@ export async function repositoryValidityActiveFile(plugin:GithubPublisher, repo: */ export async function uploadAllEditedNotes(plugin: GithubPublisher ,branchName: string, repo: Repository|null=null): Promise { const publisher = await plugin.reloadOctokit(repo?.smartKey); - const repoFrontmatter = getRepoFrontmatter(plugin, repo, null, true); + const prop = getProperties(plugin, repo, null, true); await shareAllEditedNotes( publisher, branchName, { - frontmatter: Array.isArray(repoFrontmatter) ? repoFrontmatter[0] : repoFrontmatter, - repo, + frontmatter: Array.isArray(prop) ? prop[0] : prop, + repository: repo, convert: frontmatterSettingsRepository(plugin, repo) }, ); @@ -202,13 +202,13 @@ export async function uploadAllEditedNotes(plugin: GithubPublisher ,branchName: */ export async function shareEditedOnly(branchName: string, repo: Repository|null, plugin: GithubPublisher): Promise { const publisher = await plugin.reloadOctokit(repo?.smartKey); - const repoFrontmatter = getRepoFrontmatter(plugin, repo, null, true); + const prop = getProperties(plugin, repo, null, true); await shareOnlyEdited( publisher, branchName, { - frontmatter: Array.isArray(repoFrontmatter) ? repoFrontmatter[0] : repoFrontmatter, - repo, + frontmatter: Array.isArray(prop) ? prop[0] : prop, + repository: repo, convert: frontmatterSettingsRepository(plugin, repo) }, ); diff --git a/src/conversion/file_path.ts b/src/conversion/file_path.ts index f66fc255..f7e99f5e 100644 --- a/src/conversion/file_path.ts +++ b/src/conversion/file_path.ts @@ -15,14 +15,14 @@ import { GitHubPublisherSettings, LinkedNotes, MultiProperties, - RepoFrontmatter, + Properties, Repository, } from "../interfaces"; import { logs, } from "../utils"; import {checkIfRepoIsInAnother, isInternalShared, isShared} from "../utils/data_validation_test"; -import { frontmatterFromFile, frontmatterSettingsRepository, getCategory, getFrontmatterSettings, getRepoFrontmatter } from "../utils/parse_frontmatter"; +import { frontmatterFromFile, frontmatterSettingsRepository, getCategory, getFrontmatterSettings, getProperties } from "../utils/parse_frontmatter"; import { createRegexFromText } from "./find_and_replace_text"; @@ -76,10 +76,10 @@ export async function createRelativePath( ): Promise { const settings = properties.plugin.settings; const shortRepo = properties.repository; - const sourcePath = getReceiptFolder(sourceFile, shortRepo, properties.plugin, properties.frontmatter.repo); + const sourcePath = getReceiptFolder(sourceFile, shortRepo, properties.plugin, properties.frontmatter.prop); const frontmatterTarget = frontmatterFromFile(targetFile.linked, properties.plugin, properties.repository); - const targetRepo = getRepoFrontmatter(properties.plugin, shortRepo, frontmatterTarget); - const isFromAnotherRepo = checkIfRepoIsInAnother(properties.frontmatter.repo, targetRepo); + const targetRepo = getProperties(properties.plugin, shortRepo, frontmatterTarget); + const isFromAnotherRepo = checkIfRepoIsInAnother(properties.frontmatter.prop, targetRepo); const shared = isInternalShared( frontmatterTarget, properties, @@ -200,12 +200,12 @@ function createObsidianPath( settings: GitHubPublisherSettings, vault: Vault, fileName: string, - repoFrontmatter?: RepoFrontmatter, + prop?: Properties, ): string { fileName = folderNoteIndexOBS(file, vault, settings, fileName); - const defaultFolder = repoFrontmatter?.path?.defaultName && repoFrontmatter.path.defaultName.length > 0 ? - repoFrontmatter.path.defaultName : settings.upload.defaultName.length > 0 ? + const defaultFolder = prop?.path?.defaultName && prop.path.defaultName.length > 0 ? + prop.path.defaultName : settings.upload.defaultName.length > 0 ? settings.upload.defaultName : ""; const path = defaultFolder + fileName; //remove last word from path splitted with / @@ -229,9 +229,9 @@ function folderNoteIndexYAML( fileName: string, frontmatter: FrontMatterCache | undefined | null, settings: GitHubPublisherSettings, - repoFrontmatter?: RepoFrontmatter, + prop?: Properties, ): string { - const category = repoFrontmatter?.path?.category?.value ?? getCategory(frontmatter, settings, repoFrontmatter?.path); + const category = prop?.path?.category?.value ?? getCategory(frontmatter, settings, prop?.path); const catSplit = category.split("/"); const parentCatFolder = category.endsWith("/") ? catSplit.at(-2) as string : catSplit.at(-1) as string; @@ -256,13 +256,13 @@ function createFrontmatterPath( settings: GitHubPublisherSettings, frontmatter: FrontMatterCache | null | undefined, fileName: string, - repoFrontmatter?: RepoFrontmatter, + prop?: Properties, ): string { const uploadSettings = settings.upload; - const folderCategory = repoFrontmatter?.path?.category?.value ?? getCategory(frontmatter, settings, repoFrontmatter?.path); - const path = repoFrontmatter?.path; - const folderNote = folderNoteIndexYAML(fileName, frontmatter, settings, repoFrontmatter); + const folderCategory = prop?.path?.category?.value ?? getCategory(frontmatter, settings, prop?.path); + const path = prop?.path; + const folderNote = folderNoteIndexYAML(fileName, frontmatter, settings, prop); const root = path?.rootFolder && path.rootFolder.length > 0 ? path.rootFolder : uploadSettings.rootFolder.length > 0 ? uploadSettings.rootFolder : undefined; const folderRoot = root && !folderCategory.includes(root) ? `${root}/` : ""; if (folderCategory.trim().length === 0) return folderNote; @@ -369,16 +369,16 @@ export function getReceiptFolder( file: TFile, otherRepo: Repository | null, plugin: GithubPublisher, - repoFrontmatter?: RepoFrontmatter | RepoFrontmatter[], + prop?: Properties | Properties[], ): string { const { vault} = plugin.app; const settings = plugin.settings; if (file.extension === "md") { const frontmatter = frontmatterFromFile(file, plugin, otherRepo); - if (!repoFrontmatter) repoFrontmatter = getRepoFrontmatter(plugin, otherRepo, frontmatter); - repoFrontmatter = repoFrontmatter instanceof Array ? repoFrontmatter : [repoFrontmatter]; - let targetRepo = repoFrontmatter.find((repo) => repo.path?.smartkey === otherRepo?.smartKey || "default"); - if (!targetRepo) targetRepo = repoFrontmatter[0]; + if (!prop) prop = getProperties(plugin, otherRepo, frontmatter); + prop = prop instanceof Array ? prop : [prop]; + let targetRepo = prop.find((repo) => repo.path?.smartkey === otherRepo?.smartKey || "default"); + if (!targetRepo) targetRepo = prop[0]; const fileName = getTitleField(frontmatter, file, settings); const editedFileName = regexOnFileName(fileName, settings); if ( @@ -417,7 +417,7 @@ export function getImagePath( file: TFile, plugin: GithubPublisher, sourceFrontmatter: FrontmatterConvert | null, - repository: RepoFrontmatter | RepoFrontmatter[], + repository: Properties | Properties[], ): string { const settings = plugin.settings; const overridePath = repository instanceof Array ? repository[0] : repository; @@ -439,7 +439,7 @@ export function getImagePath( function createImagePath(file: TFile, settings: GitHubPublisherSettings, sourceFrontmatter: FrontmatterConvert | null, - overridePath?: RepoFrontmatter, + overridePath?: Properties, ): { path: string, name: string } { let fileName = file.name; let filePath = file.path; diff --git a/src/interfaces/index.ts b/src/interfaces/index.ts index f92bfc99..cbe500a0 100644 --- a/src/interfaces/index.ts +++ b/src/interfaces/index.ts @@ -24,8 +24,8 @@ export type { MultiRepoProperties, OverrideAttachments, Path, + Properties, RegexReplace, - Properties as RepoFrontmatter, Repository, SetRepositoryFrontmatter, TextCleaner, diff --git a/src/interfaces/main.ts b/src/interfaces/main.ts index 372e8f1a..3fe0716b 100644 --- a/src/interfaces/main.ts +++ b/src/interfaces/main.ts @@ -135,15 +135,15 @@ export interface LinkedNotes { /** * @interface ConvertedLink - * A type for the shared files in the vault that includes the repoFrontmatter, but also the real path in Obsidian and the converted path in GitHub + * A type for the shared files in the vault that includes the prop, but also the real path in Obsidian and the converted path in GitHub */ export interface ConvertedLink { /** Path in GitHub */ converted: string; /** Path in Obsidian */ real: string; - /** The repoFrontmatter */ - repoFrontmatter?: Properties | Properties[]; + /** The prop */ + prop?: Properties | Properties[]; } /** @@ -210,7 +210,7 @@ export interface Path { }; } -/** A sort of extension of RepoFrontmatter, but include settings like bake embed, dataview or unshared links conversion */ +/** A sort of extension of Properties, but include settings like bake embed, dataview or unshared links conversion */ export interface PropertiesConversion { /** Convert links */ links: boolean; @@ -239,7 +239,7 @@ export interface PropertiesConversion { } /** A very important interface that handle a repository from the frontmatter and a lot of usefull settings that override the default plugin behavior, including {@link Path}. - * RepoFrontmatter also handle {@link Repository} settings. + * Properties also handle {@link Repository} settings. */ export interface Properties { /** Branch name */ diff --git a/src/interfaces/properties.ts b/src/interfaces/properties.ts index ebc335c1..f3cb2607 100644 --- a/src/interfaces/properties.ts +++ b/src/interfaces/properties.ts @@ -12,7 +12,7 @@ export interface MultiProperties { plugin: GithubPublisher; frontmatter: { general: PropertiesConversion; - repo: Properties | Properties[]; + prop: Properties | Properties[]; }, repository: Repository | null; filepath: string; @@ -26,7 +26,7 @@ export interface MonoProperties { plugin: GithubPublisher; frontmatter: { general: PropertiesConversion; - repo: Properties; + prop: Properties; source: FrontMatterCache | null | undefined; }, repository: Repository | null; @@ -36,19 +36,19 @@ export interface MonoProperties { /** * @interface MonoRepoProperties - * A resume of {@link MonoProperties} and {@link MultiProperties} for a single repoFrontmatter + * A resume of {@link MonoProperties} and {@link MultiProperties} for a single properties */ export interface MonoRepoProperties { frontmatter: Properties; - repo: Repository | null; + repository: Repository | null; convert: PropertiesConversion; } /** * @interface MultiRepoProperties - * A resume of {@link MonoProperties} and {@link MultiProperties} for multiple repoFrontmatter + * A resume of {@link MonoProperties} and {@link MultiProperties} for multiple properties */ export interface MultiRepoProperties { frontmatter: Properties[] | Properties; - repo: Repository | null; + repository: Repository | null; } \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index fa820dc1..d3b4dd76 100644 --- a/src/main.ts +++ b/src/main.ts @@ -157,21 +157,17 @@ export default class GithubPublisher extends Plugin { } /** - * Create a new instance of Octokit to load a new instance of GithubBranch + * Create a new instance of Octokit to load a new instance of GithubBranch + * @param {string} repo - The repository to load the Octokit for */ async reloadOctokit(repo?: string) { - let octokit: Octokit; const apiSettings = this.settings.github.api; const token = await this.loadToken(repo); - if (apiSettings.tiersForApi === GithubTiersVersion.entreprise && apiSettings.hostname.length > 0) { - octokit = new Octokit( - { - baseUrl: `${apiSettings.hostname}/api/v3`, - auth: token, - }); - } else { - octokit = new Octokit({ auth: token }); - } + const octokit = apiSettings.tiersForApi === GithubTiersVersion.entreprise && apiSettings.hostname.length > 0 ? new Octokit( + { + baseUrl: `${apiSettings.hostname}/api/v3`, + auth: token, + }) : new Octokit({ auth: token }); return new GithubBranch( octokit, this, @@ -214,9 +210,12 @@ export default class GithubPublisher extends Plugin { } for (const repository of this.settings.github.otherRepo) { - const repoOctokit = await this.reloadOctokit(repository.smartKey); - repository.verifiedRepo = await checkRepositoryValidity(repoOctokit, repository, null, false); - repository.rateLimit = await verifyRateLimitAPI(repoOctokit.octokit, this.settings); + if (!repository.verifiedRepo && (await this.loadToken(repository.smartKey)) !== "") + { + const repoOctokit = await this.reloadOctokit(repository.smartKey); + repository.verifiedRepo = await checkRepositoryValidity(repoOctokit, repository, null, false); + repository.rateLimit = await verifyRateLimitAPI(repoOctokit.octokit, this.settings); + } if (repository.set) { //take the file and update the frontmatter @@ -282,12 +281,17 @@ export default class GithubPublisher extends Plugin { } /** - * Called when the plugin is disabled - */ + * Called when the plugin is disabled + */ onunload() { console.info("[Github Publisher] unloaded"); } + /** + * Load the settings of the plugin + * Use merge methods to merge the default settings with the loaded settings as I use a lot of nested objects + * If the deep merge fails, I use the default method + */ async loadSettings() { const loadedData = await this.loadData(); try { @@ -299,8 +303,8 @@ export default class GithubPublisher extends Plugin { } /** - * Save the settings of the plugin - */ + * Save the settings of the plugin + */ async saveSettings() { await this.saveData(this.settings); } diff --git a/src/utils/data_validation_test.ts b/src/utils/data_validation_test.ts index c6ae4a71..eaca1db0 100644 --- a/src/utils/data_validation_test.ts +++ b/src/utils/data_validation_test.ts @@ -6,9 +6,9 @@ import GithubPublisher from "src/main"; import merge from "ts-deepmerge"; import {GithubBranch} from "../GitHub/branch"; -import {FIND_REGEX, FrontmatterConvert, GitHubPublisherSettings, GithubTiersVersion, MultiProperties, RepoFrontmatter, Repository} from "../interfaces"; +import {FIND_REGEX, FrontmatterConvert, GitHubPublisherSettings, GithubTiersVersion, MultiProperties, Properties, Repository} from "../interfaces"; import { notif} from "."; -import { frontmatterFromFile, getLinkedFrontmatter, getRepoFrontmatter } from "./parse_frontmatter"; +import { frontmatterFromFile, getLinkedFrontmatter, getProperties } from "./parse_frontmatter"; /** * - Check if the file is a valid file to publish @@ -129,7 +129,6 @@ export function isExcludedPath(settings: GitHubPublisherSettings, file: TFile | * @param {FrontMatterCache | undefined} frontmatter - The frontmatter of the file. * @param {GitHubPublisherSettings} settings - The GitHub Publisher settings. * @param {TFile | null} file - The file to get the shared keys from. - * @param {App} app - The Obsidian app instance. * @returns {string[]} - An array of shared keys found in the file. */ export function multipleSharedKey(frontmatter: FrontMatterCache | undefined | null, file: TFile | null, plugin: GithubPublisher): string[] { @@ -203,24 +202,24 @@ export function isAttachment(filename: string, attachmentExtern?: string[]): Reg /** * Check if a target Repository === source Repository - * @param {RepoFrontmatter | RepoFrontmatter[]} source - * @param {RepoFrontmatter | RepoFrontmatter[]} target + * @param {Properties | Properties[]} source + * @param {Properties | Properties[]} target * @return {boolean} if they are the same */ export function checkIfRepoIsInAnother( - source: RepoFrontmatter | RepoFrontmatter[], - target: RepoFrontmatter | RepoFrontmatter[] + source: Properties | Properties[], + target: Properties | Properties[] ): boolean { source = source instanceof Array ? source : [source]; target = target instanceof Array ? target : [target]; /** - * A function to compare two repoFrontmatter - * @param {RepoFrontmatter} source - * @param {RepoFrontmatter} target + * A function to compare two prop + * @param {Properties} source + * @param {Properties} target * @return {boolean} */ - const isSame = (source: RepoFrontmatter, target: RepoFrontmatter) => { + const isSame = (source: Properties, target: Properties) => { return ( source.owner === target.owner && source.repo === target.repo && @@ -249,15 +248,15 @@ export function checkIfRepoIsInAnother( /** * Verify if the Repository configuration is not empty * Permit to send a special notice for each empty configuration - * @param {RepoFrontmatter | RepoFrontmatter[]} repoFrontmatter the repoFrontmatter to check + * @param {Properties | Properties[]} prop the prop to check * @param {GithubPublisher} plugin the plugin instance * @param silent * @return {Promise} */ -export async function checkEmptyConfiguration(repoFrontmatter: RepoFrontmatter | RepoFrontmatter[], plugin: GithubPublisher, silent= false): Promise { - repoFrontmatter = Array.isArray(repoFrontmatter) - ? repoFrontmatter - : [repoFrontmatter]; +export async function checkEmptyConfiguration(prop: Properties | Properties[], plugin: GithubPublisher, silent= false): Promise { + prop = Array.isArray(prop) + ? prop + : [prop]; const isEmpty: boolean[] = []; const token = await plugin.loadToken(); if (token.length === 0) { @@ -266,7 +265,7 @@ export async function checkEmptyConfiguration(repoFrontmatter: RepoFrontmatter | if (!silent) new Notice(i18next.t("error.isEmpty", {what: whatIsEmpty})); } else { - for (const repo of repoFrontmatter) { + for (const repo of prop) { if (repo.repo.length === 0) { isEmpty.push(true); const whatIsEmpty = i18next.t("common.repository") ; @@ -322,10 +321,10 @@ export async function checkRepositoryValidity( const settings = PublisherManager.settings; try { const frontmatter = frontmatterFromFile(file, PublisherManager.plugin, repository); - const repoFrontmatter = getRepoFrontmatter(PublisherManager.plugin, repository, frontmatter); - const isNotEmpty = await checkEmptyConfiguration(repoFrontmatter, PublisherManager.plugin, silent); + const prop = getProperties(PublisherManager.plugin, repository, frontmatter); + const isNotEmpty = await checkEmptyConfiguration(prop, PublisherManager.plugin, silent); if (isNotEmpty) { - await PublisherManager.checkRepository(repoFrontmatter, silent); + await PublisherManager.checkRepository(prop, silent); return true; } } @@ -339,25 +338,25 @@ export async function checkRepositoryValidity( /** * Check the validity of the repository settings, from the frontmatter of the file or from the settings of the plugin * @param {GithubBranch} PublisherManager - * @param {RepoFrontmatter} repoFrontmatter + * @param {Properties} prop * @param {number} numberOfFile the number of file to publish * @return {Promise} */ -export async function checkRepositoryValidityWithRepoFrontmatter( +export async function checkRepositoryValidityWithProperties( PublisherManager: GithubBranch, - repoFrontmatter: RepoFrontmatter, + prop: Properties, numberOfFile: number=1 ): Promise { const settings = PublisherManager.settings; if (settings.github.dryRun.enable) return true; try { - const verified = repoFrontmatter.verifiedRepo; - const rateLimit = repoFrontmatter.rateLimit; + const verified = prop.verifiedRepo; + const rateLimit = prop.rateLimit; if (verified && rateLimit) return true; - const isNotEmpty = await checkEmptyConfiguration(repoFrontmatter, PublisherManager.plugin); + const isNotEmpty = await checkEmptyConfiguration(prop, PublisherManager.plugin); if (isNotEmpty) { - await PublisherManager.checkRepository(repoFrontmatter, true); - if (repoFrontmatter?.rateLimit === 0 || numberOfFile > 20) { + await PublisherManager.checkRepository(prop, true); + if (prop?.rateLimit === 0 || numberOfFile > 20) { return await verifyRateLimitAPI(PublisherManager.octokit, settings, false, numberOfFile) > 0; } return true; diff --git a/src/utils/index.ts b/src/utils/index.ts index 461b3320..09f049b6 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -13,7 +13,7 @@ import { ListEditedFiles, MetadataExtractor, MultiRepoProperties, - RepoFrontmatter, TOKEN_PATH, + Properties, TOKEN_PATH, UploadedFiles} from "../interfaces"; import { ERROR_ICONS, HOURGLASS_ICON, SUCCESS_ICON } from "./icons"; import { frontmatterFromFile } from "./parse_frontmatter"; @@ -48,7 +48,15 @@ export function notif(args: LogsParameters, ...messages: unknown[]) { console.log(prefix, ...messages); } -export function noticeMobile(cls:"error"|"load"|"success"|"wait", icon: string, message: string) { +/** + * Notify the user with a message in the console and a message in the notification + * Only for mobile + * @param cls {"error"|"load"|"success"|"wait"} To adjust css style in function of the type of message + * @param icon {string} The icon to display + * @param message {string} The message to display + * @returns {Notice | undefined} + */ +export function noticeMobile(cls:"error"|"load"|"success"|"wait", icon: string, message: string): Notice | undefined { if (!Platform.isMobile) { return; } @@ -58,6 +66,11 @@ export function noticeMobile(cls:"error"|"load"|"success"|"wait", icon: string, 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} + */ function callFunction(type?: boolean):string { const index = type ? 4 : 3; let callFunction = new Error().stack?.split("\n")[index].trim(); @@ -74,6 +87,8 @@ function callFunction(type?: boolean):string { * Will make appear ALL the logs in the console * Not just the logs for normal process * For advanced users only + * @param args {LogsParameters} the settings and the error type + * @param messages {unknown[]} the message to display */ export function logs(args: LogsParameters, ...messages: unknown[]) { const settings = args.settings as GitHubPublisherSettings; @@ -87,7 +102,12 @@ export function logs(args: LogsParameters, ...messages: unknown[]) { } } -export function monkeyPatchConsole(plugin: GithubPublisher) { +/** + * Monkey patch the console to log all the messages in a file in the plugin folder + * @param plugin {GithubPublisher} the plugin instance + * @returns {void} + */ +export function monkeyPatchConsole(plugin: GithubPublisher): void { const stack = new Error().stack?.split("\n")?.[3]; if (!stack?.includes("obsidian-mkdocs-publisher") || !plugin.settings.plugin.dev) { return; @@ -196,7 +216,7 @@ export async function getSettingsOfMetadataExtractor( const path = `${app.vault.configDir}/plugins/metadata-extractor`; // @ts-ignore const plugin = app.plugins.plugins["metadata-extractor"]; - if (plugin && plugin.settings) { + if (plugin?.settings) { if (plugin.settings["allExceptMdFile"].length > 0) { //get file from plugins folder in .obsidian folder metadataExtractor.allExceptMdFile = @@ -241,7 +261,7 @@ export async function createLink( multiRepo: MultiRepoProperties, plugin: GithubPublisher, ): Promise { - const otherRepo = multiRepo.repo; + const otherRepo = multiRepo.repository; const settings = plugin.settings; const repo = multiRepo.frontmatter; const copyLink = otherRepo ? otherRepo.copyLink : settings.plugin.copyLink; @@ -314,17 +334,17 @@ export async function createLink( * @param {Publisher} PublisherManager * @param {TFile | string} file * @param {GitHubPublisherSettings} settings - * @param {RepoFrontmatter | RepoFrontmatter[]} repo + * @param {Properties | Properties[]} prop */ export async function publisherNotification( PublisherManager: Publisher, file: TFile | string | undefined, settings: GitHubPublisherSettings, - repo: RepoFrontmatter | RepoFrontmatter[] + prop: Properties | Properties[] ) { - repo = Array.isArray(repo) ? repo : [repo]; - for (const repository of repo) { + prop = Array.isArray(prop) ? prop : [prop]; + for (const repository of prop) { await publisherNotificationOneRepo( PublisherManager, file, @@ -334,8 +354,12 @@ export async function publisherNotification( } } -export function notifError(repoFrontmatter: RepoFrontmatter | RepoFrontmatter[]) { - const repo = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; +/** + * Notify the user with a message in the console and a message in the notification + * @param properties + */ +export function notifError(properties: Properties | Properties[]) { + const repo = Array.isArray(properties) ? properties : [properties]; for (const repository of repo) { const notif = document.createDocumentFragment(); notif.createSpan({ cls: ["error", "obsidian-publisher", "icons", "notification"] }).innerHTML = ERROR_ICONS; @@ -349,7 +373,7 @@ export function notifError(repoFrontmatter: RepoFrontmatter | RepoFrontmatter[]) * @param {Publisher} PublisherManager * @param {TFile | string} file * @param {GitHubPublisherSettings} settings - * @param {RepoFrontmatter} repo + * @param {Properties} prop * @return {Promise} */ @@ -357,14 +381,14 @@ async function publisherNotificationOneRepo( PublisherManager: Publisher, file: TFile | string | undefined, settings: GitHubPublisherSettings, - repo: RepoFrontmatter + prop: Properties ): Promise { const noticeValue = file instanceof TFile ? `"${file.basename}"` : file; const docSuccess = document.createDocumentFragment(); const successMsg = file instanceof String ? - i18next.t("informations.successfulPublish", { nbNotes: noticeValue, repo }) - : i18next.t("informations.successPublishOneNote", { file: noticeValue, repo }); + i18next.t("informations.successfulPublish", { nbNotes: noticeValue, repo: prop }) + : i18next.t("informations.successPublishOneNote", { file: noticeValue, repo: prop }); docSuccess.createEl("span", { text: successMsg, cls: ["obsidian-publisher", "success", "icons"] }).innerHTML = SUCCESS_ICON; docSuccess.createEl("span", { cls: ["obsidian-publisher", "success", "notification"] }).innerHTML = successMsg; if (settings.github.workflow.name.length === 0) { @@ -372,11 +396,11 @@ async function publisherNotificationOneRepo( return; } const workflowSuccess = document.createDocumentFragment(); - workflowSuccess.createEl("span", { text: i18next.t("informations.successfulPublish", { nbNotes: noticeValue, repo }), cls: ["obsidian-publisher", "wait", "icons"] }).innerHTML = HOURGLASS_ICON; - const msg = `${i18next.t("informations.sendMessage", {nbNotes: noticeValue, repo})}.
${i18next.t("informations.waitingWorkflow")}`; + workflowSuccess.createEl("span", { text: i18next.t("informations.successfulPublish", { nbNotes: noticeValue, repo: prop }), cls: ["obsidian-publisher", "wait", "icons"] }).innerHTML = HOURGLASS_ICON; + const msg = `${i18next.t("informations.sendMessage", {nbNotes: noticeValue, repo: prop})}.
${i18next.t("informations.waitingWorkflow")}`; workflowSuccess.createEl("span", { cls: ["obsidian-publisher", "wait", "notification"] }).innerHTML = msg; new Notice(workflowSuccess); - const successWorkflow = await PublisherManager.workflowGestion(repo); + const successWorkflow = await PublisherManager.workflowGestion(prop); if (successWorkflow) { new Notice(docSuccess, 0); } diff --git a/src/utils/parse_frontmatter.ts b/src/utils/parse_frontmatter.ts index 49d8d6ad..2d019e09 100644 --- a/src/utils/parse_frontmatter.ts +++ b/src/utils/parse_frontmatter.ts @@ -7,7 +7,7 @@ import { FrontMatterCache, normalizePath, TFile } from "obsidian"; import GithubPublisher from "src/main"; import merge from "ts-deepmerge"; -import { FolderSettings, FrontmatterConvert, GitHubPublisherSettings, Path, RepoFrontmatter, Repository } from "../interfaces"; +import { FolderSettings, FrontmatterConvert, GitHubPublisherSettings, Path, Properties, Repository } from "../interfaces"; export function frontmatterSettingsRepository(plugin: GithubPublisher, repo: Repository | null) { const defaultConvert = getFrontmatterSettings(null, plugin.settings, repo); @@ -19,10 +19,10 @@ export function frontmatterSettingsRepository(plugin: GithubPublisher, repo: Rep ); } -export function getDefaultRepoFrontmatter(repository: Repository | null, plugin: GithubPublisher) { - const defaultSettings = getRepoFrontmatter(plugin, repository); +export function getDefaultProperties(repository: Repository | null, plugin: GithubPublisher) { + const defaultSettings = getProperties(plugin, repository); if (!repository?.set || (repository && !plugin.repositoryFrontmatter[repository.smartKey])) return defaultSettings; - return getRepoFrontmatter(plugin, repository, plugin.repositoryFrontmatter[repository.smartKey]); + return getProperties(plugin, repository, plugin.repositoryFrontmatter[repository.smartKey]); } @@ -99,14 +99,14 @@ function booleanRemoveEmbed(removeEmbed: unknown) { * @param {Repository | null} repository - The repository information. * @param {FrontMatterCache | null} frontmatter - The frontmatter cache. * @param {boolean} [checkSet] - Whether to check the set file for frontmatter (preventing multiple reading of the same file) - * @returns {RepoFrontmatter[] | RepoFrontmatter} - The repository frontmatter. + * @returns {Properties[] | Properties} - The repository frontmatter. */ -export function getRepoFrontmatter( +export function getProperties( plugin: GithubPublisher, repository: Repository | null, frontmatter?: FrontMatterCache | null, checkSet?: boolean -): RepoFrontmatter[] | RepoFrontmatter { +): Properties[] | Properties { const settings = plugin.settings; let github = repository ?? settings.github; if (checkSet && repository && plugin.repositoryFrontmatter[repository.smartKey]) { @@ -122,7 +122,7 @@ export function getRepoFrontmatter( }); github = shortRepo ?? github; } - let repoFrontmatter: RepoFrontmatter = { + let Properties: Properties = { branch: github.branch, repo: github.repo, owner: github.user, @@ -138,46 +138,46 @@ export function getRepoFrontmatter( } }; if (settings.upload.behavior === FolderSettings.fixed) { - repoFrontmatter.autoclean = false; + Properties.autoclean = false; } if (!frontmatter || (frontmatter.multipleRepo === undefined && frontmatter.repo === undefined && frontmatter.shortRepo === undefined)) { - return parsePath(plugin, repository, repoFrontmatter, frontmatter); + return parsePath(plugin, repository, Properties, frontmatter); } let isFrontmatterAutoClean = null; if (frontmatter.multipleRepo) { - const multipleRepo = parseMultipleRepo(frontmatter, repoFrontmatter); + const multipleRepo = parseMultipleRepo(frontmatter, Properties); return parsePath(plugin, repository, multipleRepo, frontmatter); } else if (frontmatter.repo) { if (typeof frontmatter.repo === "object") { if (frontmatter.repo.branch != undefined) { - repoFrontmatter.branch = frontmatter.repo.branch; + Properties.branch = frontmatter.repo.branch; } if (frontmatter.repo.repo != undefined) { - repoFrontmatter.repo = frontmatter.repo.repo; + Properties.repo = frontmatter.repo.repo; } if (frontmatter.repo.owner != undefined) { - repoFrontmatter.owner = frontmatter.repo.owner; + Properties.owner = frontmatter.repo.owner; } if (frontmatter.repo.autoclean != undefined) { - repoFrontmatter.autoclean = frontmatter.repo.autoclean; + Properties.autoclean = frontmatter.repo.autoclean; isFrontmatterAutoClean = true; } } else { const repo = frontmatter.repo.split("/"); isFrontmatterAutoClean = repo.length > 4 ? true : null; - repoFrontmatter = repositoryStringSlice(repo, repoFrontmatter); + Properties = repositoryStringSlice(repo, Properties); } } else if (frontmatter.shortRepo instanceof Array) { - return multipleShortKeyRepo(frontmatter, settings.github.otherRepo, repoFrontmatter, plugin); + return multipleShortKeyRepo(frontmatter, settings.github.otherRepo, Properties, plugin); } if (frontmatter.autoclean != undefined && isFrontmatterAutoClean === null) { - repoFrontmatter.autoclean = frontmatter.autoclean; + Properties.autoclean = frontmatter.autoclean; } - return parsePath(plugin, repository, repoFrontmatter); + return parsePath(plugin, repository, Properties); } /** - * Get the repoFrontmatter array from the frontmatter + * Get the Properties array from the frontmatter * @example * multipleRepo: * - repo: repo1 @@ -189,22 +189,22 @@ export function getRepoFrontmatter( * branch: branch2 * autoclean: false * @param {FrontMatterCache} frontmatter - * @param {RepoFrontmatter} repoFrontmatter - * @return {RepoFrontmatter[]} + * @param {Properties} Properties + * @return {Properties[]} */ function parseMultipleRepo( frontmatter: FrontMatterCache, - repoFrontmatter: RepoFrontmatter + Properties: Properties ) { - const multipleRepo: RepoFrontmatter[] = []; + const multipleRepo: Properties[] = []; if ( frontmatter.multipleRepo instanceof Array && frontmatter.multipleRepo.length > 0 ) { for (const repo of frontmatter.multipleRepo) { if (typeof repo === "object") { - const repository: RepoFrontmatter = structuredClone(repoFrontmatter); + const repository: Properties = structuredClone(Properties); if (repo.branch != undefined) { repository.branch = repo.branch; } @@ -221,7 +221,7 @@ function parseMultipleRepo( } else { //is string const repoString = repo.split("/"); - const repository: RepoFrontmatter = structuredClone(repoFrontmatter); + const repository: Properties = structuredClone(Properties); multipleRepo.push( repositoryStringSlice(repoString, repository) ); @@ -232,12 +232,12 @@ function parseMultipleRepo( } /** - * Removes duplicate repositories from the given array of RepoFrontmatter objects. + * Removes duplicate repositories from the given array of Properties objects. * Only the {repo, owner, branch, autoclean} properties are compared. - * @param multipleRepo - An array of RepoFrontmatter objects representing multiple repositories. - * @returns An array of RepoFrontmatter objects with duplicate repositories removed. + * @param multipleRepo - An array of Properties objects representing multiple repositories. + * @returns An array of Properties objects with duplicate repositories removed. */ -function removeDuplicateRepo(multipleRepo: RepoFrontmatter[]) { +function removeDuplicateRepo(multipleRepo: Properties[]) { return multipleRepo.filter( (v, i, a) => a.findIndex( @@ -251,19 +251,19 @@ function removeDuplicateRepo(multipleRepo: RepoFrontmatter[]) { } /** - * Get the repoFrontmatter from the `shortRepo` string ; - * Using the `default` key will put the default repoFrontmatter in the list + * Get the Properties from the `shortRepo` string ; + * Using the `default` key will put the default Properties in the list * @param {FrontMatterCache} frontmatter - The frontmatter of the file * @param {Repository[]} allRepo - The list of all repo from the settings - * @param {RepoFrontmatter} repoFrontmatter - The default repoFrontmatter (from the default settings) + * @param {Properties} properties - The default Properties (from the default settings) */ -function multipleShortKeyRepo(frontmatter: FrontMatterCache, allRepo: Repository[], repoFrontmatter: RepoFrontmatter, plugin: GithubPublisher) { +function multipleShortKeyRepo(frontmatter: FrontMatterCache, allRepo: Repository[], properties: Properties, plugin: GithubPublisher) { if (frontmatter.shortRepo instanceof Array) { - const multipleRepo: RepoFrontmatter[] = []; + const multipleRepo: Properties[] = []; for (const repo of frontmatter.shortRepo) { const smartKey = repo.toLowerCase(); if (smartKey === "default") { - multipleRepo.push(repoFrontmatter); + multipleRepo.push(properties); } else { const shortRepo = allRepo.find((repo) => { return repo.smartKey.toLowerCase() === smartKey; @@ -273,12 +273,12 @@ function multipleShortKeyRepo(frontmatter: FrontMatterCache, allRepo: Repository branch: shortRepo.branch, repo: shortRepo.repo, owner: shortRepo.user, - autoclean: repoFrontmatter.autoclean, + autoclean: properties.autoclean, automaticallyMergePR: shortRepo.automaticallyMergePR, workflowName: shortRepo.workflow.name, commitMsg: shortRepo.workflow.commitMessage, - dryRun: repoFrontmatter.dryRun - } as RepoFrontmatter; + dryRun: properties.dryRun + } as Properties; const parsedPath = parsePath(plugin, shortRepo, repo); repo = Array.isArray(parsedPath) ? parsedPath[0] : parsedPath; multipleRepo.push(repo); @@ -287,7 +287,7 @@ function multipleShortKeyRepo(frontmatter: FrontMatterCache, allRepo: Repository } return multipleRepo; } - return repoFrontmatter; + return properties; } /** @@ -301,12 +301,12 @@ function multipleShortKeyRepo(frontmatter: FrontMatterCache, allRepo: Repository * @example * repo: repo1 * @param {string} repo - * @param {RepoFrontmatter} repoFrontmatter - * @return {RepoFrontmatter} + * @param {Properties} properties + * @return {Properties} */ -function repositoryStringSlice(repo: string, repoFrontmatter: RepoFrontmatter): RepoFrontmatter { - const newRepo: RepoFrontmatter = structuredClone(repoFrontmatter); +function repositoryStringSlice(repo: string, properties: Properties): Properties { + const newRepo: Properties = structuredClone(properties); if (repo.length === 4) { newRepo.branch = repo[2]; newRepo.repo = repo[1]; @@ -347,10 +347,10 @@ export function getCategory( export function parsePath( plugin: GithubPublisher, repository: Repository | null, - repoFrontmatter: RepoFrontmatter | RepoFrontmatter[], + properties: Properties | Properties[], frontmatter?: FrontMatterCache | null | undefined -): RepoFrontmatter[] | RepoFrontmatter { - repoFrontmatter = repoFrontmatter instanceof Array ? repoFrontmatter : [repoFrontmatter]; +): Properties[] | Properties { + properties = properties instanceof Array ? properties : [properties]; const settings = plugin.settings; const splitArrayPath = (path?: string[] | string):string|undefined => { if (!path) return; @@ -366,7 +366,7 @@ export function parsePath( return settings.upload.behavior; }; - for (const repo of repoFrontmatter) { + for (const repo of properties) { const smartKey = repository ? repository.smartKey : "default"; const path: Path = { @@ -421,7 +421,7 @@ export function parsePath( path.category!.value = getCategory(frontmatter, settings, path); repo.path = path; } - return repoFrontmatter; + return properties; } function getFrontmatterSettingRepository( diff --git a/src/utils/status_bar.ts b/src/utils/status_bar.ts index e147b391..1a699fe4 100644 --- a/src/utils/status_bar.ts +++ b/src/utils/status_bar.ts @@ -107,12 +107,12 @@ export class ShareStatusBar { * Remove the status bar if error occurs */ - error(repoFrontmatter: Properties) { + error(prop: Properties) { this.statusBarItem.addClass("error"); this.statusBarItem.removeClass("sharing"); this.statusBarItem.removeClass("found-attachments"); this.icon.innerHTML = ERROR_ICONS; - this.status.innerHTML = i18next.t("error.errorPublish", {repo: repoFrontmatter}); + this.status.innerHTML = i18next.t("error.errorPublish", {repo: prop}); this.noticeMobile?.hide(); setTimeout(() => { this.statusBarItem.remove();