1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
#!/usr/local/bin/python3.12
import markdown
import sys
import io
import os
import re
from pygments.formatters import HtmlFormatter
from markdown.extensions.toc import TocExtension
from markdown.treeprocessors import Treeprocessor
from markdown import Extension
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# Build root-relative plain URL base: /<repo>/plain/
repo_url = os.environ.get('CGIT_REPO_URL', '')
if repo_url:
plain_base = '/' + repo_url.strip('/') + '/plain/'
else:
plain_base = None
class RewriteRelativeURLs(Treeprocessor):
def run(self, root):
if not plain_base:
return
for img in root.iter('img'):
src = img.get('src', '')
if src and not src.startswith(('http://', 'https://', '//', '#', 'data:')):
img.set('src', plain_base + src.lstrip('/'))
for a in root.iter('a'):
href = a.get('href', '')
if href and not href.startswith(('http://', 'https://', '//', '#', 'mailto:')):
a.set('href', plain_base + href.lstrip('/'))
class RewriteURLsExtension(Extension):
def extendMarkdown(self, md):
md.treeprocessors.register(RewriteRelativeURLs(md), 'rewrite_urls', 5)
sys.stdout.write("<div class='markdown-body'>")
sys.stdout.flush()
markdown.markdownFromFile(
output_format="html5",
extensions=[
"markdown.extensions.fenced_code",
"markdown.extensions.codehilite",
"markdown.extensions.tables",
"markdown.extensions.sane_lists",
TocExtension(anchorlink=True),
RewriteURLsExtension()],
extension_configs={
"markdown.extensions.codehilite":{"css_class":"highlight"}}
)
sys.stdout.write("</div>")
|