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