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