]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
Tags.
[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
104 def write_if_changed(filename, new_text):
105    try:
106       infile = open(filename, 'r')
107       old_text = infile.read()
108       infile.close()
109    except IOError:
110       old_text = None
111
112    if old_text <> new_text:
113       print "Writing", filename
114       outfile = open(filename, 'w')
115       outfile.write(new_text)
116       outfile.close()
117
118
119 def write_template(level, year, month, day, titles):
120    path = []
121    if level >= 1:
122       path.append(year)
123    if level >= 2:
124       path.append(month)
125    if level == 3:
126       path.append(day)
127    path.append("index.tmpl")
128    index_name = os.path.join(*path)
129
130    new_text = ["""\
131 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
132 #extends phd_pp_ru
133 #implements respond
134 """]
135
136    if level == 0:
137       new_text.append("""\
138 #attr $Title = "Oleg BroytMann's blog"
139 #attr $Description = "BroytMann Russian Blog Index Document"
140 #attr $Copyright = %(cyear)s
141 ##
142 #def body_html
143 <H1>Журнал</H1>
144 """ % {"cyear": year or 2005})
145
146    elif level == 1:
147       new_text.append("""\
148 #attr $Title = "Oleg BroytMann's blog: %(year)s"
149 #attr $Description = "BroytMann Russian Blog %(year)s Index Document"
150 #attr $Copyright = %(cyear)s
151 ##
152 #def body_html
153 <H1>Журнал: %(year)s</H1>
154 """ % {"year": year, "cyear": year or 2005})
155
156    elif level == 2:
157       imonth = int(month)
158       new_text.append("""\
159 #attr $Title = "Oleg BroytMann's blog: %(month_abbr_en)s %(year)s"
160 #attr $Description = "BroytMann Russian Blog %(month_name_en)s %(year)s Index Document"
161 #attr $Copyright = %(cyear)s
162 ##
163 #def body_html
164 <H1>Журнал: %(month_name_ru0)s %(year)s</H1>
165 """ % {
166       "year": year, "cyear": year or 2005,
167       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
168       "month_name_ru0": months_names_ru0[imonth],
169    })
170
171    elif level == 3:
172       iday = int(day)
173       imonth = int(month)
174
175       new_text.append("""\
176 #attr $Next = "%s"
177 """ % titles[0][3])
178
179
180       if len(titles) == 1:
181          new_text.append("""\
182 #attr $refresh = "0; URL=%s"
183 """ % titles[0][3])
184
185       new_text.append("""\
186 #attr $Title = "Oleg BroytMann's blog: %(day)d %(month_abbr_en)s %(year)s"
187 #attr $Description = "BroytMann Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
188 #attr $Copyright = %(cyear)s
189 ##
190 #def body_html
191 <H1>Журнал: %(day)d %(month_name_ru0)s %(year)s</H1>
192 """ % {
193       "year": year, "cyear": year or 2005,
194       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
195       "month_name_ru0": months_names_ru0[imonth],
196       "day": iday
197    })
198
199    save_titles = titles[:]
200    titles.reverse()
201
202    save_day = None
203    for year, month, day, file, title, lead in titles:
204       href = []
205       if level == 0:
206          href.append(year)
207       if level <= 1:
208          href.append(month)
209       if level <= 2:
210          href.append(day)
211       href.append(file)
212       href = '/'.join(href)
213       if day[0] == '0': day = day[1:]
214       if save_day <> day:
215          if level == 0:
216             new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
217          else:
218             new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
219          save_day = day
220       if lead:
221          lead = lead + ' '
222       else:
223          lead = ''
224       new_text.append('''
225 <p class="head">
226    %s<a href="%s">%s</a>.
227 </p>
228 ''' % (lead, href, title))
229
230    if level == 0:
231       years = {}
232       for year, month, day, file, title, lead in save_titles:
233          years[year] = True
234       first_year = True
235       new_text.append('''
236 <hr>
237
238 <p class="years">
239 ''')
240       for year in sorted(years.keys()):
241          if first_year:
242             first_year = False
243          else:
244             new_text.append(' - ')
245          new_text.append('<a href="%s/">%s</a>' % (year, year))
246       new_text.append('''
247 </p>
248 ''')
249
250    new_text.append("""\
251 #end def
252 $phd_pp_ru.respond(self)
253 """)
254
255    write_if_changed(index_name, ''.join(new_text))
256
257
258 all_titles = []
259 all_tags = {}
260
261 for year in sorted(years.keys()):
262    year_titles = []
263    months = years[year]
264    for month in sorted(months.keys()):
265       month_titles = []
266       for day in sorted(months[month]):
267          day_titles = []
268          key = year, month, day
269          if key in blog:
270             for file, title, lead, tags in blog[key]:
271                if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
272                value = (year, month, day, file, title, lead)
273                all_titles.append(value)
274                year_titles.append(value)
275                month_titles.append(value)
276                day_titles.append(value)
277                for tag in tags:
278                   if tag in all_tags:
279                      tag_links = all_tags[tag]
280                   else:
281                      tag_links = all_tags[tag] = []
282                   tag_links.append('/'.join(("..", year, month, day, file)))
283          write_template(3, year, month, day, day_titles)
284       write_template(2, year, month, day, month_titles)
285    write_template(1, year, month, day, year_titles)
286 write_template(0, year, month, day, all_titles[-20:])
287
288 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
289 all_tags.sort()
290
291 new_text = ["""\
292 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
293 #extends phd_pp_ru
294 #implements respond
295 #attr $Title = "Oleg BroytMann's blog: tags"
296 #attr $Description = "BroytMann Russian Blog Tags Index Document"
297 #attr $Copyright = 2006
298 ##
299 #def body_html
300 <H1>Теги</H1>
301 """]
302
303 for count, tag, links in all_tags:
304    new_text.append("""
305 <p class="head"><a href="%s.html">%s (%d)</a></p>
306 """ % (tag, tag, count))
307
308    tag_text = ["""\
309 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
310 #extends phd_pp_ru
311 #implements respond
312 #attr $Title = "Oleg BroytMann's blog: tag %s"
313 #attr $Description = "BroytMann Russian Blog Tag %s Index Document"
314 #attr $Copyright = 2006
315 ##
316 #def body_html
317 <H1>%s</H1>
318 """ % (tag, tag, tag)]
319
320    for link in links:
321       junk, year, month, day, filename = link.split('/')
322       tag_text.append("""
323 <p class="head"><a href="%s">%s/%s/%s: %s</a></p>
324 """ % (link, year, month, day, filename))
325
326    tag_text.append("""\
327 #end def
328 $phd_pp_ru.respond(self)
329 """)
330    write_if_changed(os.path.join("tags", tag+".tmpl"), ''.join(tag_text))
331
332 new_text.append("""\
333 #end def
334 $phd_pp_ru.respond(self)
335 """)
336 write_if_changed(os.path.join("tags", "index.tmpl"), ''.join(new_text))