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