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