]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
A number of minor optimizations.
[phdru.name/phdru.name.git] / reindex_blog.py
1 #! /usr/local/bin/python -O
2 # -*- coding: koi8-r -*-
3
4 __version__ = "$Revision$"[11:-2]
5 __revision__ = "$Id$"[5:-2]
6 __date__ = "$Date$"[7:-2]
7 __author__ = "Oleg BroytMann <phd@phd.pp.ru>"
8 __copyright__ = "Copyright (C) 2006 PhiloSoft Design"
9
10
11 import sys, os
12
13 try:
14    import cPickle as pickle
15 except ImportError:
16    import pickle
17
18 from Cheetah.Template import Template
19
20
21 # Load old blog
22
23 blog_filename = sys.argv[1]
24 try:
25    blog_file = open(blog_filename, "rb")
26 except IOError:
27    old_blog = {}
28 else:
29    old_blog = pickle.load(blog_file)
30    blog_file.close()
31
32
33 # blog is a dictionary mapping (year, month, day) => (filename, title, lead)
34 blog = {}
35 years = {}
36
37 # Walk the directory recursively
38 for dirpath, dirs, files in os.walk(os.curdir):
39    for file in files:
40       # Ignore index.tmpl and *.html files; supose all other files are *.tmpl
41       if file == "index.tmpl" or file.endswith(".html"):
42          continue
43       fullpath = os.path.join(dirpath, file)
44       template = Template(file=fullpath)
45       title_parts = template.Title.split()
46       title = ' '.join(title_parts[6:])
47       lead = getattr(template, "Lead", None)
48
49       if title:
50          key = year, month, day = tuple(dirpath.split(os.sep)[1:])
51          if key in blog:
52             days = blog[key]
53          else:
54             days = blog[key] = []
55          days.append((file, title, lead))
56
57          if year in years:
58             months = years[year]
59          else:
60             months = years[year] = {}
61
62          if month in months:
63             days = months[month]
64          else:
65             days = months[month] = []
66
67          if day not in days: days.append(day)
68
69
70 # Need to save the blog?
71 if blog <> old_blog:
72    blog_file = open(blog_filename, "wb")
73    pickle.dump(blog, blog_file, pickle.HIGHEST_PROTOCOL)
74    blog_file.close()
75
76
77 # Localized month names
78
79 import locale
80 locale.setlocale(locale.LC_ALL, '')
81 from calendar import _localized_day, _localized_month
82
83 locale.setlocale(locale.LC_TIME, 'C')
84 months_names_en = list(_localized_month('%B'))
85 months_abbrs_en = list(_localized_month('%b'))
86
87 locale.setlocale(locale.LC_TIME, '')
88 months_names_ru = [month.lower() for month in _localized_month('%B')]
89
90 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
91    "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
92 ]
93
94
95 def write_template(level, year, month, day, titles):
96    path = []
97    if level >= 1:
98       path.append(year)
99    if level >= 2:
100       path.append(month)
101    if level == 3:
102       path.append(day)
103    path.append("index.tmpl")
104    index_name = os.path.join(*path)
105    try:
106       index_tmpl = open(index_name, 'r')
107       old_text = index_tmpl.read()
108       index_tmpl.close()
109    except IOError:
110       old_text = None
111
112    new_text = ["""\
113 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
114 #extends phd_pp_ru
115 #implements respond
116 """]
117
118    if level == 0:
119       new_text.append("""\
120 #attr $Title = "Oleg BroytMann's blog"
121 #attr $Description = "BroytMann Russian Blog Index Document"
122 #attr $Copyright = %(cyear)s
123 ##
124 #def body_html
125 <H1>Журнал</H1>
126 """ % {"cyear": year or 2005})
127
128    elif level == 1:
129       new_text.append("""\
130 #attr $Title = "Oleg BroytMann's blog: %(year)s"
131 #attr $Description = "BroytMann Russian Blog %(year)s Index Document"
132 #attr $Copyright = %(cyear)s
133 ##
134 #def body_html
135 <H1>Журнал: %(year)s</H1>
136 """ % {"year": year, "cyear": year or 2005})
137
138    elif level == 2:
139       imonth = int(month)
140       new_text.append("""\
141 #attr $Title = "Oleg BroytMann's blog: %(month_abbr_en)s %(year)s"
142 #attr $Description = "BroytMann Russian Blog %(month_name_en)s %(year)s Index Document"
143 #attr $Copyright = %(cyear)s
144 ##
145 #def body_html
146 <H1>Журнал: %(month_name_ru0)s %(year)s</H1>
147 """ % {
148       "year": year, "cyear": year or 2005,
149       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
150       "month_name_ru0": months_names_ru0[imonth],
151    })
152
153    elif level == 3:
154       iday = int(day)
155       imonth = int(month)
156
157       new_text.append("""\
158 #attr $Title = "Oleg BroytMann's blog: %(day)d %(month_abbr_en)s %(year)s"
159 #attr $Description = "BroytMann Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
160 #attr $Copyright = %(cyear)s
161 ##
162 #def body_html
163 <H1>Журнал: %(day)d %(month_name_ru0)s %(year)s</H1>
164 """ % {
165       "year": year, "cyear": year or 2005,
166       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
167       "month_name_ru0": months_names_ru0[imonth],
168       "day": iday
169    })
170
171    save_titles = titles[:]
172    titles.reverse()
173
174    save_day = None
175    for year, month, day, filename, title, lead in titles:
176       href = []
177       if level == 0:
178          href.append(year)
179       if level <= 1:
180          href.append(month)
181       if level <= 2:
182          href.append(day)
183       href.append(filename)
184       href = '/'.join(href)
185       if day[0] == '0': day = day[1:]
186       if save_day <> day:
187          if level == 0:
188             new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
189          else:
190             new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
191          save_day = day
192       if lead:
193          lead = lead + ' '
194       else:
195          lead = ''
196       new_text.append('''
197 <p class="head">
198    %s<a href="%s">%s</a>.
199 </p>
200 ''' % (lead, href, title))
201
202    if level == 0:
203       years = {}
204       for year, month, day, filename, title, lead in save_titles:
205          years[year] = True
206       first_year = True
207       new_text.append('''
208 <hr>
209
210 <p class="years">
211 ''')
212       for year in sorted(years.keys()):
213          if first_year:
214             first_year = False
215          else:
216             new_text.append(' - ')
217          new_text.append('<a href="%s/">%s</a>' % (year, year))
218       new_text.append('''
219 </p>
220 ''')
221
222    new_text.append("""\
223 #end def
224 $phd_pp_ru.respond(self)
225 """)
226
227    new_text = ''.join(new_text)
228    if old_text <> new_text:
229       print "Writing", index_name
230       index_tmpl = open(index_name, 'w')
231       index_tmpl.write(new_text)
232       index_tmpl.close()
233
234
235 all_titles = []
236 for year in sorted(years.keys()):
237    year_titles = []
238    months = years[year]
239    for month in sorted(months.keys()):
240       month_titles = []
241       for day in sorted(months[month]):
242          day_titles = []
243          key = year, month, day
244          if key in blog:
245             for filename, title, lead in blog[key]:
246                if filename.endswith(".tmpl"):
247                   filename = filename[:-len("tmpl")] + "html"
248                value = (year, month, day, filename, title, lead)
249                all_titles.append(value)
250                year_titles.append(value)
251                month_titles.append(value)
252                day_titles.append(value)
253          write_template(3, year, month, day, day_titles)
254       write_template(2, year, month, day, month_titles)
255    write_template(1, year, month, day, year_titles)
256 write_template(0, year, month, day, all_titles[-20:])