]> git.donarmstrong.com Git - lilypond.git/blob - python/auxiliar/postprocess_html.py
fd254b5a08411acf4abbb668dcd05b9c710d760a
[lilypond.git] / python / auxiliar / postprocess_html.py
1 #!@PYTHON@
2
3 """
4 Postprocess HTML files:
5 add footer, tweak links, add language selection menu.
6 """
7 import re
8 import os
9 import time
10 import operator
11
12 import langdefs
13
14 # This is to try to make the docball not too big with almost duplicate files
15 # see process_links()
16 non_copied_pages = ['Documentation/out-www/notation-big-page',
17                     'Documentation/out-www/internals-big-page',
18                     'Documentation/out-www/learning-big-page',
19                     'Documentation/out-www/usage-big-page',
20                     'Documentation/out-www/music-glossary-big-page',
21                     'Documentation/out-www/contributor',
22                     'Documentation/out-www/changes-big-page',
23                     'Documentation/out-www/essay-big-page',
24                     'Documentation/out-www/extending-big-page',
25                     'Documentation/out-www/snippets',
26                     'out-www/examples',
27                     'Documentation/topdocs',
28                     'Documentation/bibliography',
29                     'Documentation/out-www/DEDICATION',
30                     'input/']
31
32 def _doc (s):
33     return s
34
35 header = r"""
36 """
37
38 footer = '''
39 <div class="footer">
40 <p class="footer_version">
41 %(footer_name_version)s
42 </p>
43 <p class="footer_report">
44 %(footer_report_links)s
45 </p>
46 </div>
47 '''
48
49 web_footer = '''
50 <div class="footer">
51 </div>
52 '''
53
54 footer_name_version = _doc ('This page is for %(package_name)s-%(package_version)s (%(branch_str)s).')
55 # ugh, must not have "_doc" in strings because it is naively replaced with "_" in hacked gettext process
56 footer_report_links = _doc ('We welcome your aid; please <a href="%(help_us_url)s">help us</a> by reporting errors to our <a href="%(mail_address_url)s">bug list</a>.')
57
58
59 mail_address = 'http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs'
60 help_us_url = 'http://lilypond.org/help-us.html'
61
62 header_tag = '<!-- header_tag -->'
63 header_tag_re = re.compile (header_tag)
64
65 footer_tag = '<!-- footer_tag -->'
66 footer_tag_re = re.compile (footer_tag)
67
68 lang_available = _doc ("Other languages: %s.")
69 browser_lang = _doc ('About <a href="%s">automatic language selection</a>.')
70 browser_language_url = "http://www.lilypond.org/website/misc/browser-language"
71
72 LANGUAGES_TEMPLATE = '''
73 <p id="languages">
74  %(language_available)s
75  <br>
76  %(browser_language)s
77 </p>
78 '''
79
80
81 html_re = re.compile ('(.*?)(?:[.]([^/.]*))?[.]html$')
82 pages_dict = {}
83
84 def build_pages_dict (filelist):
85     """Build dictionary of available translations of each page"""
86     global pages_dict
87     for f in filelist:
88         m = html_re.match (f)
89         if m:
90             g = m.groups()
91             if len (g) <= 1 or g[1] == None:
92                 e = ''
93             else:
94                 e = g[1]
95             if not g[0] in pages_dict:
96                 pages_dict[g[0]] = [e]
97             else:
98                 pages_dict[g[0]].append (e)
99
100 def source_links_replace (m, source_val):
101     return 'href="' + os.path.join (source_val, m.group (1)) + '"'
102
103 # More hardcoding, yay!
104 split_docs_re = re.compile('(Documentation/out-www/(automated-engraving|essay|notation|changes|extending|music-glossary|usage|web|learning|snippets|contributor))/')
105 lily_examples_re = re.compile ('(href|src)="(ly-examples/.*?)"')
106 lily_snippets_re = re.compile ('(href|src)="([0-9a-f]{2}/lily-.*?)"')
107 pictures_re = re.compile ('src="(pictures/.*?)"')
108
109 docindex_link_re = re.compile (r'href="index.html"')
110 manuals_page_link_re = re.compile (r'href="((?:\.\./)+)Documentation/web/manuals')
111
112 ## Windows does not support symlinks.
113 # This function avoids creating symlinks for split HTML manuals
114 # Get rid of symlinks in GNUmakefile.in (local-WWW-post)
115 # this also fixes missing PNGs only present in translated docs
116 def hack_urls (s, prefix, target, is_development_branch):
117     depth = (prefix.count ('/') - 1) * '../'
118     # fix css links
119     s = css_re.sub ('<link \\1href="%(rel)sDocumentation/css/\\2"\\3>' % {'rel': depth}, s)
120     # fix image links
121     if split_docs_re.match (prefix):
122         s = lily_examples_re.sub ('\\1="../\\2"', s)
123         s = lily_snippets_re.sub ('\\1="../\\2"', s)
124         s = pictures_re.sub ('src="../\\1"', s)
125
126     # we also need to replace in the lsr, which is already processed above!
127     if 'input/' in prefix or 'Documentation/topdocs' in prefix or \
128             'Documentation/contributor' in prefix:
129         # fix the link from the regtest, lsr and topdoc pages to the doc index 
130         # (rewrite prefix to obtain the relative path of the doc index page)
131         rel_link = re.sub (r'out-www/.*$', '', prefix)
132         rel_link = re.sub (r'[^/]*/', '../', rel_link)
133         if 'input/regression' in prefix or 'Documentation/contributor' in prefix:
134             indexfile = "Documentation/devel"
135         else:
136             indexfile = "index"
137         s = docindex_link_re.sub ('href="' + rel_link + indexfile + '.html\"', s)
138     # make the "return to doc index" work with the online website.
139     if target == 'online':
140         if (('Documentation/contributor' in prefix) or
141             is_development_branch):
142             manuals_page = 'development'
143         else:
144             manuals_page = 'manuals'
145         s = manuals_page_link_re.sub (r'href="../../\1website/%s'
146                                       % manuals_page, s)
147     source_path = os.path.join (os.path.dirname (prefix), 'source')
148     if not os.path.islink (source_path):
149         return s
150     source_val = os.readlink (source_path)
151     return re.sub ('href="source/(.*?)"', lambda m: source_links_replace (m, source_val), s)
152
153 body_tag_re = re.compile ('(?i)<body([^>]*)>')
154 html_tag_re = re.compile ('(?i)<html>')
155 doctype_re = re.compile ('(?i)<!DOCTYPE')
156 doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
157 css_re = re.compile ('(?i)<link ([^>]*)href="[^">]*?(lilypond.*\.css)"([^>]*)>')
158 end_head_tag_re = re.compile ('(?i)</head>')
159 css_link = """    <link rel="stylesheet" type="text/css" title="Default design" href="%(rel)sDocumentation/css/lilypond-manuals.css">
160     <!--[if lte IE 7]>
161     <link href="%(rel)sDocumentation/css/lilypond-ie-fixes.css" rel="stylesheet" type="text/css">
162     <![endif]-->
163 """
164
165
166 def add_header (s, prefix):
167     """Add header (<body>, doctype and CSS)"""
168     if header_tag_re.search (s) == None:
169         body = '<body\\1>'
170         (s, n) = body_tag_re.subn (body + header, s, 1)
171         if not n:
172             (s, n) = html_tag_re.subn ('<html>' + header, s, 1)
173             if not n:
174                 s = header + s
175
176         if doctype_re.search (s) == None:
177             s = doctype + header_tag + '\n' + s
178
179         if css_re.search (s) == None:
180             depth = (prefix.count ('/') - 1) * '../'
181             s = end_head_tag_re.sub ((css_link % {'rel': depth}) + '</head>', s)
182     return s
183
184 title_tag_re = re.compile ('.*?<title>(.*?)</title>', re.DOTALL)
185 AT_web_title_re = re.compile ('@WEB-TITLE@')
186
187 def add_title (s):
188     # urg
189     # maybe find first node?
190     fallback_web_title = '-- --'
191     m = title_tag_re.match (s)
192     if m:
193         fallback_web_title = m.group (1)
194     s = AT_web_title_re.sub (fallback_web_title, s)
195     return s
196
197 footer_insert_re = re.compile ('<!--\s*FOOTER\s*-->')
198 end_body_re = re.compile ('(?i)</body>')
199 end_html_re = re.compile ('(?i)</html>')
200
201 def add_footer (s, footer_text):
202     """add footer"""
203     (s, n) = footer_insert_re.subn (footer_text + '\n' + '<!-- FOOTER -->', s, 1)
204     if not n:
205         (s, n) = end_body_re.subn (footer_text + '\n' + '</body>', s, 1)
206     if not n:
207         (s, n) = end_html_re.subn (footer_text + '\n' + '</html>', s, 1)
208     if not n:
209         s += footer_text + '\n'
210     return s
211
212 def find_translations (prefix, lang_ext):
213     """find available translations of a page"""
214     available = []
215     missing = []
216     for l in langdefs.LANGUAGES:
217         e = l.webext
218         if lang_ext != e:
219             if e in pages_dict[prefix]:
220                 available.append (l)
221             elif lang_ext == '' and l.enabled and reduce (operator.and_,
222                                                           [not prefix.startswith (s)
223                                                            for s in non_copied_pages]):
224                 # English version of missing translated pages will be written
225                 missing.append (e)
226     return available, missing
227
228 online_links_re = re.compile ('''(href|src)=['"]\
229 ((?!Compiling-from-source.html")[^/][.]*[^.:'"]*)\
230 ([.]html)(#[^"']*|)['"]''')
231 offline_links_re = re.compile ('href=[\'"]\
232 ((?!Compiling-from-source.html")(?![.]{2}/contributor)[^/][.]*[^.:\'"]*)([.]html)(#[^"\']*|)[\'"]')
233 big_page_name_re = re.compile ('''(.+?)-big-page''')
234
235 def process_i18n_big_page_links (match, prefix, lang_ext):
236     big_page_name = big_page_name_re.match (match.group (1))
237     if big_page_name:
238         destination_path = os.path.normpath (os.path.join (os.path.dirname (prefix),
239                                                            big_page_name.group (0)))
240         if not (destination_path in pages_dict and
241                 lang_ext in pages_dict[destination_path]):
242             return match.group (0)
243     return 'href="' + match.group (1) + '.' + lang_ext \
244         + match.group (2) + match.group (3) + '"'
245
246 def process_links (s, prefix, lang_ext, file_name, missing, target):
247     page_flavors = {}
248     if target == 'online':
249         # Strip .html, suffix for auto language selection (content
250         # negotiation).  The menu must keep the full extension, so do
251         # this before adding the menu.
252         page_flavors[file_name] = \
253             [lang_ext, online_links_re.sub ('\\1="\\2\\4"', s)]
254     elif target == 'offline':
255         # in LANG doc index: don't rewrite .html suffixes
256         # as not all .LANG.html pages exist;
257         # the doc index should be translated and contain links with the right suffixes
258         # idem for NEWS
259         if prefix in ('Documentation/out-www/index', 'Documentation/topdocs/out-www/NEWS'):
260             page_flavors[file_name] = [lang_ext, s]
261         elif lang_ext == '':
262             page_flavors[file_name] = [lang_ext, s]
263             for e in missing:
264                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = \
265                     [e, offline_links_re.sub ('href="\\1.' + e + '\\2\\3"', s)]
266         else:
267             # For saving bandwidth and disk space, we don't duplicate big pages
268             # in English, so we must process translated big pages links differently.
269             if 'big-page' in prefix:
270                 page_flavors[file_name] = \
271                     [lang_ext,
272                      offline_links_re.sub \
273                          (lambda match: process_i18n_big_page_links (match, prefix, lang_ext),
274                           s)]
275             else:
276                 page_flavors[file_name] = \
277                     [lang_ext,
278                      offline_links_re.sub ('href="\\1.' + lang_ext + '\\2\\3"', s)]
279     return page_flavors
280
281 def add_menu (page_flavors, prefix, available, target, translation):
282     for k in page_flavors:
283         language_menu = ''
284         languages = ''
285         if page_flavors[k][0] != '':
286             t = translation[page_flavors[k][0]]
287         else:
288             t = _doc
289         for lang in available:
290             lang_file = lang.file_name (os.path.basename (prefix), '.html')
291             if language_menu != '':
292                 language_menu += ', '
293             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
294         browser_language = t (browser_lang) % browser_language_url
295         if language_menu:
296             language_available = t (lang_available) % language_menu
297             languages = LANGUAGES_TEMPLATE % vars ()
298         page_flavors[k][1] = add_footer (page_flavors[k][1], languages)
299     return page_flavors
300
301
302 def process_html_files (package_name = '',
303                         package_version = '',
304                         target = 'offline',
305                         name_filter = lambda s: s):
306     """Add header, footer and tweak links to a number of HTML files
307
308     Arguments:
309      package_name=NAME         set package_name to NAME
310      package_version=VERSION   set package version to VERSION
311      targets=offline|online    set page processing depending on the target
312           offline is for reading HTML pages locally
313           online is for hosting the HTML pages on a website with content
314             negotiation
315      name_filter               a HTML file name filter
316     """
317     translation = langdefs.translation
318     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
319
320     if "http://" in mail_address:
321         mail_address_url = mail_address
322     else:
323         mail_address_url= 'mailto:' + mail_address
324
325     versiontup = package_version.split ('.')
326     branch_str = _doc ('stable-branch')
327     if int (versiontup[1]) %  2:
328         branch_str = _doc ('development-branch')
329
330     # Initialize dictionaries for string formatting
331     subst = {}
332     subst[''] = dict ([i for i in globals ().items() if type (i[1]) is str])
333     subst[''].update (dict ([i for i in locals ().items() if type (i[1]) is str]))
334     for l in translation:
335         e = langdefs.LANGDICT[l].webext
336         if e:
337             subst[e] = {}
338             for name in subst['']:
339                 subst[e][name] = translation[l] (subst[''][name])
340     # Do deeper string formatting as early as possible,
341     # so only one '%' formatting pass is needed later
342     for e in subst:
343         subst[e]['footer_name_version'] = subst[e]['footer_name_version'] % subst[e]
344         subst[e]['footer_report_links'] = subst[e]['footer_report_links'] % subst[e]
345
346     for prefix, ext_list in pages_dict.items ():
347         for lang_ext in ext_list:
348             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
349             source_time = os.path.getmtime(file_name)
350             dest_time = 0
351             if os.path.exists(name_filter(file_name)):
352                 dest_time = os.path.getmtime(name_filter(file_name))
353             if dest_time < source_time:
354
355                 in_f = open (file_name)
356                 s = in_f.read()
357                 in_f.close()
358
359                 s = s.replace ('%', '%%')
360                 s = hack_urls (s, prefix, target, bool (int (versiontup[1]) %  2))
361                 s = add_header (s, prefix)
362
363                 ### add footer
364                 if footer_tag_re.search (s) == None:
365                     if 'web' in file_name:
366                         s = add_footer (s, footer_tag + web_footer)
367                     else:
368                         s = add_footer (s, footer_tag + footer)
369
370                     available, missing = find_translations (prefix, lang_ext)
371                     page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
372                     # Add menu after stripping: must not have autoselection for language menu.
373                     page_flavors = add_menu (page_flavors, prefix, available, target, translation)
374                 for k in page_flavors:
375                     page_flavors[k][1] = page_flavors[k][1] % subst[page_flavors[k][0]]
376                     out_f = open (name_filter (k), 'w')
377                     out_f.write (page_flavors[k][1])
378                     out_f.close()
379         # if the page is translated, a .en.html symlink is necessary for content negotiation
380         if target == 'online' and ext_list != [''] and not os.path.lexists (name_filter (prefix + '.en.html')):
381             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))