Python で blosxom !

書こうと思ったけどやめちゃった (笑) 雰囲気はわかったからいいかな〜(’’;)

#!/usr/bin/env python

import os

opts = {
        'data-dir' : "data",
        'data-ext' : ".txt",
        }

class BlosxomPy:
    class Entry:
        pass

    def __init__(self, opts):
        self.opts = opts

    def run(self):
        def sort_by_mtime(a, b):
            return cmp(b.time, a.time)
        entries = self.entries()
        entries.sort(sort_by_mtime)
        print repr([e.name for e in entries])

    def entries(self):
        ret = []
        for path in self.listfiles(opts['data-dir']):
            f = file(path)
            content = f.readlines()

            e = self.Entry()
            e.file  = path
            e.name  = path.replace(opts['data-dir'], '').replace(opts['data-ext'], '')
            e.time  = os.stat(path).st_mtime
            e.title = content[0]
            e.body  = content[1:-1]
            ret.append(e)

        return ret

    def listfiles(self, dir):
        def _listfiles(dirs, result):
            if len(dirs) == 0:
                return result

            dir = dirs.pop()
            for file in os.listdir(dir):
                file = os.path.normpath(os.path.join(dir, file))
                if os.path.isdir(file):
                    dirs.append(file)
                else:
                    result.append(file)
            # tail call
            return _listfiles(dirs, result)
        return _listfiles([dir], [])

BlosxomPy(opts).run()

Python は Pyblosxom とかゆうのがあるし、べつにいいかなぁ??

  • リストの内包表記は楽しいかも
  • いろんなところのコロンを忘れる (笑)
  • リファレンスから目的の関数がひきにくい (オブジェクト指向じゃないからかな)

書いたあとに調べてみたら Python は末尾再帰最適化しなかった(ノ_<。)