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