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