Skip to content

Commit

Permalink
Refactor markdownWithRepositoryContext function to improve URL handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ludeeus committed May 23, 2024
1 parent 6b59bf7 commit faea1b4
Showing 1 changed file with 11 additions and 21 deletions.
32 changes: 11 additions & 21 deletions src/tools/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}#`);
});

Expand All @@ -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;
};

0 comments on commit faea1b4

Please sign in to comment.