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