Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a script to linkify PEPs #194

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions link-peps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#! /usr/bin/env python
"""Destructively* link PEPs in the given Markdown document.

"PEP nnnn" or "PEP nnnn (title)" are converted to "[PEP nnnn](url) (title)".

* The document is changed "destructively". Make a backup (e.g. `git add`)
before runnig the tool.

This is just a simple helper for simple cases. Always check its work.
"""

import re
import fileinput
import urllib.request
import json

PEP_RE = re.compile(
r'''
(?<!\[) # Don't process links (square bracket before 'PEP')
PEP # 'PEP'
(\s|-)* # Whitespace or dash(es)
(?P<num>\d+) # PEP number
\s* # Optional whitespace
( # Optionally:
\( # parenthesized
(?P<title> # title
[^)]+ # (anything except end-parenthesis)
)
\)
)?
''',
re.VERBOSE,
)

def linkify(match):
number = int(match['num'])
title = match['title'] or get_title(number)
return f'[PEP {number}](https://peps.python.org/pep-{number:04}/) ({title})'

def get_title(number):
global pep_info
try:
pep_info
except NameError:
with urllib.request.urlopen('https://peps.python.org/api/peps.json') as response:
pep_info = json.load(response)
return pep_info[str(number)]['title']


for line in fileinput.input(inplace=True):
print(PEP_RE.sub(linkify, line.rstrip()))