]> git.donarmstrong.com Git - lilypond.git/blob - python/auxiliar/postprocess_html.py
Fix 1323 - links "Back to documentation index" in HTML docs
[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/THANKS',
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 <p class="footer_version">
42 %(footer_name_version)s
43 </p>
44 <p class="footer_report">
45 %(footer_report_links)s
46 </p>
47 </div>
48 '''
49
50 web_footer = '''
51 <div class="footer">
52 </div>
53 '''
54
55 footer_name_version = _doc ('This page is for %(package_name)s-%(package_version)s (%(branch_str)s).')
56 # ugh, must not have "_doc" in strings because it is naively replaced with "_" in hacked gettext process
57 footer_report_links = _doc ('Your <a href="%(suggest_Docs_url)s">suggestions for the documentation</a> are welcome, please report errors to our <a href="%(mail_address_url)s">bug list</a>.')
58
59
60 mail_address = 'http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs'
61 suggest_Docs_url = 'http://lilypond.org/web/devel/participating/documentation-adding'
62
63 header_tag = '<!-- header_tag -->'
64 header_tag_re = re.compile (header_tag)
65
66 footer_tag = '<!-- footer_tag -->'
67 footer_tag_re = re.compile (footer_tag)
68
69 lang_available = _doc ("Other languages: %s.")
70 browser_lang = _doc ('About <A HREF="%s">automatic language selection</A>.')
71 browser_language_url = "/web/about/browser-language"
72
73 LANGUAGES_TEMPLATE = '''
74 <p id="languages">
75  %(language_available)s
76  <br>
77  %(browser_language)s
78 </p>
79 '''
80
81
82 html_re = re.compile ('(.*?)(?:[.]([^/.]*))?[.]html$')
83 pages_dict = {}
84
85 def build_pages_dict (filelist):
86     """Build dictionary of available translations of each page"""
87     global pages_dict
88     for f in filelist:
89         m = html_re.match (f)
90         if m:
91             g = m.groups()
92             if len (g) <= 1 or g[1] == None:
93                 e = ''
94             else:
95                 e = g[1]
96             if not g[0] in pages_dict:
97                 pages_dict[g[0]] = [e]
98             else:
99                 pages_dict[g[0]].append (e)
100
101 def source_links_replace (m, source_val):
102     return 'href="' + os.path.join (source_val, m.group (1)) + '"'
103
104 # More hardcoding, yay!
105 splitted_docs_re = re.compile('(Documentation/out-www/(automated-engraving|essay|notation|changes|extending|music-glossary|usage|web|learning|snippets))/')
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 splitted 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     if splitted_docs_re.match (prefix):
118         s = lily_snippets_re.sub ('\\1="../\\2"', s)
119         s = pictures_re.sub ('src="../\\1"', s)
120
121     # we also need to replace in the lsr, which is already processed above!
122     if 'input/' in prefix or 'Documentation/topdocs' in prefix or \
123             'Documentation/contributor' in prefix:
124         # fix the link from the regtest, lsr and topdoc pages to the doc index 
125         # (rewrite prefix to obtain the relative path of the doc index page)
126         rel_link = re.sub (r'out-www/.*$', '', prefix)
127         rel_link = re.sub (r'[^/]*/', '../', rel_link)
128         if 'input/regression' in prefix or 'Documentation/contributor' in prefix:
129             indexfile = "Documentation/devel"
130         else:
131             indexfile = "index"
132         s = docindex_link_re.sub ('href="' + rel_link + indexfile + '.html\"', s)
133     # make the "return to doc index" work with the online website.
134     if target == 'online':
135         if (('Documentation/contributor' in prefix) or
136             is_development_branch):
137             manuals_page = 'development'
138         else:
139             manuals_page = 'manuals'
140         s = manuals_page_link_re.sub (r'href="../../\1website/%s'
141                                       % manuals_page, s)
142     source_path = os.path.join (os.path.dirname (prefix), 'source')
143     if not os.path.islink (source_path):
144         return s
145     source_val = os.readlink (source_path)
146     return re.sub ('href="source/(.*?)"', lambda m: source_links_replace (m, source_val), s)
147
148 body_tag_re = re.compile ('(?i)<body([^>]*)>')
149 html_tag_re = re.compile ('(?i)<html>')
150 doctype_re = re.compile ('(?i)<!DOCTYPE')
151 doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
152 css_re = re.compile ('(?i)<link rel="stylesheet" type="text/css" ([^>]*)href="[^">]*?lilypond.*\.css"([^>]*)>')
153 end_head_tag_re = re.compile ('(?i)</head>')
154 css_link = """    <link rel="stylesheet" type="text/css" title="Patrick McCarty's design" href="%(rel)sDocumentation/lilypond-mccarty.css">
155     <link rel="alternate stylesheet" type="text/css" href="%(rel)sDocumentation/lilypond.css" title="Andrew Hawryluk's design">
156     <link rel="alternate stylesheet" type="text/css" href="%(rel)sDocumentation/lilypond-blue.css" title="Kurt Kroon's blue design">
157     <!--[if lte IE 7]>
158     <link href="%(rel)sDocumentation/lilypond-ie-fixes.css" rel="stylesheet" type="text/css">
159     <![endif]-->
160 """
161
162
163 def add_header (s, prefix):
164     """Add header (<body>, doctype and CSS)"""
165     if header_tag_re.search (s) == None:
166         body = '<body\\1>'
167         (s, n) = body_tag_re.subn (body + header, s, 1)
168         if not n:
169             (s, n) = html_tag_re.subn ('<html>' + header, s, 1)
170             if not n:
171                 s = header + s
172
173         if doctype_re.search (s) == None:
174             s = doctype + header_tag + '\n' + s
175
176         if css_re.search (s) == None:
177             depth = (prefix.count ('/') - 1) * '../'
178             s = end_head_tag_re.sub ((css_link % {'rel': depth}) + '</head>', s)
179     return s
180
181 title_tag_re = re.compile ('.*?<title>(.*?)</title>', re.DOTALL)
182 AT_web_title_re = re.compile ('@WEB-TITLE@')
183
184 def add_title (s):
185     # urg
186     # maybe find first node?
187     fallback_web_title = '-- --'
188     m = title_tag_re.match (s)
189     if m:
190         fallback_web_title = m.group (1)
191     s = AT_web_title_re.sub (fallback_web_title, s)
192     return s
193
194 footer_insert_re = re.compile ('<!--\s*FOOTER\s*-->')
195 end_body_re = re.compile ('(?i)</body>')
196 end_html_re = re.compile ('(?i)</html>')
197
198 def add_footer (s, footer_text):
199     """add footer"""
200     (s, n) = footer_insert_re.subn (footer_text + '\n' + '<!-- FOOTER -->', s, 1)
201     if not n:
202         (s, n) = end_body_re.subn (footer_text + '\n' + '</body>', s, 1)
203     if not n:
204         (s, n) = end_html_re.subn (footer_text + '\n' + '</html>', s, 1)
205     if not n:
206         s += footer_text + '\n'
207     return s
208
209 def find_translations (prefix, lang_ext):
210     """find available translations of a page"""
211     available = []
212     missing = []
213     for l in langdefs.LANGUAGES:
214         e = l.webext
215         if lang_ext != e:
216             if e in pages_dict[prefix]:
217                 available.append (l)
218             elif lang_ext == '' and l.enabled and reduce (operator.and_,
219                                                           [not prefix.startswith (s)
220                                                            for s in non_copied_pages]):
221                 # English version of missing translated pages will be written
222                 missing.append (e)
223     return available, missing
224
225 online_links_re = re.compile ('''(href|src)=['"]\
226 ((?!Compiling-from-source.html")[^/][.]*[^.:'"]*)\
227 ([.]html)(#[^"']*|)['"]''')
228 offline_links_re = re.compile ('href=[\'"]\
229 ((?!Compiling-from-source.html")(?![.]{2}/contributor)[^/][.]*[^.:\'"]*)([.]html)(#[^"\']*|)[\'"]')
230 big_page_name_re = re.compile ('''(.+?)-big-page''')
231
232 def process_i18n_big_page_links (match, prefix, lang_ext):
233     big_page_name = big_page_name_re.match (match.group (1))
234     if big_page_name:
235         destination_path = os.path.normpath (os.path.join (os.path.dirname (prefix),
236                                                            big_page_name.group (0)))
237         if not (destination_path in pages_dict and
238                 lang_ext in pages_dict[destination_path]):
239             return match.group (0)
240     return 'href="' + match.group (1) + '.' + lang_ext \
241         + match.group (2) + match.group (3) + '"'
242
243 def process_links (s, prefix, lang_ext, file_name, missing, target):
244     page_flavors = {}
245     if target == 'online':
246         # Strip .html, suffix for auto language selection (content
247         # negotiation).  The menu must keep the full extension, so do
248         # this before adding the menu.
249         page_flavors[file_name] = \
250             [lang_ext, online_links_re.sub ('\\1="\\2\\4"', s)]
251     elif target == 'offline':
252         # in LANG doc index: don't rewrite .html suffixes
253         # as not all .LANG.html pages exist;
254         # the doc index should be translated and contain links with the right suffixes
255         # idem for NEWS
256         if prefix in ('Documentation/out-www/index', 'Documentation/topdocs/out-www/NEWS'):
257             page_flavors[file_name] = [lang_ext, s]
258         elif lang_ext == '':
259             page_flavors[file_name] = [lang_ext, s]
260             for e in missing:
261                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = \
262                     [e, offline_links_re.sub ('href="\\1.' + e + '\\2\\3"', s)]
263         else:
264             # For saving bandwidth and disk space, we don't duplicate big pages
265             # in English, so we must process translated big pages links differently.
266             if 'big-page' in prefix:
267                 page_flavors[file_name] = \
268                     [lang_ext,
269                      offline_links_re.sub \
270                          (lambda match: process_i18n_big_page_links (match, prefix, lang_ext),
271                           s)]
272             else:
273                 page_flavors[file_name] = \
274                     [lang_ext,
275                      offline_links_re.sub ('href="\\1.' + lang_ext + '\\2\\3"', s)]
276     return page_flavors
277
278 def add_menu (page_flavors, prefix, available, target, translation):
279     for k in page_flavors:
280         language_menu = ''
281         languages = ''
282         if page_flavors[k][0] != '':
283             t = translation[page_flavors[k][0]]
284         else:
285             t = _doc
286         for lang in available:
287             lang_file = lang.file_name (os.path.basename (prefix), '.html')
288             if language_menu != '':
289                 language_menu += ', '
290             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
291         if target == 'offline':
292             browser_language = ''
293         elif target == 'online':
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             in_f = open (file_name)
350             s = in_f.read()
351             in_f.close()
352
353             s = s.replace ('%', '%%')
354             s = hack_urls (s, prefix, target, bool (int (versiontup[1]) %  2))
355             s = add_header (s, prefix)
356
357             ### add footer
358             if footer_tag_re.search (s) == None:
359                 if 'web' in file_name:
360                     s = add_footer (s, footer_tag + web_footer)
361                 else:
362                     s = add_footer (s, footer_tag + footer)
363
364                 available, missing = find_translations (prefix, lang_ext)
365                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
366                 # Add menu after stripping: must not have autoselection for language menu.
367                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
368             for k in page_flavors:
369                 page_flavors[k][1] = page_flavors[k][1] % subst[page_flavors[k][0]]
370                 out_f = open (name_filter (k), 'w')
371                 out_f.write (page_flavors[k][1])
372                 out_f.close()
373         # if the page is translated, a .en.html symlink is necessary for content negotiation
374         if target == 'online' and ext_list != ['']:
375             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))