]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
Generate news templates from text source files.
[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
34 # (year, month, day) => [list of (file, title, lead, tags)]
35
36 blog = {}
37 years = {}
38
39 # Walk the directory recursively
40 for dirpath, dirs, files in os.walk(os.curdir):
41    d = os.path.basename(dirpath)
42    if not d.startswith("20") and not d.isdigit():
43       continue
44    for file in files:
45       # Ignore index.tmpl and *.html files; supose all other files are *.tmpl
46       if file == "index.tmpl" or file.endswith(".html"):
47          continue
48       fullpath = os.path.join(dirpath, file)
49       template = Template(file=fullpath)
50       title_parts = template.Title.split()
51       title = ' '.join(title_parts[6:])
52       lead = getattr(template, "Lead", None)
53
54       tags = getattr(template, "Tag", None)
55       if isinstance(tags, basestring):
56          tags = (tags,)
57
58       if title:
59          key = year, month, day = tuple(dirpath.split(os.sep)[1:])
60          if key in blog:
61             days = blog[key]
62          else:
63             days = blog[key] = []
64          days.append((file, title, lead, tags))
65
66          if year in years:
67             months = years[year]
68          else:
69             months = years[year] = {}
70
71          if month in months:
72             days = months[month]
73          else:
74             days = months[month] = []
75
76          if day not in days: days.append(day)
77
78
79 # Need to save the blog?
80 if blog <> old_blog:
81    blog_file = open(blog_filename, "wb")
82    pickle.dump(blog, blog_file, pickle.HIGHEST_PROTOCOL)
83    blog_file.close()
84
85
86 # Localized month names
87
88 import locale
89 locale.setlocale(locale.LC_ALL, '')
90 from calendar import _localized_day, _localized_month
91
92 locale.setlocale(locale.LC_TIME, 'C')
93 months_names_en = list(_localized_month('%B'))
94 months_abbrs_en = list(_localized_month('%b'))
95
96 locale.setlocale(locale.LC_TIME, '')
97 months_names_ru = [month.lower() for month in _localized_month('%B')]
98
99 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
100    "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
101 ]
102
103 from news import write_if_changed
104
105
106 def write_template(level, year, month, day, titles, tags=None):
107    path = []
108    if level >= 1:
109       path.append(year)
110    if level >= 2:
111       path.append(month)
112    if level == 3:
113       path.append(day)
114    path.append("index.tmpl")
115    index_name = os.path.join(*path)
116
117    new_text = ["""\
118 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
119 #extends phd_pp_ru
120 #implements respond
121 """]
122
123    if level == 0:
124       new_text.append("""\
125 #attr $Title = "Oleg BroytMann's blog"
126 #attr $Description = "BroytMann Russian Blog Index Document"
127 #attr $Copyright = %(cyear)s
128 ##
129 #def body_html
130 <H1>Журнал</H1>
131 """ % {"cyear": year or 2005})
132
133    elif level == 1:
134       new_text.append("""\
135 #attr $Title = "Oleg BroytMann's blog: %(year)s"
136 #attr $Description = "BroytMann Russian Blog %(year)s Index Document"
137 #attr $Copyright = %(cyear)s
138 ##
139 #def body_html
140 <H1>Журнал: %(year)s</H1>
141 """ % {"year": year, "cyear": year or 2005})
142
143    elif level == 2:
144       imonth = int(month)
145       new_text.append("""\
146 #attr $Title = "Oleg BroytMann's blog: %(month_abbr_en)s %(year)s"
147 #attr $Description = "BroytMann Russian Blog %(month_name_en)s %(year)s Index Document"
148 #attr $Copyright = %(cyear)s
149 ##
150 #def body_html
151 <H1>Журнал: %(month_name_ru0)s %(year)s</H1>
152 """ % {
153       "year": year, "cyear": year or 2005,
154       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
155       "month_name_ru0": months_names_ru0[imonth],
156    })
157
158    elif level == 3:
159       iday = int(day)
160       imonth = int(month)
161
162       new_text.append("""\
163 #attr $Next = "%s"
164 """ % titles[0][3])
165
166
167       if len(titles) == 1:
168          new_text.append("""\
169 #attr $refresh = "0; URL=%s"
170 """ % titles[0][3])
171
172       new_text.append("""\
173 #attr $Title = "Oleg BroytMann's blog: %(day)d %(month_abbr_en)s %(year)s"
174 #attr $Description = "BroytMann Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
175 #attr $Copyright = %(cyear)s
176 ##
177 #def body_html
178 <H1>Журнал: %(day)d %(month_name_ru0)s %(year)s</H1>
179 """ % {
180       "year": year, "cyear": year or 2005,
181       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
182       "month_name_ru0": months_names_ru0[imonth],
183       "day": iday
184    })
185
186    save_titles = titles[:]
187    titles.reverse()
188
189    save_day = None
190    for year, month, day, file, title, lead in titles:
191       href = []
192       if level == 0:
193          href.append(year)
194       if level <= 1:
195          href.append(month)
196       if level <= 2:
197          href.append(day)
198       href.append(file)
199       href = '/'.join(href)
200       if day[0] == '0': day = day[1:]
201       if save_day <> day:
202          if level == 0:
203             new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
204          else:
205             new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
206          save_day = day
207       if lead:
208          lead = lead + ' '
209       else:
210          lead = ''
211       new_text.append('''
212 <p class="head">
213    %s<a href="%s">%s</a>.
214 </p>
215 ''' % (lead, href, title))
216
217    if level == 0:
218       years = {}
219       for year, month, day, file, title, lead in save_titles:
220          years[year] = True
221       new_text.append('''
222 <hr>
223
224 <p class="noindent"><a href="tags/">Теги</a>:
225 ''')
226       first_tag = True
227       for count, tag, links in all_tags:
228          if first_tag:
229             first_tag = False
230          else:
231             new_text.append(' - ')
232          new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
233       new_text.append('''
234 </p>
235 ''')
236
237       new_text.append('''
238 <p class="noindent">По годам:
239 ''')
240       first_year = True
241       for year in sorted(years.keys()):
242          if first_year:
243             first_year = False
244          else:
245             new_text.append(' - ')
246          new_text.append('<a href="%s/">%s</a>' % (year, year))
247       new_text.append('''
248 </p>
249 ''')
250
251    new_text.append("""\
252 #end def
253 $phd_pp_ru.respond(self)
254 """)
255
256    write_if_changed(index_name, ''.join(new_text))
257
258
259 all_titles = []
260 all_tags = {}
261
262 for year in sorted(years.keys()):
263    year_titles = []
264    months = years[year]
265    for month in sorted(months.keys()):
266       month_titles = []
267       for day in sorted(months[month]):
268          day_titles = []
269          key = year, month, day
270          if key in blog:
271             for file, title, lead, tags in blog[key]:
272                if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
273                value = (year, month, day, file, title, lead)
274                all_titles.append(value)
275                year_titles.append(value)
276                month_titles.append(value)
277                day_titles.append(value)
278                for tag in tags:
279                   if tag in all_tags:
280                      tag_links = all_tags[tag]
281                   else:
282                      tag_links = all_tags[tag] = []
283                   tag_links.append(value)
284          write_template(3, year, month, day, day_titles)
285       write_template(2, year, month, day, month_titles)
286    write_template(1, year, month, day, year_titles)
287
288 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
289 all_tags.sort()
290
291 write_template(0, year, month, day, all_titles[-20:], all_tags)
292
293 new_text = ["""\
294 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
295 #extends phd_pp_ru
296 #implements respond
297 #attr $Title = "Oleg BroytMann's blog: tags"
298 #attr $Description = "BroytMann Russian Blog Tags Index Document"
299 #attr $Copyright = 2006
300 ##
301 #def body_html
302 <H1>Теги</H1>
303
304 <p class="head">
305 <dl>
306 """]
307
308 for count, tag, links in all_tags:
309    new_text.append("""\
310    <dt><a href="%s.html">%s (%d)</a></dt>
311 """ % (tag, tag, count))
312
313    tag_text = ["""\
314 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
315 #extends phd_pp_ru
316 #implements respond
317 #attr $Title = "Oleg BroytMann's blog: tag %s"
318 #attr $Description = "BroytMann Russian Blog Tag %s Index Document"
319 #attr $Copyright = 2006
320 ##
321 #def body_html
322 <H1>%s</H1>
323
324 <p class="head">
325 <ul>
326 """ % (tag, tag, tag)]
327
328    count = 0
329    for year, month, day, filename, title, lead in reversed(links):
330       if lead:
331          lead = lead + ' '
332       else:
333          lead = ''
334       link = "../%s/%s/%s/%s" % (year, month, day, filename)
335       item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead, title)
336
337       count += 1
338       if count <= 5:
339          new_text.append("      <dd>%s</dd>\n" % item_text)
340
341       tag_text.append("   %s\n" % item_text)
342
343    tag_text.append("""\
344 </ul>
345 </p>
346 #end def
347 $phd_pp_ru.respond(self)
348 """)
349    write_if_changed(os.path.join("tags", tag+".tmpl"), ''.join(tag_text))
350
351 new_text.append("""\
352 </dl>
353 </p>
354 #end def
355 $phd_pp_ru.respond(self)
356 """)
357 write_if_changed(os.path.join("tags", "index.tmpl"), ''.join(new_text))