]> git.donarmstrong.com Git - lilypond.git/blob - stepmake/bin/add-html-footer.py
Fix some bugs in the dynamic engraver and PostScript backend
[lilypond.git] / stepmake / bin / add-html-footer.py
1 #!@PYTHON@
2
3 """
4 Print a nice footer.  add the top of the ChangeLog file (up to the ********)
5 """
6 import re
7 import sys
8 import os
9 import time
10 import string 
11 import getopt
12
13 gcos = "unknown"
14 index_url=''
15 top_url=''
16 changelog_file=''
17 package_name = ''
18 package_version = ''
19
20 mail_address = '(address unknown)'
21 try:
22     mail_address= os.environ['MAILADDRESS']
23 except KeyError:
24     pass
25
26 mail_address_url= 'mailto:' + mail_address
27 if re.search ("http://", mail_address):
28     mail_address_url = mail_address
29     
30 webmaster= mail_address
31 try:
32     webmaster= os.environ['WEBMASTER']
33 except KeyError:
34     pass
35
36 header_file = ''
37 footer_file = ''
38 default_header = r"""
39 """
40
41
42 #wiki_base = 'http://afavant.elte.hu/lywiki/'
43 wiki_base = None 
44
45
46 default_footer = r"""<hr>Please take me <a href=@INDEX@>back to the index</a>
47 of @PACKAGE_NAME@
48 """
49
50 built = r"""
51 <div style="background-color: #e8ffe8; padding: 2; border: #c0ffc0 1px solid;">
52 %(wiki_string)s
53 <p>
54 <font size="-1">
55 This page is for %(package_name)s-%(package_version)s (%(branch_str)s). <br>
56 </font>
57 <address><font size="-1">
58 Report errors to <a href="%(mail_address_url)s">%(mail_address)s</a>.</font></address>
59 </p>
60 </div>
61 """
62
63
64 def gulp_file (f):
65     try:
66         i = open(f)
67         i.seek (0, 2)
68         n = i.tell ()
69         i.seek (0,0)
70     except:
71         sys.stderr.write ("can't open file: %s\n" % f)
72         return ''
73     s = i.read (n)
74     if len (s) <= 0:
75         sys.stderr.write ("gulped empty file: %s\n" % f)
76     i.close ()
77     return s
78
79 def help ():
80     sys.stdout.write (r"""Usage: add-html-footer [OPTIONS]... HTML-FILE
81 Add header, footer and top of ChangLog file (up to the ********) to HTML-FILE
82
83 Options:
84  --changelog=FILE          use FILE as ChangeLog [ChangeLog]
85  --footer=FILE             use FILE as footer
86  --header=FILE             use FILE as header
87  -h, --help                print this help
88  --index=URL               set homepage to URL
89  --name=NAME               set package_name to NAME
90  --version=VERSION         set package version to VERSION
91
92 """)
93     sys.exit (0)
94
95 (options, files) = getopt.getopt(sys.argv[1:], 'h', [
96     'changelog=', 'footer=', 'header=', 'help', 'index=',
97     'name=', 'version=']) 
98
99 for opt in options:
100     o = opt[0]
101     a = opt[1]
102     if o == '--changelog':
103         changelog_file = a
104     elif o == '--footer':
105         footer_file = a
106     elif o == '--header':
107         header_file = a
108     elif o == '-h' or o == '--help':
109         help ()
110     # urg, this is top!
111     elif o == '--index':
112         index_url = a
113     elif o == '--name':
114         package_name = a
115     elif o == '--version':
116         package_version = a
117     else:
118         raise 'unknown opt ', o
119
120 #burp?
121 def set_gcos ():
122     global gcos
123     os.environ["CONFIGSUFFIX"] = 'www';
124     if os.name == 'nt':
125         import ntpwd
126         pw = ntpwd.getpwname(os.environ['USERNAME'])
127     else:
128         import pwd
129         if os.environ.has_key('FAKEROOTKEY') and os.environ.has_key('LOGNAME'):
130             pw = pwd.getpwnam (os.environ['LOGNAME'])
131         else:
132             pw = pwd.getpwuid (os.getuid())
133
134     f = pw[4]
135     f = string.split (f, ',')[0]
136     gcos = f 
137
138 def compose (default, file):
139     s = default
140     if file:
141         s = gulp_file (file)
142     return s
143
144 set_gcos ()
145 localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
146
147 if os.path.basename (index_url) != "index.html":
148     index_url = os.path.join (index_url , "index.html")
149 top_url = os.path.dirname (index_url) + "/"
150
151 header = compose (default_header, header_file)
152
153 # compose (default_footer, footer_file)
154 footer =  built
155 header_tag = '<!-- header_tag -->'
156 footer_tag = '<!-- footer_tag -->'
157
158 # Python < 1.5.2 compatibility
159 #
160 # On most platforms, this is equivalent to
161 #`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
162 if os.path.__dict__.has_key ('abspath'):
163     abspath = os.path.abspath
164 else:
165     def abspath (path):
166         return os.path.normpath (os.path.join (os.getcwd (), path))
167
168
169 def remove_self_ref (s):        
170     self_url = abspath (os.getcwd () + '/' + f)
171     #sys.stderr.write ('url0: %s\n' % self_url)
172
173     # self_url = re.sub ('.*?' + string.lower (package_name) + '[^/]*/',
174     #                 '', self_url)
175     # URG - this only works when source tree is unpacked in `src/' dir
176     # For some reason, .*? still eats away
177     #     /home/fred/usr/src/lilypond-1.5.14/Documentation/user/out-www/lilypond/
178     # instead of just
179     #
180     #     /home/fred/usr/src/lilypond-1.5.14/
181     #
182     #     Tutorial.html
183     self_url = re.sub ('.*?src/' + string.lower (package_name) + '[^/]*/',
184             '', self_url)
185
186     #sys.stderr.write ('url1: %s\n' % self_url)
187     
188     #urg, ugly lily-specific toplevel index hack
189     self_url = re.sub ('.*topdocs/out-www/index.html', 'index.html', self_url)
190     #sys.stderr.write ('url2: %s\n' % self_url)
191
192     # ugh, python2.[12] re is broken.
193     ## pat = re.compile ('.*?(<a href="[\./]*' + self_url + '#?[^"]*">)([^<]*)(</a>)', re.DOTALL)
194     pat = re.compile ('[.\n]*?(<a href="[\./]*' + self_url + '#?[^"]*">)([^<]*)(</a>)')
195     m = pat.search (s)
196     while m:
197         #sys.stderr.write ('self: %s\n' % m.group (2))
198         s = s[:m.start (1)] + m.group (2) + s[m.end (3):]
199         m = pat.search (s)
200     return s
201
202 def do_file (f):
203     s = gulp_file (f)
204     s = re.sub ('%', '%%', s)
205
206
207     if re.search (header_tag, s) == None:
208         body = '<BODY BGCOLOR=WHITE TEXT=BLACK>'
209         s = re.sub ('(?i)<body>', body, s)
210         if re.search ('(?i)<BODY', s):
211             s = re.sub ('(?i)<body[^>]*>', body + header, s, 1)
212         elif re.search ('(?i)<html', s):                
213             s = re.sub ('(?i)<html>', '<HTML>' + header, s, 1)
214         else:
215             s = header + s
216
217         s = header_tag + '\n' + s
218
219         if re.search ('(?i)<!DOCTYPE', s) == None:
220             doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
221             s = doctype + s
222
223     if re.search (footer_tag, s) == None:
224         if re.search ('(?i)</body', s):
225             s = re.sub ('(?i)</body>', footer_tag + footer + '\n' + '</BODY>', s, 1)
226         elif re.search ('(?i)</html', s):                
227             s = re.sub ('(?i)</html>', footer_tag + footer + '\n' + '</HTML>', s, 1)
228         else:
229             s = s + footer_tag + footer + '\n'
230
231         s = i18n (f, s)
232
233     #URUGRGOUSNGUOUNRIU
234     index = index_url
235     top = top_url
236     if os.path.basename (f) == "index.html":
237         cwd = os.getcwd ()
238         if os.path.basename (cwd) == "topdocs":
239             index = "index.html"
240             top = ""
241
242         # don't cause ///////index.html entries in log files.
243         #        index = "./index.html"
244         #        top = "./"
245             
246     versiontup = string.split(package_version, '.')
247     branch_str = 'stable-branch'
248     if string.atoi ( versiontup[1]) %  2:
249         branch_str = 'development-branch'
250
251     wiki_page = ('v%s.%s-' % (versiontup[0], versiontup[1]) +  f)
252     wiki_page = re.sub ('out-www/', '', wiki_page)
253     wiki_page = re.sub ('/', '-', wiki_page) 
254     wiki_page = re.sub (r'\.-', '', wiki_page) 
255     wiki_page = re.sub ('.html', '', wiki_page)
256
257     wiki_string = ''
258
259     if wiki_base:
260         wiki_string = (r'''<a href="%(wiki_base)s%(wiki_page)s">Read </a> comments on this page, or
261         <a href="%(wiki_base)s%(wiki_page)s?action=edit">add</a> one.''' % 
262                { 'wiki_base': wiki_base,
263                 'wiki_page': wiki_page})
264         
265     subst = globals ()
266     subst.update (locals())
267     s = s % subst
268
269     # urg
270     # maybe find first node?
271     fallback_web_title = '-- --'
272
273     # ugh, python2.[12] re is broken.
274     #m = re.match ('.*?<title>\(.*?\)</title>', s, re.DOTALL)
275     m = re.match ('[.\n]*?<title>([.\n]*?)</title>', s)
276     if m:
277         fallback_web_title = m.group (1)
278     s = re.sub ('@WEB-TITLE@', fallback_web_title, s)
279     
280     s = remove_self_ref (s)
281
282     # remove info's annoying's indication of referencing external document
283     s = re.sub (' \((lilypond|lilypond-internals|music-glossary)\)</a>',
284           '</a>', s)
285
286     open (f, 'w').write (s)
287
288
289
290 localedir = 'out/locale'
291 try:
292     import gettext
293     gettext.bindtextdomain ('newweb', localedir)
294     gettext.textdomain ('newweb')
295     _ = gettext.gettext
296 except:
297     def _ (s):
298         return s
299 underscore = _
300
301
302 LANGUAGES = (
303     ('site', 'English'),
304     ('nl', 'Nederlands'),
305     )
306
307 language_available = _ ("Other languages: %s.") % "%(language_menu)s"
308 browser_language = _ ("Using <A HREF='%s'>automatic language selection</A>.") \
309            % "%(root_url)sabout/browser-language"
310
311 LANGUAGES_TEMPLATE = '''\
312 <P>
313  %(language_available)s
314  <BR>
315  %(browser_language)s
316 </P>
317 ''' % vars ()
318
319 def file_lang (file, lang):
320     (base, ext) = os.path.splitext (file)
321     base = os.path.splitext (base)[0]
322     if lang and lang != 'site':
323         return base + '.' + lang + ext
324     return base + ext
325
326
327 def i18n (file_name, page):
328     # ugh
329     root_url = "/web/"
330
331     base_name = os.path.basename (file_name)
332
333     lang = 'site'
334     m = re.match ('.*[.]([^.]*).html', file_name)
335     if m:
336         lang = m.group (1)
337
338     # Find available translations of this page.
339     available = filter (lambda x: lang != x[0] \
340               and os.path.exists (file_lang (file_name, x[0])),
341               LANGUAGES)
342
343     # Strip .html, .png suffix for auto language selection.
344 #        page = re.sub ('''(href|src)=[\'"]([^/][.]*[^.:\'"]*)(.html(#[^"]*)|.png)[\'"]''',
345 #                       '\\1="\\2"', page)
346
347     # Create language menu.
348     language_menu = ''
349     for (prefix, name) in available:
350         lang_file = file_lang (base_name, prefix)
351         language_menu += '<a href="%(lang_file)s">%(name)s</a>' % vars ()
352
353     languages = ''
354     if language_menu:
355         languages = LANGUAGES_TEMPLATE % vars ()
356
357     # Put language menu before '</body>' and '</html>' tags
358     if re.search ('(?i)</body', page):
359         page = re.sub ('(?i)</body>', languages + '</BODY>', page, 1)
360     elif re.search ('(?i)</html', page):                
361         page = re.sub ('(?i)</html>', languages + '</HTML>', page, 1)
362     else:
363         page = page + languages
364
365     return page
366     ## end i18n
367
368 for f in files:
369     do_file (f)
370