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