The Last Static Blog.

This blog

Thu 17 Mar 2011

blog, prog, python, static blog, kiss, first

Getting rid of PHP and MySQL on my server was one of my quests, and rewriting my old French blog was my first assignment in order to fulfill it. Since this is now done, I'll share further in this first post its source code.

So this is the direct continuation of my blog where I'll try to talk mostly on various technical and fun nerds stuff. You will also note my English is even worse than my approximative French, but I hope it will still be readable. I will try to rewrite the most interesting stuff of pilule-rouge.net before I finally drop it.

Speaking of the blog features, here is an exhaustive list:

And that's all. No there is no comments system, but you can contact me on IRC/jabber/mail (see page footer for more information).

Here is the simple python script I use:

  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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python2

import glob, os, sys, unicodedata, markdown, time, urllib, email.utils
from pygments.formatters import get_formatter_by_name

TPL_BASE = '''<!doctype html>
<html>
 <head>
  <title>%(title)s</title>
  <link rel="icon" type="image/png" href="/favicon.png" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link href="/rss.xml" rel="alternate" type="application/rss+xml" title="blog.pkh.me" />
  <link rel="stylesheet" type="text/css" href="/style.css" />
  <link rel="stylesheet" type="text/css" href="/pygments.css" />
  <meta name="keywords" content="%(tags)s" />
  <meta name="viewport" content="width=device-width" />
 </head>
 <header><a href="/index.html">The Last Static Blog.</a></header>
 <body>
  <div id="content">%(content)s</div>
 </body>
 <footer>
  <a href="http://ubitux.fr">www/misc</a>
  | jabber: <i>u pkh.me</i>
  | mail: <i>ubitux gmail</i>
  | irc: <i>ubitux@<a href="http://freenode.net">freenode</a>/<a href="http://yozora-irc.net">yozora</a></i>
 </footer>
</html>
'''

TPL_POST = '''
<h1><a href="#content">%(title)s</a></h1>
<p class="date">%(date)s</p>
%(tags)s
<article>%(content)s</article>
<p id="idxurl"><a href="/index.html">index</a> | <a href="%(raw_url)s">article raw</a></p>
'''

TPL_RSS = '''<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
 <channel xmlns:atom="http://www.w3.org/2005/Atom">
  <atom:link href="http://blog.pkh.me/rss.xml" rel="self" type="application/rss+xml" />
  <title>The Last Static Blog RSS</title>
  <description>Default feed for blog.pkh.me</description>
  <link>http://blog.pkh.me/</link>
%s
 </channel>
</rss>
'''

TPL_RSS_ITEM = '''<item>
 <guid>%(guid)s</guid>
 <link>%(link)s</link>
 <title>%(title)s</title>
 <pubDate>%(date)s</pubDate>
 <description>%(desc)s</description>
</item>
'''

def get_page_name(base, n):
    return '%s-p%d.html' % (base, n) if n != 1 else '%s.html' % base

def escape(s):
    return s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')

def get_tag_html(tags, current=None):
    tdata = []
    for tag in tags:
        if tag == current:
            tdata.append(tag)
        else:
            tdata.append('<a href="/index-%s.html">%s</a>' % (tag, tag))
    return '<p class="tags">%s<p>\n' % ', '.join(tdata)

def write_html_index(data, tag=None):

    files = []
    title = 'ubitux/blog'
    bname = 'index'
    data  = data[::-1]
    if tag:
        bname += '-' + tag
        title += '/' + tag
        data = filter(lambda e: tag in e['tags'], data)

    n = 5
    pages = [data[i:i+n] for i in range(0, len(data), n)]
    for (n, entries) in enumerate(pages, 1):
        fname = get_page_name(bname, n)
        print('   writing %s' % fname)

        pdata = []
        for i in range(1, len(pages) + 1):
            if i == n:
                pdata.append('%d' % i)
            else:
                pdata.append('<a href="%s">%d</a>' % (get_page_name(bname, i), i))

        raw = '<p class="pages">%s</p>\n' % ' '.join(pdata)
        for entry in entries:
            raw += '''<h1><a href="%(page)s">%(title)s</a></h1>
                      <p class="date">%(date)s</p>
                      <p>%(preview)s</p>''' % entry
            raw += get_tag_html(entry['tags'], tag)

        files.append(fname)
        index = open(fname, 'w')
        index.write(TPL_BASE % {
            'tags':   'last static blog, computing, nerd',
            'title':   title,
            'content': raw,
        })
        index.close()

    return files

def write_pages(raws, noidx):
    fulltaglist = set()
    plist = ['p/index.html']
    index_data = []

    if noidx: print(':: write requested pages only')
    else:     print(':: write pages')

    for i, raw in enumerate(raws):
        meta, content = open(raw, 'r').read().split('\n\n', 1)

        title, tags, disabled = None, [], False

        for line in meta.splitlines():
            k, v = line.split(':', 1)
            v = v.strip()
            if k == 'title':
                title = escape(v)
            elif k == 'tags':
                tags = [t.strip() for t in v.split(',')]
                fulltaglist |= set(tags)
            elif k == 'disabled':
                disabled = v.lower() in ('true', 'yes', '1')

        if not title:
            print('No title set in %s. Abort page generation' % raw)
            continue

        p = unicodedata.normalize('NFKD', title.decode('utf-8')).encode('ascii', 'ignore')
        p = 'p/%d-%s.html' % (i, '-'.join(p.strip().lower().replace('/', ' ').split()))
        print('   writing %s' % p)

        ts = int(raw.split('/')[-1][:-4])
        datefmt = time.strftime('%a %d %b %Y', time.gmtime(ts))

        out = open(p, 'w')
        out.write(TPL_BASE % {
            'title':   title,
            'tags':    ', '.join(tags),
            'content': TPL_POST % {
                'title':   title,
                'date':    datefmt,
                'tags':    get_tag_html(tags),
                'raw_url': '/' + raw,
                'content': markdown.markdown(content.decode('utf-8'),
                                             ['codehilite(force_linenos=True)', 'codeinsert']).encode('utf-8'),
            }
        })
        out.close()

        plist.append(p)

        if disabled:
            print('     -> page %s is disabled' % p)
            continue

        index_data.append({
            'title':   title,
            'page':    urllib.quote(p),
            'preview': ' '.join(content.split()[:20]) + '...',
            'tags':    tags,
            'ts':      ts,
            'date':    datefmt,
        })

    if noidx:
        return

    print('\n:: write indexes')
    files = write_html_index(index_data)
    for tag in fulltaglist:
        files += write_html_index(index_data, tag)

    print('\n:: cleanup')
    for f in set(files) ^ set(glob.glob('index*html')):
        print('   rm %s' % f)
        os.unlink(f)

    for f in set(plist) ^ set(glob.glob('p/*html')):
        print('   rm %s' % f)
        os.unlink(f)

    print('\n:: update pygments CSS')
    csshilite = open('pygments.css', 'w')
    csshilite.write(get_formatter_by_name('html', style='monokai').get_style_defs('.codehilite'))
    csshilite.close()

    print('\n:: RSS')
    rss_content = ''
    rss = open('rss.xml', 'w')
    for item in index_data[::-1][:10]:
        link = 'http://blog.pkh.me/' + item['page']
        info = {
            'guid':       link,
            'short-link': item['page'],
            'link':       link,
            'title':      item['title'],
            'date':       email.utils.formatdate(item['ts']),
            'links':      '',
            'desc':       escape(item['preview']),
        }
        rss_content += TPL_RSS_ITEM % info

    rss_content = TPL_RSS % rss_content
    rss.write(rss_content)
    rss.close()

if len(sys.argv) > 1:
    write_pages(sys.argv[1:], True)
else:
    write_pages(sorted(glob.glob('raw/*.raw')), False)

And the insert code module for markdown:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import markdown

class CodeInsertPreprocessor(markdown.preprocessors.Preprocessor):
    def run(self, lines):
        new_lines = []
        for line in lines:
            if not line.startswith('    ||'):
                new_lines.append(line)
                continue
            lang, fname = line[4+2:].split(':')
            new_lines += ['    :::' + lang]
            f = open(fname, 'r')
            new_lines += ['    ' + l for l in f.read().splitlines()]
            f.close()
        return new_lines

class CodeInsertExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        md.preprocessors.add('codeinsert', CodeInsertPreprocessor(md), '<reference')

def makeExtension(configs=None):
    return CodeInsertExtension(configs=configs)

And deploy:

1
2
3
4
5
6
7
#!/bin/sh

[ $# -ne 1 ] && echo usage: $0 rawfile && exit

cp -n $1 raw/`date +%s`.raw && rm -f $1

./run.py

And finally the basic usage:

./deploy my-last-awesome-blog-post

index | article raw