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