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