From faea1b4abb61b42319c780ff8b3df5edb86f326b Mon Sep 17 00:00:00 2001 From: ludeeus Date: Thu, 23 May 2024 09:57:49 +0000 Subject: [PATCH] Refactor markdownWithRepositoryContext function to improve URL handling --- src/tools/markdown.ts | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/src/tools/markdown.ts b/src/tools/markdown.ts index d7732825..029a3481 100644 --- a/src/tools/markdown.ts +++ b/src/tools/markdown.ts @@ -5,31 +5,29 @@ const showGitHubWeb = (text: string) => export const markdownWithRepositoryContext = (input: string, repository?: RepositoryInfo) => { // Handle convertion to raw GitHub URL - input = input.replace(/(https:\/\/github\.com\/.*.\/blob*.[^\s]+)/g, function (x) { - return showGitHubWeb(x) - ? x - : x - .replace("https://github.com/", "https://raw.githubusercontent.com/") - .replace("/blob/", "/"); - }); + input = input.replace( + /https:\/\/github\.com\/([^\/]+)\/([^\/]+)\/blob\/([^\s]+)/g, + function (x, owner, repo, path) { + return showGitHubWeb(x) ? x : `https://raw.githubusercontent.com/${owner}/${repo}/${path}`; + }, + ); // Handle relative links if (repository) { - input = input.replace(/(!)?\[*.*\]\((?!.*:\/\/).*\/*.*\.\w*\)/g, function (x) { + input = input.replace(/\[.*?\]\([^#](?!.*?:\/\/).*?\)/g, function (x) { + const showWeb = showGitHubWeb(x); return x .replace("(/", "(") .replace( "(", - `(${showGitHubWeb(x) ? `https://github.com` : `https://raw.githubusercontent.com`}/${ + `(${showWeb ? `https://github.com` : `https://raw.githubusercontent.com`}/${ repository.full_name - }${showGitHubWeb(x) ? "/blob" : ""}/${ - repository.available_version || repository.default_branch - }/` + }${showWeb ? "/blob" : ""}/${repository.available_version || repository.default_branch}/`, ); }); // Handle anchor refrences - input = input.replace(/\[*.*\]\(\#.*\)/g, function (x) { + input = input.replace(/\[.*\]\(\#.*\)/g, function (x) { return x.replace("(#", `(/hacs/repository/${repository.id}#`); }); @@ -40,13 +38,5 @@ export const markdownWithRepositoryContext = (input: string, repository?: Reposi return `[${reference}](https://github.com/${fullName}/issues/${issue})`; }); } - - // Shorten commits links - input = input.replace( - /[^(]https:\/\/github\.com\/\S*\/commit\/([0-9a-f]{40})/g, - (url, commit) => { - return `[\`${commit.substr(0, 7)}\`](${url})`; - } - ); return input; };