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