Created
December 31, 2023 10:48
-
-
Save osa1/8867af00e0e663bc417310962cd23f7d to your computer and use it in GitHub Desktop.
Convert markdown issue, PR, commit references to GitHub links (written by ChatGPT)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# linkify.py input.md output.md github-username github-repo-name | |
# | |
# Converts PR, issue, and commit references to full links. | |
# | |
# Written by ChatGPT. | |
import re | |
import requests | |
import argparse | |
def is_pull_request(url): | |
response = requests.head(url, allow_redirects=True) | |
# Check if the final URL is a pull request URL | |
return 'pull' in response.url.split('/') | |
def replace_mentions_with_links(markdown_content, username, repo): | |
# Define regular expressions for GitHub issue, PR, and commit mentions | |
issue_pr_pattern = re.compile(r'#(\d+)') | |
commit_pattern = re.compile(r'\b([a-f0-9]{40})\b') | |
def replace_issue_pr(match): | |
number = match.group(1) | |
issue_url = f'https://github.com/{username}/{repo}/issues/{number}' | |
is_pr = is_pull_request(issue_url) | |
if is_pr: | |
return f'[PR #{number}]({issue_url})' | |
else: | |
return f'[Issue #{number}]({issue_url})' | |
def replace_commit(match): | |
commit_hash = match.group(1) | |
return f'[Commit {commit_hash}](https://github.com/{username}/{repo}/commit/{commit_hash})' | |
# Replace mentions with links | |
markdown_content = issue_pr_pattern.sub(replace_issue_pr, markdown_content) | |
markdown_content = commit_pattern.sub(replace_commit, markdown_content) | |
return markdown_content | |
def main(): | |
parser = argparse.ArgumentParser(description='Process GitHub mentions in a Markdown file.') | |
parser.add_argument('input_file', help='Path to the input Markdown file') | |
parser.add_argument('output_file', help='Path to the output Markdown file') | |
parser.add_argument('username', help='Your GitHub username') | |
parser.add_argument('repo', help='Your GitHub repository name') | |
args = parser.parse_args() | |
with open(args.input_file, 'r', encoding='utf-8') as file: | |
markdown_content = file.read() | |
processed_content = replace_mentions_with_links(markdown_content, args.username, args.repo) | |
with open(args.output_file, 'w', encoding='utf-8') as file: | |
file.write(processed_content) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment