]> git.phdru.name Git - phdru.name/phdru.name.git/blob - phd_pp.py
Scripts to (re)build phd.pp.ru site.
[phdru.name/phdru.name.git] / phd_pp.py
1 import os, re, time
2 from Cheetah.Template import Template
3
4
5 # Copied from ZWiki
6
7 urlchars         = r'[A-Za-z0-9/:@_%~#=&\.\-\?\+\$,]+'
8 urlendchar       = r'[A-Za-z0-9/]'
9 url              = r'["=]?((about|gopher|http|https|ftp|mailto|file):%s)' % \
10                    (urlchars+urlendchar)
11
12 def _url2href(match):
13    url = match.group(0)
14    return '<a href="%s">%s</a>' % (url, url)
15
16
17 full_dirs = len(os.getcwd().split('/')) + 1
18
19 class phd_pp(Template):
20    def __init__(self, *args, **kw):
21       Template.__init__(self, *args, **kw)
22       directories = self._fileDirName.split('/')[full_dirs:] # remove directories up to "./files"
23       dirs_to_root = len(directories)
24       if dirs_to_root:
25          root = "../"*dirs_to_root
26       else:
27          root = ''
28       self.root = root
29       path = '/'.join(directories) + '/' + \
30          self._fileBaseName.replace(".tmpl", ".html")
31       if path[0] <> '/': path = '/' + path
32       self.path = path
33
34    def copyright(self, start_year):
35       this_year = time.localtime()[0]
36       if start_year >= this_year:
37          return this_year
38       if start_year == this_year - 1:
39          return "%s, %s" % (start_year, this_year)
40       return "%s-%s" % (start_year, this_year)
41
42    def body(self):
43       if hasattr(self, "body_html"):
44          return self.body_html()
45       if hasattr(self, "body_text"):
46          return self.text2html()
47       if hasattr(self, "body_rst"):
48          return self.rst2html()
49
50    def text2html(self):
51       body = re.sub(url, _url2href, self.body_text())
52
53       paragraphs = body.split("\n\n")
54
55       new_paras = []
56       for p in paragraphs:
57          parts = p.split("\n   ")
58          parts[0] = parts[0].strip()
59          new_paras.append('\n</p>\n<p>\n'.join(parts))
60
61       if self.Title:
62          title = "<h1>%s</h1>\n\n" % self.Title
63       else:
64          title = ''
65
66       body = '\n</p>\n\n<p class="head">\n'.join(new_paras)
67       return "%s<p>%s</p>" % (title, body)
68
69    def rst2html(self):
70       from docutils.core import publish_parts
71       from locale import getpreferredencoding
72       encoding = getpreferredencoding()
73
74       parts = publish_parts(self.body_rst(), writer_name="html")
75
76       title = parts["title"].encode(encoding) or self.Title
77       if title:
78          title = "<h1>%s</h1>" % title
79
80       subtitle = parts["subtitle"].encode(encoding)
81       if subtitle:
82          subtitle = "<h2>%s</h2>" % subtitle
83
84       body = parts["body"].encode(encoding)
85       parts = [part for part in (title, subtitle, body) if part]
86       return "\n\n".join(parts)