]> git.donarmstrong.com Git - lilypond.git/blob - python/auxiliar/postprocess_html.py
Merge remote branch 'origin' into release/unstable
[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 ('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>.')
58
59
60 mail_address = 'http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs'
61 help_us_url = 'http://lilypond.org/help-us.html'
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 split_docs_re = re.compile('(Documentation/out-www/(automated-engraving|essay|notation|changes|extending|music-glossary|usage|web|learning|snippets|contributor))/')
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     if split_docs_re.match (prefix):
121         s = lily_snippets_re.sub ('\\1="../\\2"', s)
122         s = pictures_re.sub ('src="../\\1"', s)
123
124     # we also need to replace in the lsr, which is already processed above!
125     if 'input/' in prefix or 'Documentation/topdocs' in prefix or \
126             'Documentation/contributor' in prefix:
127         # fix the link from the regtest, lsr and topdoc pages to the doc index 
128         # (rewrite prefix to obtain the relative path of the doc index page)
129         rel_link = re.sub (r'out-www/.*$', '', prefix)
130         rel_link = re.sub (r'[^/]*/', '../', rel_link)
131         if 'input/regression' in prefix or 'Documentation/contributor' in prefix:
132             indexfile = "Documentation/devel"
133         else:
134             indexfile = "index"
135         s = docindex_link_re.sub ('href="' + rel_link + indexfile + '.html\"', s)
136     # make the "return to doc index" work with the online website.
137     if target == 'online':
138         if (('Documentation/contributor' in prefix) or
139             is_development_branch):
140             manuals_page = 'development'
141         else:
142             manuals_page = 'manuals'
143         s = manuals_page_link_re.sub (r'href="../../\1website/%s'
144                                       % manuals_page, s)
145     source_path = os.path.join (os.path.dirname (prefix), 'source')
146     if not os.path.islink (source_path):
147         return s
148     source_val = os.readlink (source_path)
149     return re.sub ('href="source/(.*?)"', lambda m: source_links_replace (m, source_val), s)
150
151 body_tag_re = re.compile ('(?i)<body([^>]*)>')
152 html_tag_re = re.compile ('(?i)<html>')
153 doctype_re = re.compile ('(?i)<!DOCTYPE')
154 doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
155 css_re = re.compile ('(?i)<link ([^>]*)href="[^">]*?(lilypond.*\.css)"([^>]*)>')
156 end_head_tag_re = re.compile ('(?i)</head>')
157 css_link = """    <link rel="stylesheet" type="text/css" title="Default design" href="%(rel)sDocumentation/css/lilypond-manuals.css">
158     <!--[if lte IE 7]>
159     <link href="%(rel)sDocumentation/css/lilypond-ie-fixes.css" rel="stylesheet" type="text/css">
160     <![endif]-->
161 """
162
163
164 def add_header (s, prefix):
165     """Add header (<body>, doctype and CSS)"""
166     if header_tag_re.search (s) == None:
167         body = '<body\\1>'
168         (s, n) = body_tag_re.subn (body + header, s, 1)
169         if not n:
170             (s, n) = html_tag_re.subn ('<html>' + header, s, 1)
171             if not n:
172                 s = header + s
173
174         if doctype_re.search (s) == None:
175             s = doctype + header_tag + '\n' + s
176
177         if css_re.search (s) == None:
178             depth = (prefix.count ('/') - 1) * '../'
179             s = end_head_tag_re.sub ((css_link % {'rel': depth}) + '</head>', s)
180     return s
181
182 title_tag_re = re.compile ('.*?<title>(.*?)</title>', re.DOTALL)
183 AT_web_title_re = re.compile ('@WEB-TITLE@')
184
185 def add_title (s):
186     # urg
187     # maybe find first node?
188     fallback_web_title = '-- --'
189     m = title_tag_re.match (s)
190     if m:
191         fallback_web_title = m.group (1)
192     s = AT_web_title_re.sub (fallback_web_title, s)
193     return s
194
195 footer_insert_re = re.compile ('<!--\s*FOOTER\s*-->')
196 end_body_re = re.compile ('(?i)</body>')
197 end_html_re = re.compile ('(?i)</html>')
198
199 def add_footer (s, footer_text):
200     """add footer"""
201     (s, n) = footer_insert_re.subn (footer_text + '\n' + '<!-- FOOTER -->', s, 1)
202     if not n:
203         (s, n) = end_body_re.subn (footer_text + '\n' + '</body>', s, 1)
204     if not n:
205         (s, n) = end_html_re.subn (footer_text + '\n' + '</html>', s, 1)
206     if not n:
207         s += footer_text + '\n'
208     return s
209
210 def find_translations (prefix, lang_ext):
211     """find available translations of a page"""
212     available = []
213     missing = []
214     for l in langdefs.LANGUAGES:
215         e = l.webext
216         if lang_ext != e:
217             if e in pages_dict[prefix]:
218                 available.append (l)
219             elif lang_ext == '' and l.enabled and reduce (operator.and_,
220                                                           [not prefix.startswith (s)
221                                                            for s in non_copied_pages]):
222                 # English version of missing translated pages will be written
223                 missing.append (e)
224     return available, missing
225
226 online_links_re = re.compile ('''(href|src)=['"]\
227 ((?!Compiling-from-source.html")[^/][.]*[^.:'"]*)\
228 ([.]html)(#[^"']*|)['"]''')
229 offline_links_re = re.compile ('href=[\'"]\
230 ((?!Compiling-from-source.html")(?![.]{2}/contributor)[^/][.]*[^.:\'"]*)([.]html)(#[^"\']*|)[\'"]')
231 big_page_name_re = re.compile ('''(.+?)-big-page''')
232
233 def process_i18n_big_page_links (match, prefix, lang_ext):
234     big_page_name = big_page_name_re.match (match.group (1))
235     if big_page_name:
236         destination_path = os.path.normpath (os.path.join (os.path.dirname (prefix),
237                                                            big_page_name.group (0)))
238         if not (destination_path in pages_dict and
239                 lang_ext in pages_dict[destination_path]):
240             return match.group (0)
241     return 'href="' + match.group (1) + '.' + lang_ext \
242         + match.group (2) + match.group (3) + '"'
243
244 def process_links (s, prefix, lang_ext, file_name, missing, target):
245     page_flavors = {}
246     if target == 'online':
247         # Strip .html, suffix for auto language selection (content
248         # negotiation).  The menu must keep the full extension, so do
249         # this before adding the menu.
250         page_flavors[file_name] = \
251             [lang_ext, online_links_re.sub ('\\1="\\2\\4"', s)]
252     elif target == 'offline':
253         # in LANG doc index: don't rewrite .html suffixes
254         # as not all .LANG.html pages exist;
255         # the doc index should be translated and contain links with the right suffixes
256         # idem for NEWS
257         if prefix in ('Documentation/out-www/index', 'Documentation/topdocs/out-www/NEWS'):
258             page_flavors[file_name] = [lang_ext, s]
259         elif lang_ext == '':
260             page_flavors[file_name] = [lang_ext, s]
261             for e in missing:
262                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = \
263                     [e, offline_links_re.sub ('href="\\1.' + e + '\\2\\3"', s)]
264         else:
265             # For saving bandwidth and disk space, we don't duplicate big pages
266             # in English, so we must process translated big pages links differently.
267             if 'big-page' in prefix:
268                 page_flavors[file_name] = \
269                     [lang_ext,
270                      offline_links_re.sub \
271                          (lambda match: process_i18n_big_page_links (match, prefix, lang_ext),
272                           s)]
273             else:
274                 page_flavors[file_name] = \
275                     [lang_ext,
276                      offline_links_re.sub ('href="\\1.' + lang_ext + '\\2\\3"', s)]
277     return page_flavors
278
279 def add_menu (page_flavors, prefix, available, target, translation):
280     for k in page_flavors:
281         language_menu = ''
282         languages = ''
283         if page_flavors[k][0] != '':
284             t = translation[page_flavors[k][0]]
285         else:
286             t = _doc
287         for lang in available:
288             lang_file = lang.file_name (os.path.basename (prefix), '.html')
289             if language_menu != '':
290                 language_menu += ', '
291             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
292         if target == 'offline':
293             browser_language = ''
294         elif target == 'online':
295             browser_language = t (browser_lang) % browser_language_url
296         if language_menu:
297             language_available = t (lang_available) % language_menu
298             languages = LANGUAGES_TEMPLATE % vars ()
299         page_flavors[k][1] = add_footer (page_flavors[k][1], languages)
300     return page_flavors
301
302
303 def process_html_files (package_name = '',
304                         package_version = '',
305                         target = 'offline',
306                         name_filter = lambda s: s):
307     """Add header, footer and tweak links to a number of HTML files
308
309     Arguments:
310      package_name=NAME         set package_name to NAME
311      package_version=VERSION   set package version to VERSION
312      targets=offline|online    set page processing depending on the target
313           offline is for reading HTML pages locally
314           online is for hosting the HTML pages on a website with content
315             negotiation
316      name_filter               a HTML file name filter
317     """
318     translation = langdefs.translation
319     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
320
321     if "http://" in mail_address:
322         mail_address_url = mail_address
323     else:
324         mail_address_url= 'mailto:' + mail_address
325
326     versiontup = package_version.split ('.')
327     branch_str = _doc ('stable-branch')
328     if int (versiontup[1]) %  2:
329         branch_str = _doc ('development-branch')
330
331     # Initialize dictionaries for string formatting
332     subst = {}
333     subst[''] = dict ([i for i in globals ().items() if type (i[1]) is str])
334     subst[''].update (dict ([i for i in locals ().items() if type (i[1]) is str]))
335     for l in translation:
336         e = langdefs.LANGDICT[l].webext
337         if e:
338             subst[e] = {}
339             for name in subst['']:
340                 subst[e][name] = translation[l] (subst[''][name])
341     # Do deeper string formatting as early as possible,
342     # so only one '%' formatting pass is needed later
343     for e in subst:
344         subst[e]['footer_name_version'] = subst[e]['footer_name_version'] % subst[e]
345         subst[e]['footer_report_links'] = subst[e]['footer_report_links'] % subst[e]
346
347     for prefix, ext_list in pages_dict.items ():
348         for lang_ext in ext_list:
349             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
350             in_f = open (file_name)
351             s = in_f.read()
352             in_f.close()
353
354             s = s.replace ('%', '%%')
355             s = hack_urls (s, prefix, target, bool (int (versiontup[1]) %  2))
356             s = add_header (s, prefix)
357
358             ### add footer
359             if footer_tag_re.search (s) == None:
360                 if 'web' in file_name:
361                     s = add_footer (s, footer_tag + web_footer)
362                 else:
363                     s = add_footer (s, footer_tag + footer)
364
365                 available, missing = find_translations (prefix, lang_ext)
366                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
367                 # Add menu after stripping: must not have autoselection for language menu.
368                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
369             for k in page_flavors:
370                 page_flavors[k][1] = page_flavors[k][1] % subst[page_flavors[k][0]]
371                 out_f = open (name_filter (k), 'w')
372                 out_f.write (page_flavors[k][1])
373                 out_f.close()
374         # if the page is translated, a .en.html symlink is necessary for content negotiation
375         if target == 'online' and ext_list != ['']:
376             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))