]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/add_html_footer.py
Merge branch 'master' into dev/texi2html
[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 user_ref_re = re.compile (r'href="(?:\.\./)?lilypond(|-internals|-learning|-program)')
98
99 ## Windows does not support symlinks.
100 # This function avoids creating symlinks for splitted HTML manuals
101 # Get rid of symlinks in GNUmakefile.in (local-WWW-post)
102 # this also fixes missing PNGs only present in translated docs
103 def hack_urls (s, prefix):
104     if splitted_docs_re.match (prefix):
105         s = re.sub ('(href|src)="(../lily-.*?|.*?[.]png)"', '\\1="../\\2"', s)
106
107     # fix xrefs between documents in different directories ad hoc
108     if 'user/out-www/lilypond' in prefix:
109         s = snippets_ref_re.sub ('href="source/input/lsr/lilypond-snippets', s)
110     elif 'input/lsr' in prefix:
111         s = user_ref_re.sub ('href="source/Documentation/user/lilypond\\1', s)
112
113     source_path = os.path.join (os.path.dirname (prefix), 'source')
114     if not os.path.islink (source_path):
115         return s
116     source_val = os.readlink (source_path)
117     return re.sub ('href="source/(.*?)"', lambda m: source_links_replace (m, source_val), s)
118
119 body_tag_re = re.compile ('(?i)<body([^>]*)>')
120 html_tag_re = re.compile ('(?i)<html>')
121 doctype_re = re.compile ('(?i)<!DOCTYPE')
122 doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
123
124 def add_header (s):
125     """Add header (<body> and doctype)"""
126     if header_tag_re.search (s) == None:
127         body = '<body bgcolor="white" text="black" \\1>'
128         (s, n) = body_tag_re.subn (body + header, s, 1)
129         if not n:
130             (s, n) = html_tag_re.subn ('<html>' + header, s, 1)
131             if not n:
132                 s = header + s
133
134         s = header_tag + '\n' + s
135
136         if doctype_re.search (s) == None:
137             s = doctype + s
138         return s
139
140 title_tag_re = re.compile ('.*?<title>(.*?)</title>', re.DOTALL)
141 AT_web_title_re = re.compile ('@WEB-TITLE@')
142
143 def add_title (s):
144     # urg
145     # maybe find first node?
146     fallback_web_title = '-- --'
147     m = title_tag_re.match (s)
148     if m:
149         fallback_web_title = m.group (1)
150     s = AT_web_title_re.sub (fallback_web_title, s)
151     return s
152
153 end_body_re = re.compile ('(?i)</body>')
154 end_html_re = re.compile ('(?i)</html>')
155
156 def add_footer (s):
157     """add footer"""
158     (s, n) = end_body_re.subn (footer_tag + footer + '\n' + '</body>', s, 1)
159     if not n:
160         (s, n) = end_html_re.subn (footer_tag + footer + '\n' + '</html>', s, 1)
161         if not n:
162             s += footer_tag + footer + '\n'
163     return s
164
165 def find_translations (prefix, lang_ext):
166     """find available translations of a page"""
167     available = []
168     missing = []
169     for l in langdefs.LANGUAGES:
170         e = l.webext
171         if lang_ext != e:
172             if e in pages_dict[prefix]:
173                 available.append (l)
174             elif lang_ext == '' and l.enabled and reduce (operator.and_, [not prefix.startswith (s) for s in non_copied_pages]):
175                 # English version of missing translated pages will be written
176                 missing.append (e)
177     return available, missing
178
179 online_links_re = re.compile ('''(href|src)=[\'"]([^/][.]*[^.:\'"]*)(.html|.png)(#[^"\']*|)[\'"]''')
180 offline_links_re = re.compile ('''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''')
181
182 def process_links (s, prefix, lang_ext, file_name, missing, target):
183     page_flavors = {}
184     if target == 'online':
185         # Strip .html, .png suffix for auto language selection (content
186         # negotiation).  The menu must keep the full extension, so do
187         # this before adding the menu.
188         page_flavors[file_name] = \
189             [lang_ext, online_links_re.sub ('\\1="\\2\\4"', s)]
190     elif target == 'offline':
191         # in LANG doc index: don't rewrite .html suffixes
192         # as not all .LANG.html pages exist;
193         # the doc index should be translated and contain the right links
194         if prefix == 'Documentation/out-www/index':
195             page_flavors[file_name] = [lang_ext, s]
196         elif lang_ext == '':
197             page_flavors[file_name] = [lang_ext, s]
198             for e in missing:
199                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = \
200                     [e, offline_links_re.sub ('href="\\1.' + e + '\\2\\3"', s)]
201         else:
202             page_flavors[file_name] = \
203                 [lang_ext,
204                  offline_links_re.sub ('href="\\1.' + lang_ext + '\\2\\3"', s)]
205     return page_flavors
206
207 def add_menu (page_flavors, prefix, available, target, translation):
208     for k in page_flavors:
209         language_menu = ''
210         languages = ''
211         if page_flavors[k][0] != '':
212             t = translation[page_flavors[k][0]]
213         else:
214             t = _doc
215         for lang in available:
216             lang_file = lang.file_name (os.path.basename (prefix), '.html')
217             if language_menu != '':
218                 language_menu += ', '
219             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
220         if target == 'offline':
221             browser_language = ''
222         elif target == 'online':
223             browser_language = t (browser_lang) % browser_language_url
224         if language_menu:
225             language_available = t (lang_available) % language_menu
226             languages = LANGUAGES_TEMPLATE % vars ()
227         # put language menu before '</body>' and '</html>' tags
228         (page_flavors[k][1], n) = end_body_re.subn (languages + '</body>', page_flavors[k][1], 1)
229         if not n:
230             (page_flavors[k][1], n) = end_html_re.subn (languages + '</html>', page_flavors[k][1], 1)
231             if not n:
232                 page_flavors[k][1] += languages
233     return page_flavors
234
235
236 def add_html_footer (package_name = '',
237                      package_version = '',
238                      target = 'offline',
239                      name_filter = lambda s: s):
240     """Add header, footer to a number of HTML files
241
242     Arguments:
243      package_name=NAME         set package_name to NAME
244      package_version=VERSION   set package version to VERSION
245      targets=offline|online    set page processing depending on the target
246           offline is for reading HTML pages locally
247           online is for hosting the HTML pages on a website with content
248             negotiation
249      name_filter               a HTML file name filter
250     """
251     translation = langdefs.translation
252     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
253
254     if re.search ("http://", mail_address):
255         mail_address_url = mail_address
256     else:
257         mail_address_url= 'mailto:' + mail_address
258
259     versiontup = package_version.split ('.')
260     branch_str = _doc ('stable-branch')
261     if int (versiontup[1]) %  2:
262         branch_str = _doc ('development-branch')
263
264     for prefix, ext_list in pages_dict.items ():
265         for lang_ext in ext_list:
266             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
267             in_f = open (file_name)
268             s = in_f.read()
269             in_f.close()
270
271             s = s.replace ('%', '%%')
272             s = hack_urls (s, prefix)
273             s = add_header (s)
274
275             ### add footer
276             if footer_tag_re.search (s) == None:
277                 s = add_footer (s)
278                 
279                 available, missing = find_translations (prefix, lang_ext)
280                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
281                 # Add menu after stripping: must not have autoselection for language menu.
282                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
283             subst = dict ([i for i in globals().items() if type (i[1]) is str])
284             subst.update (dict ([i for i in locals().items() if type (i[1]) is str]))
285             for k in page_flavors:
286                 if page_flavors[k][0] in translation:
287                     for name in subst:
288                         subst[name] = translation[page_flavors[k][0]] (subst[name])
289                 subst['footer_name_version'] = subst['footer_name_version'] % subst
290                 subst['footer_report_errors'] = subst['footer_report_errors'] % subst
291                 subst['footer_suggest_docs'] = subst['footer_suggest_docs'] % subst
292                 page_flavors[k][1] = page_flavors[k][1] % subst
293                 out_f = open (name_filter (k), 'w')
294                 out_f.write (page_flavors[k][1])
295                 out_f.close()
296         # if the page is translated, a .en.html symlink is necessary for content negotiation
297         if target == 'online' and ext_list != ['']:
298             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))