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