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