-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.py
executable file
·52 lines (39 loc) · 1.67 KB
/
filter.py
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
#!/usr/bin/env python3
import io
import json
import os
import sys
from pandocfilters import walk, Link, Image
# change targets of links
def rewrite_target(key, val, fmt, meta):
# get potentially different url extension
ext = os.getenv('FILTER_URL_EXTENSION', '.html')
# when we are at a link node
if key == 'Link':
# get details of link
attr, inline, target = val
if target[0].startswith('http://') or target[0].startswith('https://') or target[0].startswith('mailto:'):
url = target[0]
else:
parts = target[0].split('#', 1)
if len(parts) > 1:
url = meta['root']['c'] + parts[0] + ext + '#' + parts[1]
else:
url = meta['root']['c'] + parts[0] + ext
return Link(attr, inline, [url, target[1]])
# when we are at a image node
elif key == 'Image':
# get details of link
attr, inline, target = val
if target[0].startswith('http://') or target[0].startswith('https://') or target[0].startswith('mailto:'):
url = target[0]
else:
path = target[0]
url = meta['root']['c'] + path
return Image(attr, inline, [url, target[1]])
# rewrite link targets in file
def rewrite_targets(doc, fmt):
return walk(doc, rewrite_target, fmt, doc['meta'] if 'meta' in doc else doc[0]['unMeta'])
if __name__ == '__main__':
# read JSON in, parse it with an optional format argument, and write JSON out
json.dump(rewrite_targets(json.load(io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')), sys.argv[1] if len(sys.argv) > 1 else ''), io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8'))