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