]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/add_html_footer.py
Merge branch 'master' of ssh://jomand@git.sv.gnu.org/srv/git/lilypond into topic...
[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 _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 </font>
41 <address><font size="-1">
42 %(footer_report_errors)s </font></address>
43 </p>
44 </div>
45 '''
46 footer_name_version = _doc ('This page is for %(package_name)s-%(package_version)s (%(branch_str)s).')
47 footer_report_errors = _doc ('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 = _doc ("Other languages: %s.")
55 browser_lang = _doc ('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 source_links_replace (m, source_val):
87     return 'href="' + os.path.join (source_val, m.group (1)) + '"'
88
89 # On systems without symlinks (e.g. Windows), docs are not very usable
90 # Get rid of symlinks here (also in GNUmakefile.in (local-WWW-post))
91 def replace_symlinks_urls (s, prefix):
92     if prefix.startswith ('Documentation/user/'):
93         s = re.sub ('(href|src)="(lily-.*?|.*?-flat-.*?)"', '\\1="../\\2"', s)
94     source_path = os.path.join (os.path.dirname (prefix), 'source')
95     if not os.path.islink (source_path):
96         return s
97     source_val = os.readlink (source_path)
98     return re.sub ('href="source/(.*?)"', lambda m: source_links_replace (m, source_val), s)
99
100 def add_header (s):
101     """Add header (<BODY> and doctype)"""
102     if re.search (header_tag, s) == None:
103         body = '<BODY BGCOLOR=WHITE TEXT=BLACK>'
104         s = re.sub ('(?i)<body>', body, s)
105         if re.search ('(?i)<BODY', s):
106             s = re.sub ('(?i)<body[^>]*>', body + header, s, 1)
107         elif re.search ('(?i)<html', s):
108             s = re.sub ('(?i)<html>', '<HTML>' + header, s, 1)
109         else:
110             s = header + s
111
112         s = header_tag + '\n' + s
113
114         if re.search ('(?i)<!DOCTYPE', s) == None:
115             doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
116             s = doctype + s
117         return s
118
119 def add_title (s):
120     # urg
121     # maybe find first node?
122     fallback_web_title = '-- --'
123     m = re.match ('.*?<title>(.*?)</title>', s, re.DOTALL)
124     if m:
125         fallback_web_title = m.group (1)
126     s = re.sub ('@WEB-TITLE@', fallback_web_title, s)
127     return s
128
129 info_nav_bar = re.compile (r'<div class="node">\s*<p>\s*<a name=".+?"></a>(.+?)<hr>\s*</div>', re.M | re.S)
130 info_footnote_hr = re.compile (r'<hr>\s*(</div>)?\s*</body>', re.M | re.I)
131
132 def add_footer (s):
133     """add footer
134
135 also add navigation bar to bottom of Info HTML pages"""
136     m = info_nav_bar.search (s)
137     if m:
138         # avoid duplicate <hr> in case there are footnotes at the end of the Info HTML page
139         if info_footnote_hr.search (s):
140             custom_footer = '<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
141         else:
142             custom_footer = '<br><hr>\n<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
143     else:
144         custom_footer = footer
145     if re.search ('(?i)</body', s):
146         s = re.sub ('(?i)</body>', footer_tag + custom_footer + '\n' + '</BODY>', s, 1)
147     elif re.search ('(?i)</html', s):                
148         s = re.sub ('(?i)</html>', footer_tag + custom_footer + '\n' + '</HTML>', s, 1)
149     else:
150         s += footer_tag + custom_footer + '\n'
151     return s
152
153 def find_translations (prefix, lang_ext):
154     """find available translations of a page"""
155     available = []
156     missing = []
157     for l in langdefs.LANGUAGES:
158         e = l.webext
159         if lang_ext != e:
160             if e in pages_dict[prefix]:
161                 available.append (l)
162             elif lang_ext == '' and l.enabled and not prefix in non_copied_pages:
163                 # English version of missing translated pages will be written
164                 missing.append (e)
165     return available, missing
166
167 def process_links (s, prefix, lang_ext, file_name, missing, target):
168     page_flavors = {}
169     if target == 'online':
170         # Strip .html, .png suffix for auto language selection (content
171         # negotiation).  The menu must keep the full extension, so do
172         # this before adding the menu.
173         page_flavors[file_name] = [lang_ext, re.sub (
174             '''(href|src)=[\'"]([^/][.]*[^.:\'"]*)(.html|.png)(#[^"\']*|)[\'"]''',
175             '\\1="\\2\\4"', s)]
176     elif target == 'offline':
177         # in LANG doc index: don't rewrite .html suffixes as not all .LANG.html pages exist
178         # the doc index should be translated and contain the right links
179         if prefix == 'Documentation/out-www/index':
180             page_flavors[file_name] = [lang_ext, s]
181         elif lang_ext == '':
182             page_flavors[file_name] = [lang_ext, s]
183             for e in missing:
184                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = [e, re.sub (
185                     '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
186                     'href="\\1.' + e + '\\2\\3"', s)]
187         else:
188             page_flavors[file_name] = [lang_ext, re.sub (
189                 '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
190                 'href="\\1.' + lang_ext + '\\2\\3"', s)]
191     return page_flavors
192
193 def add_menu (page_flavors, prefix, available, target, translation):
194     for k in page_flavors.keys():
195         language_menu = ''
196         languages = ''
197         if page_flavors[k][0] != '':
198             t = translation[page_flavors[k][0]]
199         else:
200             t = _doc
201         for lang in available:
202             lang_file = lang.file_name (os.path.basename (prefix), '.html')
203             if language_menu != '':
204                 language_menu += ', '
205             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
206         if target == 'offline':
207             browser_language = ''
208         elif target == 'online':
209             browser_language = t (browser_lang) % browser_language_url
210         if language_menu:
211             language_available = t (lang_available) % language_menu
212             languages = LANGUAGES_TEMPLATE % vars ()
213         # put language menu before '</body>' and '</html>' tags
214         if re.search ('(?i)</body', page_flavors[k][1]):
215             page_flavors[k][1] = re.sub ('(?i)</body>', languages + '</BODY>', page_flavors[k][1], 1)
216         elif re.search ('(?i)</html', page_flavors[k][1]):
217             page_flavors[k][1] = re.sub ('(?i)</html>', languages + '</HTML>', page_flavors[k][1], 1)
218         else:
219             page_flavors[k][1] += languages
220     return page_flavors
221
222
223 def add_html_footer (translation,
224                      package_name = '',
225                      package_version = '',
226                      target = 'offline',
227                      name_filter = lambda s: s):
228     """Add header, footer to a number of HTML files
229
230     Arguments:
231      translation               gettext translations dictionary, with language codes as keys
232      package_name=NAME         set package_name to NAME
233      package_version=VERSION   set package version to VERSION
234      targets=offline|online    set page processing depending on the target
235           offline is for reading HTML pages locally
236           online is for hosting the HTML pages on a website with content
237             negotiation
238      name_filter               a HTML file name filter
239     """
240     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
241
242     if re.search ("http://", mail_address):
243         mail_address_url = mail_address
244     else:
245         mail_address_url= 'mailto:' + mail_address
246
247     versiontup = package_version.split ('.')
248     branch_str = _doc ('stable-branch')
249     if int (versiontup[1]) %  2:
250         branch_str = _doc ('development-branch')
251
252     for prefix, ext_list in pages_dict.items ():
253         for lang_ext in ext_list:
254             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
255             in_f = open (file_name)
256             s = in_f.read()
257             in_f.close()
258
259             s = re.sub ('%', '%%', s)
260             if target == 'offline':
261                 s = replace_symlinks_urls (s, prefix)
262             s = add_header (s)
263
264             ### add footer
265             if re.search (footer_tag, s) == None:
266                 s = add_footer (s)
267                 
268                 available, missing = find_translations (prefix, lang_ext)
269                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
270                 # Add menu after stripping: must not have autoselection for language menu.
271                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
272             subst = dict ([i for i in globals().items() if type (i[1]) is str])
273             subst.update (dict ([i for i in locals().items() if type (i[1]) is str]))
274             for k in page_flavors.keys():
275                 if page_flavors[k][0] in translation.keys():
276                     for name in subst.keys():
277                         subst[name] = translation[page_flavors[k][0]] (subst[name])
278                 subst['footer_name_version'] = subst['footer_name_version'] % subst
279                 subst['footer_report_errors'] = subst['footer_report_errors'] % subst
280                 page_flavors[k][1] = page_flavors[k][1] % subst
281                 out_f = open (name_filter (k), 'w')
282                 out_f.write (page_flavors[k][1])
283                 out_f.close()
284         # if the page is translated, a .en.html symlink is necessary for content negotiation
285         if target == 'online' and ext_list != ['']:
286             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))