]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/add_html_footer.py
Merge branch 'master' of git+ssh://jneem@git.sv.gnu.org/srv/git/lilypond
[lilypond.git] / buildscripts / add_html_footer.py
1 #!@PYTHON@
2
3 """
4 Print a nice footer.
5 """
6 import re
7 import os
8 import time
9
10 import langdefs
11
12 # This is to try to make the docball not too big with almost duplicate files
13 # see process_links()
14 non_copied_pages = ['Documentation/user/out-www/lilypond-big-page',
15                     'Documentation/user/out-www/lilypond-internals-big-page',
16                     'Documentation/user/out-www/music-glossary-big-page',
17                     'out-www/examples',
18                     'Documentation/topdocs/out-www/NEWS',
19                     'Documentation/topdocs/out-www/INSTALL',
20                     'Documentation/bibliography/out-www/index',
21                     'Documentation/bibliography/out-www/engraving',
22                     'Documentation/bibliography/out-www/colorado',
23                     'Documentation/bibliography/out-www/computer-notation'
24                     'Documentation/out-www/THANKS',
25                     'Documentation/out-www/DEDICATION',
26                     'Documentation/topdocs/out-www/AUTHORS']
27
28 def _ (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 </font>
41 <address><font size="-1">
42 %(footer_report_errors)s </font></address>
43 </p>
44 </div>
45 '''
46 footer_name_version = _ ('This page is for %(package_name)s-%(package_version)s (%(branch_str)s).')
47 footer_report_errors = _ ('Report errors to <a href="%(mail_address_url)s">%(mail_address)s</a>.')
48
49 mail_address = 'http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs'
50
51 header_tag = '<!-- header_tag -->'
52 footer_tag = '<!-- footer_tag -->'
53
54 lang_available = _ ("Other languages: %s.")
55 browser_lang = _ ('About <A HREF="%s">automatic language selection</A>.')
56 browser_language_url = "/web/about/browser-language"
57
58 LANGUAGES_TEMPLATE = '''
59 <P>
60  %(language_available)s
61  <BR>
62  %(browser_language)s
63 </P>
64 '''
65
66
67 html_re = re.compile ('(.*?)(?:[.]([^/.]*))?[.]html$')
68 pages_dict = {}
69
70 def build_pages_dict (filelist):
71     """Build dictionnary of available translations of each page"""
72     global pages_dict
73     for f in filelist:
74         m = html_re.match (f)
75         if m:
76             g = m.groups()
77             if len (g) <= 1 or g[1] == None:
78                 e = ''
79             else:
80                 e = g[1]
81             if not g[0] in pages_dict.keys():
82                 pages_dict[g[0]] = [e]
83             else:
84                 pages_dict[g[0]].append (e)
85
86 def add_header (s):
87     """Add header (<BODY> and doctype)"""
88     if re.search (header_tag, s) == None:
89         body = '<BODY BGCOLOR=WHITE TEXT=BLACK>'
90         s = re.sub ('(?i)<body>', body, s)
91         if re.search ('(?i)<BODY', s):
92             s = re.sub ('(?i)<body[^>]*>', body + header, s, 1)
93         elif re.search ('(?i)<html', s):
94             s = re.sub ('(?i)<html>', '<HTML>' + header, s, 1)
95         else:
96             s = header + s
97
98         s = header_tag + '\n' + s
99
100         if re.search ('(?i)<!DOCTYPE', s) == None:
101             doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
102             s = doctype + s
103         return s
104
105 def info_external_ref_remove (s):
106     """Remove info's annoying's indication of referencing external document"""
107     return re.sub (' \((lilypond|lilypond-internals|music-glossary)\)</a>', '</a>', s)
108
109 def add_title (s):
110     # urg
111     # maybe find first node?
112     fallback_web_title = '-- --'
113     m = re.match ('.*?<title>(.*?)</title>', s, re.DOTALL)
114     if m:
115         fallback_web_title = m.group (1)
116     s = re.sub ('@WEB-TITLE@', fallback_web_title, s)
117     return s
118
119 info_nav_bar = re.compile (r'<div class="node">\s*<p>\s*<a name=".+?"></a>(.+?)<hr>\s*</div>', re.M | re.S)
120 info_footnote_hr = re.compile (r'<hr>\s*(</div>)?\s*</body>', re.M | re.I)
121
122 def add_footer (s):
123     """add footer
124
125 also add navigation bar to bottom of Info HTML pages"""
126     m = info_nav_bar.search (s)
127     if m:
128         # avoid duplicate <hr> in case there are footnotes at the end of the Info HTML page
129         if info_footnote_hr.search (s):
130             custom_footer = '<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
131         else:
132             custom_footer = '<br><hr>\n<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
133     else:
134         custom_footer = footer
135     if re.search ('(?i)</body', s):
136         s = re.sub ('(?i)</body>', footer_tag + custom_footer + '\n' + '</BODY>', s, 1)
137     elif re.search ('(?i)</html', s):                
138         s = re.sub ('(?i)</html>', footer_tag + custom_footer + '\n' + '</HTML>', s, 1)
139     else:
140         s += footer_tag + custom_footer + '\n'
141     return s
142
143 def find_translations (prefix, lang_ext):
144     """find available translations of a page"""
145     available = []
146     missing = []
147     for l in langdefs.LANGUAGES:
148         e = l.webext
149         if lang_ext != e:
150             if e in pages_dict[prefix]:
151                 available.append (l)
152             elif lang_ext == '' and l.enabled and not prefix in non_copied_pages:
153                 # English version of missing translated pages will be written
154                 missing.append (e)
155     return available, missing
156
157 def process_links (s, prefix, lang_ext, file_name, missing, target):
158     page_flavors = {}
159     if target == 'online':
160         # Strip .html, .png suffix for auto language selection (content
161         # negotiation).  The menu must keep the full extension, so do
162         # this before adding the menu.
163         page_flavors[file_name] = [lang_ext, re.sub (
164             '''(href|src)=[\'"]([^/][.]*[^.:\'"]*)(.html|.png)(#[^"\']*|)[\'"]''',
165             '\\1="\\2\\4"', s)]
166     elif target == 'offline':
167         # in LANG doc index: don't rewrite .html suffixes as not all .LANG.html pages exist
168         # the doc index should be translated and contain the right links
169         if prefix == 'Documentation/out-www/index':
170             page_flavors[file_name] = [lang_ext, s]
171         elif lang_ext == '':
172             page_flavors[file_name] = [lang_ext, s]
173             for e in missing:
174                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = [e, re.sub (
175                     '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
176                     'href="\\1.' + e + '\\2\\3"', s)]
177         else:
178             page_flavors[file_name] = [lang_ext, re.sub (
179                 '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
180                 'href="\\1.' + lang_ext + '\\2\\3"', s)]
181     return page_flavors
182
183 def add_menu (page_flavors, prefix, available, target, translation):
184     for k in page_flavors.keys():
185         language_menu = ''
186         languages = ''
187         if page_flavors[k][0] != '':
188             t = translation[page_flavors[k][0]]
189         else:
190             t = _
191         for lang in available:
192             lang_file = lang.file_name (os.path.basename (prefix), '.html')
193             if language_menu != '':
194                 language_menu += ', '
195             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
196         if target == 'offline':
197             browser_language = ''
198         elif target == 'online':
199             browser_language = t (browser_lang) % browser_language_url
200         if language_menu:
201             language_available = t (lang_available) % language_menu
202             languages = LANGUAGES_TEMPLATE % vars ()
203         # put language menu before '</body>' and '</html>' tags
204         if re.search ('(?i)</body', page_flavors[k][1]):
205             page_flavors[k][1] = re.sub ('(?i)</body>', languages + '</BODY>', page_flavors[k][1], 1)
206         elif re.search ('(?i)</html', page_flavors[k][1]):
207             page_flavors[k][1] = re.sub ('(?i)</html>', languages + '</HTML>', page_flavors[k][1], 1)
208         else:
209             page_flavors[k][1] += languages
210     return page_flavors
211
212
213 def add_html_footer (translation,
214                      package_name = '',
215                      package_version = '',
216                      target = 'offline',
217                      name_filter = lambda s: s):
218     """Add header, footer to a number of HTML files
219
220     Arguments:
221      translation               gettext translations dictionary, with language codes as keys
222      package_name=NAME         set package_name to NAME
223      package_version=VERSION   set package version to VERSION
224      targets=offline|online    set page processing depending on the target
225           offline is for reading HTML pages locally
226           online is for hosting the HTML pages on a website with content
227             negotiation
228      name_filter               a HTML file name filter
229     """
230     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
231
232     if re.search ("http://", mail_address):
233         mail_address_url = mail_address
234     else:
235         mail_address_url= 'mailto:' + mail_address
236
237     versiontup = package_version.split ('.')
238     branch_str = _('stable-branch')
239     if int ( versiontup[1]) %  2:
240         branch_str = _('development-branch')
241
242     for prefix, ext_list in pages_dict.items ():
243         for lang_ext in ext_list:
244             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
245             in_f = open (file_name)
246             s = in_f.read()
247             in_f.close()
248
249             s = re.sub ('%', '%%', s)
250             s = add_header (s)
251             # seems to be no more needed
252             # s = info_external_ref_remove (s)
253
254             ### add footer
255             if re.search (footer_tag, s) == None:
256                 s = add_footer (s)
257                 
258                 available, missing = find_translations (prefix, lang_ext)
259                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
260                 # Add menu after stripping: must not have autoselection for language menu.
261                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
262             # urg, this stuff is outdated and seems useless, let's disable it
263             #else:
264             #    for e in [l.webext for l in langdefs.LANGUAGES]:
265             #        if not e in pages_dict[prefix]:
266             #            page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = s
267             subst = dict ([i for i in globals().items() if type (i[1]) is str])
268             subst.update (dict ([i for i in locals().items() if type (i[1]) is str]))
269             for k in page_flavors.keys():
270                 if page_flavors[k][0] in translation.keys():
271                     for name in subst.keys():
272                         subst[name] = translation[page_flavors[k][0]] (subst[name])
273                 subst['footer_name_version'] = subst['footer_name_version'] % subst
274                 subst['footer_report_errors'] = subst['footer_report_errors'] % subst
275                 page_flavors[k][1] = page_flavors[k][1] % subst
276                 out_f = open (name_filter (k), 'w')
277                 out_f.write (page_flavors[k][1])
278                 out_f.close()
279         # if the page is translated, a .en.html symlink is necessary for content negotiation
280         if target == 'online' and ext_list != ['']:
281             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))