#!/usr/local/Python25/bin/python # _*_ coding: utf-8 _*_ # Copyright (C) 2007 Ayukawa Hiroshi from operator import and_ import urllib2 import re from django.core.cache import cache from django import template URLPAT = "http://coderepos.org/share/browser%s?rev=%d&format=txt" def get_coderepos_src(fname, rev, sline=None, eline=None): try: rev = int(rev) if sline: sline = int(sline) if eline: eline = int(eline) except ValueError: #引数が数字ではないので return None if not fname: return None cachekey = "coderepossrc_%d_%s" % (rev, fname) lines = cache.get(cachekey) if not lines: try: up = urllib2.urlopen(URLPAT % (fname, rev)) except urllib2.URLError, e: #エラー時のメッセージ return u"(*_*;) 。oO ( CodeRepos returned URL ERROR %d )\nソースコードを取得できませんでした。\n%s" % (e.code, URLPAT % (fname, rev)) lines = [unicode(l, "utf-8", "ignore") for l in up.readlines()] cache.set(cachekey, lines, 7*24*3600) #1週間保存 if sline or eline: if not eline: lines = lines[sline-1:] elif not sline: lines = lines[:eline] else: lines = lines[sline-1:eline] contents = "".join(lines) return contents TAGPAT = re.compile(ur"\[CODEREPOS:([^:]+):([0-9]+)(?::([0-9]+):([0-9]+))?\]") def henkan(g): return u"
%s" % get_coderepos_src(g.group(1), g.group(2), g.group(3), g.group(4)) def codereposfilter(value): return TAGPAT.sub(henkan, value) register = template.Library() register.filter("coderepos", codereposfilter)