]> git.donarmstrong.com Git - lilypond.git/blob - python/auxiliar/postprocess_html.py
Docs: reorganize documentation directory structure
[lilypond.git] / python / auxiliar / postprocess_html.py
1 #!@PYTHON@
2
3 """
4 Postprocess HTML files:
5 add footer, tweak links, add language selection menu.
6 """
7 import re
8 import os
9 import time
10 import operator
11
12 import langdefs
13
14 # This is to try to make the docball not too big with almost duplicate files
15 # see process_links()
16 non_copied_pages = ['Documentation/out-www/notation-big-page',
17                     'Documentation/out-www/internals-big-page',
18                     'Documentation/out-www/learning-big-page',
19                     'Documentation/out-www/application-big-page',
20                     'Documentation/out-www/music-glossary-big-page',
21                     'Documentation/out-www/contributor',
22                     'Documentation/out-www/changes',
23                     'Documentation/out-www/snippets',
24                     'out-www/examples',
25                     'Documentation/topdocs',
26                     'Documentation/bibliography',
27                     'Documentation/out-www/THANKS',
28                     'Documentation/out-www/DEDICATION',
29                     'input/']
30
31 def _doc (s):
32     return s
33
34 header = r"""
35 """
36
37 footer = '''
38 <div class="footer">
39 <p class="footer_version">
40 %(footer_name_version)s
41 </p>
42 <p class="footer_report">
43 %(footer_report_links)s
44 </p>
45 </div>
46 '''
47 footer_name_version = _doc ('This page is for %(package_name)s-%(package_version)s (%(branch_str)s).')
48 # ugh, must not have "_doc" in strings because it is naively replaced with "_" in hacked gettext process
49 footer_report_links = _doc ('Your <a href="%(suggest_Docs_url)s">suggestions for the documentation</a> are welcome, please report errors to our <a href="%(mail_address_url)s">bug list</a>.')
50
51
52 mail_address = 'http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs'
53 suggest_Docs_url = 'http://lilypond.org/web/devel/participating/documentation-adding'
54
55 header_tag = '<!-- header_tag -->'
56 header_tag_re = re.compile (header_tag)
57
58 footer_tag = '<!-- footer_tag -->'
59 footer_tag_re = re.compile (footer_tag)
60
61 lang_available = _doc ("Other languages: %s.")
62 browser_lang = _doc ('About <A HREF="%s">automatic language selection</A>.')
63 browser_language_url = "/web/about/browser-language"
64
65 LANGUAGES_TEMPLATE = '''
66 <p id="languages">
67  %(language_available)s
68  <br>
69  %(browser_language)s
70 </p>
71 '''
72
73
74 html_re = re.compile ('(.*?)(?:[.]([^/.]*))?[.]html$')
75 pages_dict = {}
76
77 def build_pages_dict (filelist):
78     """Build dictionary of available translations of each page"""
79     global pages_dict
80     for f in filelist:
81         m = html_re.match (f)
82         if m:
83             g = m.groups()
84             if len (g) <= 1 or g[1] == None:
85                 e = ''
86             else:
87                 e = g[1]
88             if not g[0] in pages_dict:
89                 pages_dict[g[0]] = [e]
90             else:
91                 pages_dict[g[0]].append (e)
92
93 def source_links_replace (m, source_val):
94     return 'href="' + os.path.join (source_val, m.group (1)) + '"'
95
96 splitted_docs_re = re.compile ('(Documentation/out-www/(notation|\
97 music-glossary|application|learning|snippets))/')
98
99 docindex_link_re = re.compile (r'href="index.html"')
100
101
102 ## Windows does not support symlinks.
103 # This function avoids creating symlinks for splitted HTML manuals
104 # Get rid of symlinks in GNUmakefile.in (local-WWW-post)
105 # this also fixes missing PNGs only present in translated docs
106 def hack_urls (s, prefix):
107     if splitted_docs_re.match (prefix):
108         s = re.sub ('(href|src)="(../lily-.*?|.*?[.]png)"', '\\1="../\\2"', s)
109
110     # we also need to replace in the lsr, which is already processed above!
111     if 'input/' in prefix or 'Documentation/topdocs' in prefix or \
112             'Documentation/contributor' in prefix:
113         # fix the link from the regtest, lsr and topdoc pages to the doc index 
114         # (rewrite prefix to obtain the relative path of the doc index page)
115         rel_link = re.sub (r'out-www/.*$', '', prefix)
116         rel_link = re.sub (r'[^/]*/', '../', rel_link)
117         if 'input/regression' in prefix or 'Documentation/contributor' in prefix:
118             indexfile = "Documentation/devel"
119         else:
120             indexfile = "index"
121         s = docindex_link_re.sub ('href="' + rel_link + indexfile + '.html\"', 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 css_re = re.compile ('(?i)<link rel="stylesheet" type="text/css" ([^>]*)href="[^">]*?lilypond.*\.css"([^>]*)>')
134 end_head_tag_re = re.compile ('(?i)</head>')
135 css_link = """    <link rel="stylesheet" type="text/css" title="Patrick McCarty's design" href="%(rel)sDocumentation/lilypond-mccarty.css">
136     <link rel="alternate stylesheet" type="text/css" href="%(rel)sDocumentation/lilypond.css" title="Andrew Hawryluk's design">
137     <link rel="alternate stylesheet" type="text/css" href="%(rel)sDocumentation/lilypond-blue.css" title="Kurt Kroon's blue design">
138     <!--[if lte IE 7]>
139     <link href="%(rel)sDocumentation/lilypond-ie-fixes.css" rel="stylesheet" type="text/css">
140     <![endif]-->
141 """
142
143
144 def add_header (s, prefix):
145     """Add header (<body>, doctype and CSS)"""
146     if header_tag_re.search (s) == None:
147         body = '<body\\1>'
148         (s, n) = body_tag_re.subn (body + header, s, 1)
149         if not n:
150             (s, n) = html_tag_re.subn ('<html>' + header, s, 1)
151             if not n:
152                 s = header + s
153
154         s = header_tag + '\n' + s
155
156         if doctype_re.search (s) == None:
157             s = doctype + s
158
159         if css_re.search (s) == None:
160             depth = (prefix.count ('/') - 1) * '../'
161             s = end_head_tag_re.sub ((css_link % {'rel': depth}) + '</head>', s)
162     return s
163
164 title_tag_re = re.compile ('.*?<title>(.*?)</title>', re.DOTALL)
165 AT_web_title_re = re.compile ('@WEB-TITLE@')
166
167 def add_title (s):
168     # urg
169     # maybe find first node?
170     fallback_web_title = '-- --'
171     m = title_tag_re.match (s)
172     if m:
173         fallback_web_title = m.group (1)
174     s = AT_web_title_re.sub (fallback_web_title, s)
175     return s
176
177 footer_insert_re = re.compile ('<!--\s*FOOTER\s*-->')
178 end_body_re = re.compile ('(?i)</body>')
179 end_html_re = re.compile ('(?i)</html>')
180
181 def add_footer (s, footer_text):
182     """add footer"""
183     (s, n) = footer_insert_re.subn (footer_text + '\n' + '<!-- FOOTER -->', s, 1)
184     if not n:
185         (s, n) = end_body_re.subn (footer_text + '\n' + '</body>', s, 1)
186     if not n:
187         (s, n) = end_html_re.subn (footer_text + '\n' + '</html>', s, 1)
188     if not n:
189         s += footer_text + '\n'
190     return s
191
192 def find_translations (prefix, lang_ext):
193     """find available translations of a page"""
194     available = []
195     missing = []
196     for l in langdefs.LANGUAGES:
197         e = l.webext
198         if lang_ext != e:
199             if e in pages_dict[prefix]:
200                 available.append (l)
201             elif lang_ext == '' and l.enabled and reduce (operator.and_,
202                                                           [not prefix.startswith (s)
203                                                            for s in non_copied_pages]):
204                 # English version of missing translated pages will be written
205                 missing.append (e)
206     return available, missing
207
208 online_links_re = re.compile ('''(href|src)=['"]\
209 ((?!Compiling-from-source.html")[^/][.]*[^.:'"]*)\
210 ([.]html)(#[^"']*|)['"]''')
211 offline_links_re = re.compile ('href=[\'"]\
212 ((?!Compiling-from-source.html")[^/][.]*[^.:\'"]*)([.]html)(#[^"\']*|)[\'"]')
213 big_page_name_re = re.compile ('''(.+?)-big-page''')
214
215 def process_i18n_big_page_links (match, prefix, lang_ext):
216     big_page_name = big_page_name_re.match (match.group (1))
217     if big_page_name:
218         destination_path = os.path.normpath (os.path.join (os.path.dirname (prefix),
219                                                            big_page_name.group (0)))
220         if not (destination_path in pages_dict and
221                 lang_ext in pages_dict[destination_path]):
222             return match.group (0)
223     return 'href="' + match.group (1) + '.' + lang_ext \
224         + match.group (2) + match.group (3) + '"'
225
226 def process_links (s, prefix, lang_ext, file_name, missing, target):
227     page_flavors = {}
228     if target == 'online':
229         # Strip .html, suffix for auto language selection (content
230         # negotiation).  The menu must keep the full extension, so do
231         # this before adding the menu.
232         page_flavors[file_name] = \
233             [lang_ext, online_links_re.sub ('\\1="\\2\\4"', s)]
234     elif target == 'offline':
235         # in LANG doc index: don't rewrite .html suffixes
236         # as not all .LANG.html pages exist;
237         # the doc index should be translated and contain links with the right suffixes
238         # idem for NEWS
239         if prefix in ('Documentation/out-www/index', 'Documentation/topdocs/out-www/NEWS'):
240             page_flavors[file_name] = [lang_ext, s]
241         elif lang_ext == '':
242             page_flavors[file_name] = [lang_ext, s]
243             for e in missing:
244                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = \
245                     [e, offline_links_re.sub ('href="\\1.' + e + '\\2\\3"', s)]
246         else:
247             # For saving bandwidth and disk space, we don't duplicate big pages
248             # in English, so we must process translated big pages links differently.
249             if 'big-page' in prefix:
250                 page_flavors[file_name] = \
251                     [lang_ext,
252                      offline_links_re.sub \
253                          (lambda match: process_i18n_big_page_links (match, prefix, lang_ext),
254                           s)]
255             else:
256                 page_flavors[file_name] = \
257                     [lang_ext,
258                      offline_links_re.sub ('href="\\1.' + lang_ext + '\\2\\3"', s)]
259     return page_flavors
260
261 def add_menu (page_flavors, prefix, available, target, translation):
262     for k in page_flavors:
263         language_menu = ''
264         languages = ''
265         if page_flavors[k][0] != '':
266             t = translation[page_flavors[k][0]]
267         else:
268             t = _doc
269         for lang in available:
270             lang_file = lang.file_name (os.path.basename (prefix), '.html')
271             if language_menu != '':
272                 language_menu += ', '
273             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
274         if target == 'offline':
275             browser_language = ''
276         elif target == 'online':
277             browser_language = t (browser_lang) % browser_language_url
278         if language_menu:
279             language_available = t (lang_available) % language_menu
280             languages = LANGUAGES_TEMPLATE % vars ()
281         page_flavors[k][1] = add_footer (page_flavors[k][1], languages)
282     return page_flavors
283
284
285 def process_html_files (package_name = '',
286                         package_version = '',
287                         target = 'offline',
288                         name_filter = lambda s: s):
289     """Add header, footer and tweak links to a number of HTML files
290
291     Arguments:
292      package_name=NAME         set package_name to NAME
293      package_version=VERSION   set package version to VERSION
294      targets=offline|online    set page processing depending on the target
295           offline is for reading HTML pages locally
296           online is for hosting the HTML pages on a website with content
297             negotiation
298      name_filter               a HTML file name filter
299     """
300     translation = langdefs.translation
301     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
302
303     if "http://" in mail_address:
304         mail_address_url = mail_address
305     else:
306         mail_address_url= 'mailto:' + mail_address
307
308     versiontup = package_version.split ('.')
309     branch_str = _doc ('stable-branch')
310     if int (versiontup[1]) %  2:
311         branch_str = _doc ('development-branch')
312
313     # Initialize dictionaries for string formatting
314     subst = {}
315     subst[''] = dict ([i for i in globals ().items() if type (i[1]) is str])
316     subst[''].update (dict ([i for i in locals ().items() if type (i[1]) is str]))
317     for l in translation:
318         e = langdefs.LANGDICT[l].webext
319         if e:
320             subst[e] = {}
321             for name in subst['']:
322                 subst[e][name] = translation[l] (subst[''][name])
323     # Do deeper string formatting as early as possible,
324     # so only one '%' formatting pass is needed later
325     for e in subst:
326         subst[e]['footer_name_version'] = subst[e]['footer_name_version'] % subst[e]
327         subst[e]['footer_report_links'] = subst[e]['footer_report_links'] % subst[e]
328
329     for prefix, ext_list in pages_dict.items ():
330         for lang_ext in ext_list:
331             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
332             in_f = open (file_name)
333             s = in_f.read()
334             in_f.close()
335
336             s = s.replace ('%', '%%')
337             s = hack_urls (s, prefix)
338             s = add_header (s, prefix)
339
340             ### add footer
341             if footer_tag_re.search (s) == None:
342                 s = add_footer (s, footer_tag + footer)
343
344                 available, missing = find_translations (prefix, lang_ext)
345                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
346                 # Add menu after stripping: must not have autoselection for language menu.
347                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
348             for k in page_flavors:
349                 page_flavors[k][1] = page_flavors[k][1] % subst[page_flavors[k][0]]
350                 out_f = open (name_filter (k), 'w')
351                 out_f.write (page_flavors[k][1])
352                 out_f.close()
353         # if the page is translated, a .en.html symlink is necessary for content negotiation
354         if target == 'online' and ext_list != ['']:
355             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))