]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/postprocess_html.py
6660519df01a008fb605f977aa59e37117ed6d55
[lilypond.git] / buildscripts / postprocess_html.py
1 #!@PYTHON@
2
3 """
4 Postprocess HTML files.
5 """
6 import re
7 import os
8 import time
9 import operator
10
11 import langdefs
12
13 # This is to try to make the docball not too big with almost duplicate files
14 # see process_links()
15 non_copied_pages = ['Documentation/user/out-www/lilypond-big-page',
16                     'Documentation/user/out-www/lilypond-internals-big-page',
17                     'Documentation/user/out-www/lilypond-learning-big-page',
18                     'Documentation/user/out-www/lilypond-program-big-page',
19                     'Documentation/user/out-www/music-glossary-big-page',
20                     'out-www/examples',
21                     'Documentation/topdocs',
22                     'Documentation/bibliography',
23                     'Documentation/out-www/THANKS',
24                     'Documentation/out-www/DEDICATION',
25                     'Documentation/out-www/devel',
26                     'input/']
27
28 def _doc (s):
29     return s
30
31 header = r"""
32 """
33
34 footer = '''
35 <div style="background-color: #e8ffe8; padding: 2; border: #c0ffc0 1px solid;">
36 <p>
37 <font size="-1">
38 %(footer_name_version)s
39 <br>
40 <address>
41 %(footer_report_errors)s </address>
42 <br>
43 %(footer_suggest_docs)s
44 </font>
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
130 def add_header (s):
131     """Add header (<body> and doctype)"""
132     if header_tag_re.search (s) == None:
133         body = '<body bgcolor="white" text="black" \\1>'
134         (s, n) = body_tag_re.subn (body + header, s, 1)
135         if not n:
136             (s, n) = html_tag_re.subn ('<html>' + header, s, 1)
137             if not n:
138                 s = header + s
139
140         s = header_tag + '\n' + s
141
142         if doctype_re.search (s) == None:
143             s = doctype + s
144         return s
145
146 title_tag_re = re.compile ('.*?<title>(.*?)</title>', re.DOTALL)
147 AT_web_title_re = re.compile ('@WEB-TITLE@')
148
149 def add_title (s):
150     # urg
151     # maybe find first node?
152     fallback_web_title = '-- --'
153     m = title_tag_re.match (s)
154     if m:
155         fallback_web_title = m.group (1)
156     s = AT_web_title_re.sub (fallback_web_title, s)
157     return s
158
159 footer_insert_re = re.compile ('<!--\s*FOOTER\s*-->')
160 end_body_re = re.compile ('(?i)</body>')
161 end_html_re = re.compile ('(?i)</html>')
162
163 def add_footer (s, footer_text):
164     """add footer"""
165     (s, n) = footer_insert_re.subn (footer_text + '\n' + '<!-- FOOTER -->', s, 1)
166     if not n:
167         (s, n) = end_body_re.subn (footer_text + '\n' + '</body>', s, 1)
168     if not n:
169         (s, n) = end_html_re.subn (footer_text + '\n' + '</html>', s, 1)
170     if not n:
171         s += footer_text + '\n'
172     return s
173
174 def find_translations (prefix, lang_ext):
175     """find available translations of a page"""
176     available = []
177     missing = []
178     for l in langdefs.LANGUAGES:
179         e = l.webext
180         if lang_ext != e:
181             if e in pages_dict[prefix]:
182                 available.append (l)
183             elif lang_ext == '' and l.enabled and reduce (operator.and_,
184                                                           [not prefix.startswith (s)
185                                                            for s in non_copied_pages]):
186                 # English version of missing translated pages will be written
187                 missing.append (e)
188     return available, missing
189
190 online_links_re = re.compile ('''(href|src)=['"]([^/][.]*[^.:'"]*)\
191 ([.]html|[.]png)(#[^"']*|)['"]''')
192 offline_links_re = re.compile ('''href=['"]([^/][.]*[^.:'"]*)([.]html)(#[^"']*|)['"]''')
193 big_page_name_re = re.compile ('''(.+?)-big-page''')
194
195 def process_i18n_big_page_links (match, prefix, lang_ext):
196     big_page_name = big_page_name_re.match (match.group (1))
197     if big_page_name:
198         destination_path = os.path.normpath (os.path.join (os.path.dirname (prefix),
199                                                            big_page_name.group (0)))
200         if not lang_ext in pages_dict[destination_path]:
201             return match.group (0)
202     return 'href="' + match.group (1) + '.' + lang_ext \
203         + match.group (2) + match.group (3) + '"'
204
205 def process_links (s, prefix, lang_ext, file_name, missing, target):
206     page_flavors = {}
207     if target == 'online':
208         # Strip .html, .png suffix for auto language selection (content
209         # negotiation).  The menu must keep the full extension, so do
210         # this before adding the menu.
211         page_flavors[file_name] = \
212             [lang_ext, online_links_re.sub ('\\1="\\2\\4"', s)]
213     elif target == 'offline':
214         # in LANG doc index: don't rewrite .html suffixes
215         # as not all .LANG.html pages exist;
216         # the doc index should be translated and contain links with the right suffixes
217         if prefix == 'Documentation/out-www/index':
218             page_flavors[file_name] = [lang_ext, s]
219         elif lang_ext == '':
220             page_flavors[file_name] = [lang_ext, s]
221             for e in missing:
222                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = \
223                     [e, offline_links_re.sub ('href="\\1.' + e + '\\2\\3"', s)]
224         else:
225             # For saving bandwidth and disk space, we don't duplicate big pages
226             # in English, so we must process translated big pages links differently.
227             if 'big-page' in prefix:
228                 page_flavors[file_name] = \
229                     [lang_ext,
230                      offline_links_re.sub \
231                          (lambda match: process_i18n_big_page_links (match, prefix, lang_ext),
232                           s)]
233             else:
234                 page_flavors[file_name] = \
235                     [lang_ext,
236                      offline_links_re.sub ('href="\\1.' + lang_ext + '\\2\\3"', s)]
237     return page_flavors
238
239 def add_menu (page_flavors, prefix, available, target, translation):
240     for k in page_flavors:
241         language_menu = ''
242         languages = ''
243         if page_flavors[k][0] != '':
244             t = translation[page_flavors[k][0]]
245         else:
246             t = _doc
247         for lang in available:
248             lang_file = lang.file_name (os.path.basename (prefix), '.html')
249             if language_menu != '':
250                 language_menu += ', '
251             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
252         if target == 'offline':
253             browser_language = ''
254         elif target == 'online':
255             browser_language = t (browser_lang) % browser_language_url
256         if language_menu:
257             language_available = t (lang_available) % language_menu
258             languages = LANGUAGES_TEMPLATE % vars ()
259         page_flavors[k][1] = add_footer (page_flavors[k][1], languages)
260     return page_flavors
261
262
263 def process_html_files (package_name = '',
264                         package_version = '',
265                         target = 'offline',
266                         name_filter = lambda s: s):
267     """Add header, footer and tweak links to a number of HTML files
268
269     Arguments:
270      package_name=NAME         set package_name to NAME
271      package_version=VERSION   set package version to VERSION
272      targets=offline|online    set page processing depending on the target
273           offline is for reading HTML pages locally
274           online is for hosting the HTML pages on a website with content
275             negotiation
276      name_filter               a HTML file name filter
277     """
278     translation = langdefs.translation
279     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
280
281     if "http://" in mail_address:
282         mail_address_url = mail_address
283     else:
284         mail_address_url= 'mailto:' + mail_address
285
286     versiontup = package_version.split ('.')
287     branch_str = _doc ('stable-branch')
288     if int (versiontup[1]) %  2:
289         branch_str = _doc ('development-branch')
290
291     # Initialize dictionaries for string formatting
292     subst = {}
293     subst[''] = dict ([i for i in globals ().items() if type (i[1]) is str])
294     subst[''].update (dict ([i for i in locals ().items() if type (i[1]) is str]))
295     for l in translation:
296         e = langdefs.LANGDICT[l].webext
297         if e:
298             subst[e] = {}
299             for name in subst['']:
300                 subst[e][name] = translation[l] (subst[''][name])
301     # Do deeper string formatting as early as possible,
302     # so only one '%' formatting pass is needed later
303     for e in subst:
304         subst[e]['footer_name_version'] = subst[e]['footer_name_version'] % subst[e]
305         subst[e]['footer_report_errors'] = subst[e]['footer_report_errors'] % subst[e]
306         subst[e]['footer_suggest_docs'] = subst[e]['footer_suggest_docs'] % subst[e]
307
308     for prefix, ext_list in pages_dict.items ():
309         for lang_ext in ext_list:
310             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
311             in_f = open (file_name)
312             s = in_f.read()
313             in_f.close()
314
315             s = s.replace ('%', '%%')
316             s = hack_urls (s, prefix)
317             s = add_header (s)
318
319             ### add footer
320             if footer_tag_re.search (s) == None:
321                 s = add_footer (s, footer_tag + footer)
322
323                 available, missing = find_translations (prefix, lang_ext)
324                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
325                 # Add menu after stripping: must not have autoselection for language menu.
326                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
327             for k in page_flavors:
328                 page_flavors[k][1] = page_flavors[k][1] % subst[page_flavors[k][0]]
329                 out_f = open (name_filter (k), 'w')
330                 out_f.write (page_flavors[k][1])
331                 out_f.close()
332         # if the page is translated, a .en.html symlink is necessary for content negotiation
333         if target == 'online' and ext_list != ['']:
334             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))