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