]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
If there is only one entry for the day - redirect from day index to the entry.
[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       if len(titles) == 1:
158          new_text.append("""\
159 #attr $refresh = "0; URL=%s"
160 """ % titles[0][3])
161
162       new_text.append("""\
163 #attr $Title = "Oleg BroytMann's blog: %(day)d %(month_abbr_en)s %(year)s"
164 #attr $Description = "BroytMann Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
165 #attr $Copyright = %(cyear)s
166 ##
167 #def body_html
168 <H1>Журнал: %(day)d %(month_name_ru0)s %(year)s</H1>
169 """ % {
170       "year": year, "cyear": year or 2005,
171       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
172       "month_name_ru0": months_names_ru0[imonth],
173       "day": iday
174    })
175
176    save_titles = titles[:]
177    titles.reverse()
178
179    save_day = None
180    for year, month, day, filename, title, lead in titles:
181       href = []
182       if level == 0:
183          href.append(year)
184       if level <= 1:
185          href.append(month)
186       if level <= 2:
187          href.append(day)
188       href.append(filename)
189       href = '/'.join(href)
190       if day[0] == '0': day = day[1:]
191       if save_day <> day:
192          if level == 0:
193             new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
194          else:
195             new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
196          save_day = day
197       if lead:
198          lead = lead + ' '
199       else:
200          lead = ''
201       new_text.append('''
202 <p class="head">
203    %s<a href="%s">%s</a>.
204 </p>
205 ''' % (lead, href, title))
206
207    if level == 0:
208       years = {}
209       for year, month, day, filename, title, lead in save_titles:
210          years[year] = True
211       first_year = True
212       new_text.append('''
213 <hr>
214
215 <p class="years">
216 ''')
217       for year in sorted(years.keys()):
218          if first_year:
219             first_year = False
220          else:
221             new_text.append(' - ')
222          new_text.append('<a href="%s/">%s</a>' % (year, year))
223       new_text.append('''
224 </p>
225 ''')
226
227    new_text.append("""\
228 #end def
229 $phd_pp_ru.respond(self)
230 """)
231
232    new_text = ''.join(new_text)
233    if old_text <> new_text:
234       print "Writing", index_name
235       index_tmpl = open(index_name, 'w')
236       index_tmpl.write(new_text)
237       index_tmpl.close()
238
239
240 all_titles = []
241 for year in sorted(years.keys()):
242    year_titles = []
243    months = years[year]
244    for month in sorted(months.keys()):
245       month_titles = []
246       for day in sorted(months[month]):
247          day_titles = []
248          key = year, month, day
249          if key in blog:
250             for filename, title, lead in blog[key]:
251                if filename.endswith(".tmpl"):
252                   filename = filename[:-len("tmpl")] + "html"
253                value = (year, month, day, filename, title, lead)
254                all_titles.append(value)
255                year_titles.append(value)
256                month_titles.append(value)
257                day_titles.append(value)
258          write_template(3, year, month, day, day_titles)
259       write_template(2, year, month, day, month_titles)
260    write_template(1, year, month, day, year_titles)
261 write_template(0, year, month, day, all_titles[-20:])