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