]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/postprocess_html.py
Fix build (add_header should always return something!)
[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 ((?!Compiling-from-source.html")[^/][.]*[^.:'"]*)\
199 ([.]html|[.]png)(#[^"']*|)['"]''')
200 offline_links_re = re.compile ('href=[\'"]\
201 ((?!Compiling-from-source.html")[^/][.]*[^.:\'"]*)([.]html)(#[^"\']*|)[\'"]')
202 big_page_name_re = re.compile ('''(.+?)-big-page''')
203
204 def process_i18n_big_page_links (match, prefix, lang_ext):
205     big_page_name = big_page_name_re.match (match.group (1))
206     if big_page_name:
207         destination_path = os.path.normpath (os.path.join (os.path.dirname (prefix),
208                                                            big_page_name.group (0)))
209         if not lang_ext in pages_dict[destination_path]:
210             return match.group (0)
211     return 'href="' + match.group (1) + '.' + lang_ext \
212         + match.group (2) + match.group (3) + '"'
213
214 def process_links (s, prefix, lang_ext, file_name, missing, target):
215     page_flavors = {}
216     if target == 'online':
217         # Strip .html, .png suffix for auto language selection (content
218         # negotiation).  The menu must keep the full extension, so do
219         # this before adding the menu.
220         page_flavors[file_name] = \
221             [lang_ext, online_links_re.sub ('\\1="\\2\\4"', s)]
222     elif target == 'offline':
223         # in LANG doc index: don't rewrite .html suffixes
224         # as not all .LANG.html pages exist;
225         # the doc index should be translated and contain links with the right suffixes
226         if prefix == 'Documentation/out-www/index':
227             page_flavors[file_name] = [lang_ext, s]
228         elif lang_ext == '':
229             page_flavors[file_name] = [lang_ext, s]
230             for e in missing:
231                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = \
232                     [e, offline_links_re.sub ('href="\\1.' + e + '\\2\\3"', s)]
233         else:
234             # For saving bandwidth and disk space, we don't duplicate big pages
235             # in English, so we must process translated big pages links differently.
236             if 'big-page' in prefix:
237                 page_flavors[file_name] = \
238                     [lang_ext,
239                      offline_links_re.sub \
240                          (lambda match: process_i18n_big_page_links (match, prefix, lang_ext),
241                           s)]
242             else:
243                 page_flavors[file_name] = \
244                     [lang_ext,
245                      offline_links_re.sub ('href="\\1.' + lang_ext + '\\2\\3"', s)]
246     return page_flavors
247
248 def add_menu (page_flavors, prefix, available, target, translation):
249     for k in page_flavors:
250         language_menu = ''
251         languages = ''
252         if page_flavors[k][0] != '':
253             t = translation[page_flavors[k][0]]
254         else:
255             t = _doc
256         for lang in available:
257             lang_file = lang.file_name (os.path.basename (prefix), '.html')
258             if language_menu != '':
259                 language_menu += ', '
260             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
261         if target == 'offline':
262             browser_language = ''
263         elif target == 'online':
264             browser_language = t (browser_lang) % browser_language_url
265         if language_menu:
266             language_available = t (lang_available) % language_menu
267             languages = LANGUAGES_TEMPLATE % vars ()
268         page_flavors[k][1] = add_footer (page_flavors[k][1], languages)
269     return page_flavors
270
271
272 def process_html_files (package_name = '',
273                         package_version = '',
274                         target = 'offline',
275                         name_filter = lambda s: s):
276     """Add header, footer and tweak links to a number of HTML files
277
278     Arguments:
279      package_name=NAME         set package_name to NAME
280      package_version=VERSION   set package version to VERSION
281      targets=offline|online    set page processing depending on the target
282           offline is for reading HTML pages locally
283           online is for hosting the HTML pages on a website with content
284             negotiation
285      name_filter               a HTML file name filter
286     """
287     translation = langdefs.translation
288     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
289
290     if "http://" in mail_address:
291         mail_address_url = mail_address
292     else:
293         mail_address_url= 'mailto:' + mail_address
294
295     versiontup = package_version.split ('.')
296     branch_str = _doc ('stable-branch')
297     if int (versiontup[1]) %  2:
298         branch_str = _doc ('development-branch')
299
300     # Initialize dictionaries for string formatting
301     subst = {}
302     subst[''] = dict ([i for i in globals ().items() if type (i[1]) is str])
303     subst[''].update (dict ([i for i in locals ().items() if type (i[1]) is str]))
304     for l in translation:
305         e = langdefs.LANGDICT[l].webext
306         if e:
307             subst[e] = {}
308             for name in subst['']:
309                 subst[e][name] = translation[l] (subst[''][name])
310     # Do deeper string formatting as early as possible,
311     # so only one '%' formatting pass is needed later
312     for e in subst:
313         subst[e]['footer_name_version'] = subst[e]['footer_name_version'] % subst[e]
314         subst[e]['footer_report_errors'] = subst[e]['footer_report_errors'] % subst[e]
315         subst[e]['footer_suggest_docs'] = subst[e]['footer_suggest_docs'] % subst[e]
316
317     for prefix, ext_list in pages_dict.items ():
318         for lang_ext in ext_list:
319             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
320             in_f = open (file_name)
321             s = in_f.read()
322             in_f.close()
323
324             s = s.replace ('%', '%%')
325             s = hack_urls (s, prefix)
326             s = add_header (s, prefix)
327
328             ### add footer
329             if footer_tag_re.search (s) == None:
330                 s = add_footer (s, footer_tag + footer)
331
332                 available, missing = find_translations (prefix, lang_ext)
333                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
334                 # Add menu after stripping: must not have autoselection for language menu.
335                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
336             for k in page_flavors:
337                 page_flavors[k][1] = page_flavors[k][1] % subst[page_flavors[k][0]]
338                 out_f = open (name_filter (k), 'w')
339                 out_f.write (page_flavors[k][1])
340                 out_f.close()
341         # if the page is translated, a .en.html symlink is necessary for content negotiation
342         if target == 'online' and ext_list != ['']:
343             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))