summaryrefslogtreecommitdiff
path: root/mkfeed.py
blob: 6b87b32287a77b927f57fa7f0aa1a74c8a001f9d (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
# Written by Martin Fischer <martin@push-f.com> and licensed under MIT.
# The embedded SVG is licensed under Mozilla's MPL / GPL / LGPL and
# from https://commons.wikimedia.org/wiki/File:Generic_Feed-icon.svg.
import os
import sys
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape

FEED_SVG = '<svg height="25" width="25" viewBox="0 0 8 8" xmlns="http://www.w3.org/2000/svg"><title>Feed</title><rect fill="#f3b01b" height="8" rx="1.5" width="8"/><g fill="#fff"><circle cx="2" cy="6" r="1"/><path d="m1 4a3 3 0 0 1 3 3h1a4 4 0 0 0 -4-4z"/><path d="m1 2a5 5 0 0 1 5 5h1a6 6 0 0 0 -6-6z"/></g></svg>'

URL = escape(os.environ['URL'])
TITLE = escape(os.environ['TITLE'])

posts = []

DIRNAME = sys.argv[1].strip('/')
DIR = '/' + DIRNAME + '/'
OUTDIR = 'build' + DIR

for filename in sorted(os.listdir(OUTDIR), reverse=True):
    if filename in ('atom.xml', 'index.html'):
        continue
    tree = ET.parse(OUTDIR + filename + '/index.html').getroot()
    title = tree.find('.//title')
    data = dict(
        title=escape(title.text),
        html=''.join(
            ET.tostring(c, 'unicode') for c in tree.find('.//div[@id="content"]')
        ),
        path=DIR + escape(filename),
    )
    dataEl = tree.find('.//meta[@name="dcterms.date"]')
    if dataEl is not None:
        data['date'] = dataEl.attrib['content']
        data['dateMeta'] = dataEl.attrib['content'] + 'T00:00:00Z'
    else:
        print('[warning] no date for', filename)
    posts.append(data)

last_updated = max([p['dateMeta'] for p in posts if 'dateMeta' in p])

with open(OUTDIR + 'index.html', 'w') as f:
    f.write(
        f'<h2>{escape(DIRNAME.title())} <a href="{escape(DIR)}atom.xml" style="vertical-align:top">{FEED_SVG}</a></h2>'
    )
    f.write('<ul class="mkfeed-list">')
    for post in posts:
        f.write(
            f"<li>{post.get('date')}: <a href=\"{post['path']}\">{post['title']}</a></li>"
        )
    f.write('</ul>')

with open(OUTDIR + 'atom.xml', 'w') as f:
    f.write(
        f'''\
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <id>{URL}</id>
 <title>{TITLE}</title>
 <link href="{URL}"/>
 <updated>{last_updated}</updated>
    '''
    )
    for post in posts[:10]:
        f.write(
            f'''
         <entry>
           <title>{post['title']}</title>
           <link href="{URL.rstrip('/')}{post['path']}"/>
           <id>{URL.rstrip('/')}{post['path']}</id>
           <updated>{post.get('dateMeta')}</updated>
           <content type="html"><![CDATA[{post['html']}]]></content>
         </entry>
        '''
        )
    f.write('</feed>')