Skip to content

Commit

Permalink
refactor: refactor all commands
Browse files Browse the repository at this point in the history
  • Loading branch information
Mara-Li committed Jun 17, 2022
1 parent b5ac9a9 commit 3418f2f
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 159 deletions.
39 changes: 3 additions & 36 deletions mkdocsPublisher/githubInteraction/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { GetFiles } from "./getFiles";
import {Base64} from "js-base64";

export async function deleteFromGithub(silent = false, settings: MkdocsPublicationSettings, octokit: Octokit, branchName='main', GetFiles: GetFiles) {
const getAllFile = await getAllFileFromRepo(branchName, octokit, settings);
const getAllFile = await GetFiles.getAllFileFromRepo(branchName, octokit, settings);
const filesInRepo = await filterGithubFile(getAllFile,
settings
);
Expand All @@ -31,10 +31,11 @@ export async function deleteFromGithub(silent = false, settings: MkdocsPublicati
return false;
}
const allSharedFiles = GetFiles.getAllFileWithPath();
const allSharedConverted = allSharedFiles.map((file) => { return file.converted; });
let deletedSuccess = 0;
let deletedFailed = 0;
for (const file of filesInRepo) {
if (!allSharedFiles.includes(file.file.trim())) {
if (!allSharedConverted.includes(file.file.trim())) {
try {
const checkingIndex = file.file.contains('index') ? await checkIndexFiles(octokit, settings, file.file):false;
if (!checkingIndex) {
Expand Down Expand Up @@ -113,41 +114,7 @@ export async function filterGithubFile(fileInRepo: { file: string; sha: string }
return sharedFilesInRepo;
}

async function getAllFileFromRepo(ref="main", octokit: Octokit, settings: MkdocsPublicationSettings) {
const filesInRepo = [];
try {
const repoContents = await octokit.request(
"GET" + " /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner: settings.githubName,
repo: settings.githubRepo,
tree_sha: ref,
recursive: "true",
}
);

if (repoContents.status === 200) {
const files = repoContents.data.tree;
for (const file of files) {
const basename = (name: string) =>
/([^/\\.]*)(\..*)?$/.exec(name)[1]; //don't delete file starting with .
if (
file.type === "blob" &&
basename(file.path).length > 0 &&
basename(file.path) != 'vault_published'
) {
filesInRepo.push({
file: file.path,
sha: file.sha,
});
}
}
}
} catch (e) {
console.log(e)
}
return filesInRepo;
}

function parseYamlFrontmatter(file: string) {
const yamlFrontmatter = file.split("---")[1];
Expand Down
11 changes: 8 additions & 3 deletions mkdocsPublisher/githubInteraction/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ import { GetFiles } from "./getFiles";
import { Octokit } from "@octokit/core";
import { Base64 } from "js-base64";
import {deleteFromGithub} from "./delete"

import {
convertLinkCitation,
convertWikilinks, getImageLinkOptions,
getReceiptFolder
} from "../utils/utils";
convertWikilinks
} from "../utils/convertText";

import {
getReceiptFolder, getImageLinkOptions
} from "../utils/filePathConvertor";

export default class MkdocsPublish {
vault: Vault;
Expand Down Expand Up @@ -152,6 +156,7 @@ export default class MkdocsPublish {
console.error(e);
}
}

async workflowGestion() {
let finished = false;
if (this.settings.workflowName.length === 0) {
Expand Down
66 changes: 66 additions & 0 deletions mkdocsPublisher/utils/convertText.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {MkdocsPublicationSettings} from "../settings/interface";
import {MetadataCache, TFile} from "obsidian";
import {getReceiptFolder, createRelativePath, getImageLinkOptions} from "./filePathConvertor";

function convertWikilinks(fileContent: string, settings: MkdocsPublicationSettings, linkedFiles: {linked: TFile, linkFrom: string, altText: string}[]) {
if (!settings.convertWikiLinks) {
return fileContent;
}
const wikiRegex = /\[\[.*?\]\]/g;
const wikiMatches = fileContent.match(wikiRegex);
if (wikiMatches) {
const fileRegex = /(?<=\[\[).*?(?=([\]|]))/;
for (const wikiMatch of wikiMatches) {
const fileMatch = wikiMatch.match(fileRegex);
if (fileMatch) {
const fileName = fileMatch[0];
const linkedFile=linkedFiles.find(item => item.linkFrom===fileName);
if (linkedFile) {
const altText = linkedFile.altText.length > 0 ? linkedFile.altText : linkedFile.linked.extension === 'md' ? linkedFile.linked.basename : "";
const linkCreator = `[${altText}](${encodeURI(linkedFile.linkFrom)})`;
fileContent = fileContent.replace(wikiMatch, linkCreator);
} else if (!fileName.startsWith('http')) {
const altMatch = wikiMatch.match(/(?<=\|).*(?=]])/);
const altCreator = fileName.split('/');
const altLink = creatorAltLink(altMatch, altCreator, fileName.split('.').at(-1));
const linkCreator = `[${altLink}](${encodeURI(fileName.trim())})`;
fileContent = fileContent.replace(wikiMatch, linkCreator);
}
}
}
}
return fileContent;
}

function convertLinkCitation(fileContent: string, settings: MkdocsPublicationSettings, linkedFiles : {linked: TFile, linkFrom: string, altText: string}[], metadataCache: MetadataCache, sourceFile: TFile) {
if (!settings.convertForGithub) {
return fileContent;
}
for (const linkedFile of linkedFiles) {
let pathInGithub=linkedFile.linked.extension === 'md' ? getReceiptFolder(linkedFile.linked, settings, metadataCache) : getImageLinkOptions(linkedFile.linked, settings);
const sourcePath = getReceiptFolder(sourceFile, settings, metadataCache);
pathInGithub = createRelativePath(sourcePath, pathInGithub);
const regexToReplace = new RegExp(`(\\[{2}.*${linkedFile.linkFrom}.*\\]{2})|(\\[.*\\]\\(.*${linkedFile.linkFrom}.*\\))`, 'g');
const matchedLink = fileContent.match(regexToReplace);
if (matchedLink) {
for (const link of matchedLink) {
const newLink = link.replace(linkedFile.linkFrom, pathInGithub);
fileContent = fileContent.replace(link, newLink);
}
}
}
return fileContent;
}

function creatorAltLink(altMatch: RegExpMatchArray, altCreator: string[], fileExtension: string) {
if (altMatch) {
return altMatch[0]
}
if (fileExtension === 'md') {
return altCreator.length > 1 ? altCreator[altCreator.length-1] : altCreator[0] //alt text based on filename for markdown files
}
return ''
}


export {convertWikilinks, convertLinkCitation, creatorAltLink};
61 changes: 61 additions & 0 deletions mkdocsPublisher/utils/filePathConvertor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {MetadataCache, TFile} from "obsidian";
import {MkdocsPublicationSettings} from "../settings/interface";

function createRelativePath(sourcePath: string, targetPath: string) {
const sourceList = sourcePath.split('/');
const targetList = targetPath.split('/');
const diffSourcePath = sourceList.filter(x => !targetList.includes(x));
const diffTargetPath = targetList.filter(x => !sourceList.includes(x));
const diffTarget = function (folderPath: string[]) {
const relativePath = [];
for (const folder of folderPath) {
if (folder != folderPath.at(-1)) {
relativePath.push('..');
}
}
return relativePath;
};
return diffTarget(diffSourcePath).concat(diffTargetPath).join('/')
}

function getReceiptFolder(file: TFile, settings:MkdocsPublicationSettings, metadataCache: MetadataCache) {
if (file.extension === 'md') {
const folderDefault = settings.folderDefaultName;
let path = settings.folderDefaultName.length > 0 ? settings.folderDefaultName + "/" + file.name : file.name;

if (settings.downloadedFolder === "yamlFrontmatter") {
const frontmatter = metadataCache.getCache(file.path).frontmatter
let folderRoot = settings.rootFolder;
if (folderRoot.length > 0) {
folderRoot = folderRoot + "/";
}
if (frontmatter && frontmatter[settings.yamlFolderKey]) {
const category = frontmatter[settings.yamlFolderKey]
const parentCatFolder = !category.endsWith('/') ? category.split('/').at(-1): category.split('/').at(-2);
const fileName = settings.folderNote && parentCatFolder === file.name ? 'index.md' : file.name
path = folderRoot + frontmatter[settings.yamlFolderKey] + "/" + fileName;
}
} else if (settings.downloadedFolder === "obsidianPath") {
const fileName = file.name.replace('.md', '') === file.parent.name && settings.folderNote ? 'index.md' : file.name
path = folderDefault + '/' + file.path.replace(file.name, fileName);
}
return path
}
}

function getImageLinkOptions(file: TFile, settings: MkdocsPublicationSettings) {
let fileDefaultPath = file.path;
const fileName = file.name;
if (settings.defaultImageFolder.length > 0) {
fileDefaultPath = settings.defaultImageFolder + "/" + fileName;
} else if (settings.folderDefaultName.length > 0) {
fileDefaultPath = settings.folderDefaultName + "/" + fileName;
}
return fileDefaultPath;
}

export {
getReceiptFolder,
getImageLinkOptions,
createRelativePath
}
121 changes: 1 addition & 120 deletions mkdocsPublisher/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {App, Notice, TFile, MetadataCache} from 'obsidian'
import {App, Notice, TFile} from 'obsidian'
import {MkdocsPublicationSettings} from '../settings/interface'
import MkdocsPublish from "../githubInteraction/upload";

Expand Down Expand Up @@ -30,126 +30,7 @@ async function noticeMessage(publish: MkdocsPublish, file: TFile | string, setti
}
}

function convertWikilinks(fileContent: string, settings: MkdocsPublicationSettings, linkedFiles: {linked: TFile, linkFrom: string, altText: string}[]) {
if (!settings.convertWikiLinks) {
return fileContent;
}
const wikiRegex = /\[\[.*?\]\]/g;
const wikiMatches = fileContent.match(wikiRegex);
if (wikiMatches) {
const fileRegex = /(?<=\[\[).*?(?=([\]|]))/;
for (const wikiMatch of wikiMatches) {
const fileMatch = wikiMatch.match(fileRegex);
if (fileMatch) {
const fileName = fileMatch[0];
const linkedFile=linkedFiles.find(item => item.linkFrom===fileName);
if (linkedFile) {
const altText = linkedFile.altText.length > 0 ? linkedFile.altText : linkedFile.linked.extension === 'md' ? linkedFile.linked.basename : "";
const linkCreator = `[${altText}](${encodeURI(linkedFile.linkFrom)})`;
fileContent = fileContent.replace(wikiMatch, linkCreator);
} else if (!fileName.startsWith('http')) {
const altMatch = wikiMatch.match(/(?<=\|).*(?=]])/);
const altCreator = fileName.split('/');
const altLink = creatorAltLink(altMatch, altCreator, fileName.split('.').at(-1));
const linkCreator = `[${altLink}](${encodeURI(fileName.trim())})`;
fileContent = fileContent.replace(wikiMatch, linkCreator);
}
}
}
}
return fileContent;
}

function creatorAltLink(altMatch: RegExpMatchArray, altCreator: string[], fileExtension: string) {
if (altMatch) {
return altMatch[0]
}
if (fileExtension === 'md') {
return altCreator.length > 1 ? altCreator[altCreator.length-1] : altCreator[0] //alt text based on filename for markdown files
}
return ''

}

function createRelativePath(sourcePath: string, targetPath: string) {
const sourceList = sourcePath.split('/');
const targetList = targetPath.split('/');
const diffSourcePath = sourceList.filter(x => !targetList.includes(x));
const diffTargetPath = targetList.filter(x => !sourceList.includes(x));
const diffTarget = function (folderPath: string[]) {
const relativePath = [];
for (const folder of folderPath) {
if (folder != folderPath.at(-1)) {
relativePath.push('..');
}
}
return relativePath;
};
return diffTarget(diffSourcePath).concat(diffTargetPath).join('/')
}

function getReceiptFolder(file: TFile, settings:MkdocsPublicationSettings, metadataCache: MetadataCache) {
if (file.extension === 'md') {
const folderDefault = settings.folderDefaultName;
let path = settings.folderDefaultName.length > 0 ? settings.folderDefaultName + "/" + file.name : file.name;

if (settings.downloadedFolder === "yamlFrontmatter") {
const frontmatter = metadataCache.getCache(file.path).frontmatter
let folderRoot = settings.rootFolder;
if (folderRoot.length > 0) {
folderRoot = folderRoot + "/";
}
if (frontmatter && frontmatter[settings.yamlFolderKey]) {
const category = frontmatter[settings.yamlFolderKey]
const parentCatFolder = !category.endsWith('/') ? category.split('/').at(-1): category.split('/').at(-2);
const fileName = settings.folderNote && parentCatFolder === file.name ? 'index.md' : file.name
path = folderRoot + frontmatter[settings.yamlFolderKey] + "/" + fileName;
}
} else if (settings.downloadedFolder === "obsidianPath") {
const fileName = file.name.replace('.md', '') === file.parent.name && settings.folderNote ? 'index.md' : file.name
path = folderDefault + '/' + file.path.replace(file.name, fileName);
}
return path
}
}

function convertLinkCitation(fileContent: string, settings: MkdocsPublicationSettings, linkedFiles : {linked: TFile, linkFrom: string, altText: string}[], metadataCache: MetadataCache, sourceFile: TFile) {
if (!settings.convertForGithub) {
return fileContent;
}
for (const linkedFile of linkedFiles) {
let pathInGithub=linkedFile.linked.extension === 'md' ? getReceiptFolder(linkedFile.linked, settings, metadataCache) : getImageLinkOptions(linkedFile.linked, settings);
const sourcePath = getReceiptFolder(sourceFile, settings, metadataCache);
pathInGithub = createRelativePath(sourcePath, pathInGithub);
const regexToReplace = new RegExp(`(\\[{2}.*${linkedFile.linkFrom}.*\\]{2})|(\\[.*\\]\\(.*${linkedFile.linkFrom}.*\\))`, 'g');
const matchedLink = fileContent.match(regexToReplace);
if (matchedLink) {
for (const link of matchedLink) {
const newLink = link.replace(linkedFile.linkFrom, pathInGithub);
fileContent = fileContent.replace(link, newLink);
}
}
}
return fileContent;
}

function getImageLinkOptions(file: TFile, settings: MkdocsPublicationSettings) {
let fileDefaultPath = file.path;
const fileName = file.name;
if (settings.defaultImageFolder.length > 0) {
fileDefaultPath = settings.defaultImageFolder + "/" + fileName;
} else if (settings.folderDefaultName.length > 0) {
fileDefaultPath = settings.folderDefaultName + "/" + fileName;
}
return fileDefaultPath;
}

export {
disablePublish,
noticeMessage,
convertWikilinks,
convertLinkCitation,
getReceiptFolder,
getImageLinkOptions,
createRelativePath
}

0 comments on commit 3418f2f

Please sign in to comment.