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