]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/add_html_footer.py
Merge branch 'master' of ssh+git://hanwen@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/lilypond-learning-big-page',
17                     'Documentation/user/out-www/lilypond-program-big-page',
18                     'Documentation/user/out-www/music-glossary-big-page',
19                     'out-www/examples',
20                     'Documentation/topdocs',
21                     'Documentation/bibliography',
22                     'Documentation/out-www/THANKS',
23                     'Documentation/out-www/DEDICATION',
24                     'Documentation/out-www/devel',
25                     'input/']
26
27 def _doc (s):
28     return s
29
30 header = r"""
31 """
32
33 footer = '''
34 <div style="background-color: #e8ffe8; padding: 2; border: #c0ffc0 1px solid;">
35 <p>
36 <font size="-1">
37 %(footer_name_version)s
38 <br>
39 <address>
40 %(footer_report_errors)s </address>
41 <br>
42 %(footer_suggest_docs)s
43 </font>
44 </p>
45 </div>
46 '''
47 footer_name_version = _doc ('This page is for %(package_name)s-%(package_version)s (%(branch_str)s).')
48 footer_report_errors = _doc ('Report errors to <a href="%(mail_address_url)s">%(mail_address)s</a>.')
49 # ugh, must not have "_doc" in strings because it is naively replaced with "_" in hacked gettext process
50 footer_suggest_docs = _doc ('Your <a href="%(suggest_Docs_url)s">suggestions for the documentation</a> are welcome.')
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 footer_tag = '<!-- footer_tag -->'
57
58 lang_available = _doc ("Other languages: %s.")
59 browser_lang = _doc ('About <A HREF="%s">automatic language selection</A>.')
60 browser_language_url = "/web/about/browser-language"
61
62 LANGUAGES_TEMPLATE = '''
63 <P>
64  %(language_available)s
65  <BR>
66  %(browser_language)s
67 </P>
68 '''
69
70
71 html_re = re.compile ('(.*?)(?:[.]([^/.]*))?[.]html$')
72 pages_dict = {}
73
74 def build_pages_dict (filelist):
75     """Build dictionary of available translations of each page"""
76     global pages_dict
77     for f in filelist:
78         m = html_re.match (f)
79         if m:
80             g = m.groups()
81             if len (g) <= 1 or g[1] == None:
82                 e = ''
83             else:
84                 e = g[1]
85             if not g[0] in pages_dict:
86                 pages_dict[g[0]] = [e]
87             else:
88                 pages_dict[g[0]].append (e)
89
90 def source_links_replace (m, source_val):
91     return 'href="' + os.path.join (source_val, m.group (1)) + '"'
92
93 splitted_docs_re = re.compile ('(input/lsr/out-www/lilypond-snippets|Documentation/user/out-www/(lilypond|music-glossary|lilypond-program|lilypond-learning))/')
94
95 snippets_ref_re = re.compile (r'href="(\.\./)?lilypond-snippets')
96 user_ref_re = re.compile (r'href="(?:\.\./)?lilypond(|-internals|-learning|-program)')
97
98 ## Windows does not support symlinks.
99 # This function avoids creating symlinks for splitted HTML manuals
100 # Get rid of symlinks in GNUmakefile.in (local-WWW-post)
101 # this also fixes missing PNGs only present in translated docs
102 def hack_urls (s, prefix):
103     if splitted_docs_re.match (prefix):
104         s = re.sub ('(href|src)="(../lily-.*?|.*?[.]png)"', '\\1="../\\2"', s)
105
106     # fix xrefs between documents in different directories ad hoc
107     if 'user/out-www/lilypond' in prefix:
108         s = snippets_ref_re.sub ('href="source/input/lsr/lilypond-snippets', s)
109     elif 'input/lsr' in prefix:
110         s = user_ref_re.sub ('href="source/Documentation/user/lilypond\\1', s)
111
112     source_path = os.path.join (os.path.dirname (prefix), 'source')
113     if not os.path.islink (source_path):
114         return s
115     source_val = os.readlink (source_path)
116     return re.sub ('href="source/(.*?)"', lambda m: source_links_replace (m, source_val), s)
117
118 def add_header (s):
119     """Add header (<BODY> and doctype)"""
120     if re.search (header_tag, s) == None:
121         body = '<BODY BGCOLOR=WHITE TEXT=BLACK>'
122         s = re.sub ('(?i)<body>', body, s)
123         if re.search ('(?i)<BODY', s):
124             s = re.sub ('(?i)<body[^>]*>', body + header, s, 1)
125         elif re.search ('(?i)<html', s):
126             s = re.sub ('(?i)<html>', '<HTML>' + header, s, 1)
127         else:
128             s = header + s
129
130         s = header_tag + '\n' + s
131
132         if re.search ('(?i)<!DOCTYPE', s) == None:
133             doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
134             s = doctype + s
135         return s
136
137 def add_title (s):
138     # urg
139     # maybe find first node?
140     fallback_web_title = '-- --'
141     m = re.match ('.*?<title>(.*?)</title>', s, re.DOTALL)
142     if m:
143         fallback_web_title = m.group (1)
144     s = re.sub ('@WEB-TITLE@', fallback_web_title, s)
145     return s
146
147 info_nav_bar = re.compile (r'<div class="node">\s*<p>\s*<a name=".+?"></a>(.+?)<hr>\s*</div>', re.M | re.S)
148 info_footnote_hr = re.compile (r'<hr>\s*(</div>)?\s*</body>', re.M | re.I)
149
150 def add_footer (s):
151     """add footer
152
153 also add navigation bar to bottom of Info HTML pages"""
154     m = info_nav_bar.search (s)
155     if m:
156         # avoid duplicate <hr> in case there are footnotes at the end of the Info HTML page
157         if info_footnote_hr.search (s):
158             custom_footer = '<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
159         else:
160             custom_footer = '<br><hr>\n<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
161     else:
162         custom_footer = footer
163     if re.search ('(?i)</body', s):
164         s = re.sub ('(?i)</body>', footer_tag + custom_footer + '\n' + '</BODY>', s, 1)
165     elif re.search ('(?i)</html', s):                
166         s = re.sub ('(?i)</html>', footer_tag + custom_footer + '\n' + '</HTML>', s, 1)
167     else:
168         s += footer_tag + custom_footer + '\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 (lambda x, y: x and y, [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 def process_links (s, prefix, lang_ext, file_name, missing, target):
186     page_flavors = {}
187     if target == 'online':
188         # Strip .html, .png suffix for auto language selection (content
189         # negotiation).  The menu must keep the full extension, so do
190         # this before adding the menu.
191         page_flavors[file_name] = [lang_ext, re.sub (
192             '''(href|src)=[\'"]([^/][.]*[^.:\'"]*)(.html|.png)(#[^"\']*|)[\'"]''',
193             '\\1="\\2\\4"', s)]
194     elif target == 'offline':
195         # in LANG doc index: don't rewrite .html suffixes as not all .LANG.html pages exist
196         # the doc index should be translated and contain the right links
197         if prefix == 'Documentation/out-www/index':
198             page_flavors[file_name] = [lang_ext, s]
199         elif lang_ext == '':
200             page_flavors[file_name] = [lang_ext, s]
201             for e in missing:
202                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = [e, re.sub (
203                     '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
204                     'href="\\1.' + e + '\\2\\3"', s)]
205         else:
206             page_flavors[file_name] = [lang_ext, re.sub (
207                 '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
208                 'href="\\1.' + lang_ext + '\\2\\3"', s)]
209     return page_flavors
210
211 def add_menu (page_flavors, prefix, available, target, translation):
212     for k in page_flavors:
213         language_menu = ''
214         languages = ''
215         if page_flavors[k][0] != '':
216             t = translation[page_flavors[k][0]]
217         else:
218             t = _doc
219         for lang in available:
220             lang_file = lang.file_name (os.path.basename (prefix), '.html')
221             if language_menu != '':
222                 language_menu += ', '
223             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
224         if target == 'offline':
225             browser_language = ''
226         elif target == 'online':
227             browser_language = t (browser_lang) % browser_language_url
228         if language_menu:
229             language_available = t (lang_available) % language_menu
230             languages = LANGUAGES_TEMPLATE % vars ()
231         # put language menu before '</body>' and '</html>' tags
232         if re.search ('(?i)</body', page_flavors[k][1]):
233             page_flavors[k][1] = re.sub ('(?i)</body>', languages + '</BODY>', page_flavors[k][1], 1)
234         elif re.search ('(?i)</html', page_flavors[k][1]):
235             page_flavors[k][1] = re.sub ('(?i)</html>', languages + '</HTML>', page_flavors[k][1], 1)
236         else:
237             page_flavors[k][1] += languages
238     return page_flavors
239
240
241 def add_html_footer (package_name = '',
242                      package_version = '',
243                      target = 'offline',
244                      name_filter = lambda s: s):
245     """Add header, footer to a number of HTML files
246
247     Arguments:
248      package_name=NAME         set package_name to NAME
249      package_version=VERSION   set package version to VERSION
250      targets=offline|online    set page processing depending on the target
251           offline is for reading HTML pages locally
252           online is for hosting the HTML pages on a website with content
253             negotiation
254      name_filter               a HTML file name filter
255     """
256     translation = langdefs.translation
257     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
258
259     if "http://" in mail_address:
260         mail_address_url = mail_address
261     else:
262         mail_address_url= 'mailto:' + mail_address
263
264     versiontup = package_version.split ('.')
265     branch_str = _doc ('stable-branch')
266     if int (versiontup[1]) %  2:
267         branch_str = _doc ('development-branch')
268
269     # Initialize dictionaries for string formatting
270     subst = {}
271     subst[''] = dict ([i for i in globals ().items() if type (i[1]) is str])
272     subst[''].update (dict ([i for i in locals ().items() if type (i[1]) is str]))
273     for l in translation:
274         e = langdefs.LANGDICT[l].webext
275         if e:
276             subst[e] = {}
277             for name in subst['']:
278                 subst[e][name] = translation[l] (subst[''][name])
279     # Do deeper string formatting as early as possible,
280     # so only one '%' formatting pass is needed later
281     for e in subst:
282         subst[e]['footer_name_version'] = subst[e]['footer_name_version'] % subst[e]
283         subst[e]['footer_report_errors'] = subst[e]['footer_report_errors'] % subst[e]
284         subst[e]['footer_suggest_docs'] = subst[e]['footer_suggest_docs'] % subst[e]
285
286     for prefix, ext_list in pages_dict.items ():
287         for lang_ext in ext_list:
288             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
289             in_f = open (file_name)
290             s = in_f.read()
291             in_f.close()
292
293             s = re.sub ('%', '%%', s)
294             s = hack_urls (s, prefix)
295             s = add_header (s)
296
297             ### add footer
298             if re.search (footer_tag, s) == None:
299                 s = add_footer (s)
300                 
301                 available, missing = find_translations (prefix, lang_ext)
302                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
303                 # Add menu after stripping: must not have autoselection for language menu.
304                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
305             for k in page_flavors:
306                 page_flavors[k][1] = page_flavors[k][1] % subst[page_flavors[k][0]]
307                 out_f = open (name_filter (k), 'w')
308                 out_f.write (page_flavors[k][1])
309                 out_f.close()
310         # if the page is translated, a .en.html symlink is necessary for content negotiation
311         if target == 'online' and ext_list != ['']:
312             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))