]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
* python/lilylib.py: strip getopt support
[lilypond.git] / python / lilylib.py
1 ################################################################
2 # lilylib.py -- options and stuff
3
4 # source file of the GNU LilyPond music typesetter
5 #
6 # (c) 1998--2006 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8
9 ###  subst:\(^\|[^._a-z]\)\(abspath\|identify\|warranty\|progress\|warning\|error\|exit\|getopt_args\|option_help_str\|options_help_str\|help\|setup_temp\|read_pipe\|system\|cleanup_temp\|strip_extension\|cp_to_dir\|mkdir_p\|init\) *(
10 ###  replace:\1ly.\2 (
11
12 ### subst: \(help_summary\|keep_temp_dir_p\|option_definitions\|original_dir\|program_name\|pseudo_filter_p\|temp_dir\|verbose_p\)
13
14 import __main__
15 import glob
16 import os
17 import re
18 import shutil
19 import string
20 import sys
21 import tempfile
22 import optparse
23
24 ################################################################
25 # Users of python modules should include this snippet
26 # and customize variables below.
27
28 # We'll suffer this path init stuff as long as we don't install our
29 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
30 # it as we do with teTeX on Red Hat Linux: set some environment var
31 # (PYTHONPATH) in profile)
32
33 # If set, LILYPONDPREFIX must take prevalence
34 # if datadir is not set, we're doing a build and LILYPONDPREFIX
35
36 datadir = '@local_lilypond_datadir@'
37 if not os.path.isdir (datadir):
38         datadir = '@lilypond_datadir@'
39 if os.environ.has_key ('LILYPONDPREFIX') :
40         datadir = os.environ['LILYPONDPREFIX']
41         while datadir[-1] == os.sep:
42                 datadir= datadir[:-1]
43
44 sys.path.insert (0, os.path.join (datadir, 'python'))
45
46
47
48
49 localedir = '@localedir@'
50 try:
51         import gettext
52         gettext.bindtextdomain ('lilypond', localedir)
53         gettext.textdomain ('lilypond')
54         _ = gettext.gettext
55 except:
56         def _ (s):
57                 return s
58 underscore = _
59
60 def identify (port):
61         port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, __main__.program_version))
62
63 def warranty ():
64         identify (sys.stdout)
65         sys.stdout.write ('\n')
66         sys.stdout.write (_ ("Copyright (c) %s by") % '1998--2006')
67         sys.stdout.write ('\n')
68         map (lambda x: sys.stdout.write ('  %s\n' % x), __main__.copyright)
69         sys.stdout.write ('\n')
70         sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
71         sys.stdout.write ('\n')
72         sys.stdout.write (_ ("It comes with NO WARRANTY."))
73         sys.stdout.write ('\n')
74
75 def progress (s):
76         sys.stderr.write (s)
77
78 def warning (s):
79         sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
80
81 def error (s):
82         sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
83         
84 def exit (i):
85         be_verbose = get_global_option('verbose_p', 'verbose')
86         if be_verbose:
87                 raise _ ('Exiting (%d)...') % i
88         else:
89                 sys.exit (i)
90         
91 def lilypond_version (binary):
92         p = read_pipe ('%s --version ' % binary)
93
94         ls = p.split ('\n')
95         v= '<not found>'
96         for l in ls:
97                 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
98                 if m:
99                         v = m.group (1)
100                         
101         return v
102         
103 def lilypond_version_check (binary, req):
104         if req[0] <> '@' :
105                 v = lilypond_version (binary)
106                 if v <> req:
107                         error (_("Binary %s has version %s, looking for version %s") % \
108                                (binary, v, req))
109                         sys.exit (1)
110         
111         
112 def setup_temp ():
113         
114         ''' Create a temporary directory, and return its name. '''
115         
116         if not __main__.keep_temp_dir_p:
117                 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
118         try:
119                 os.mkdir (__main__.temp_dir, 0700)
120         except OSError:
121                 pass
122
123         return __main__.temp_dir
124
125 def command_name (cmd):
126         # Strip all stuf after command,
127         # deal with "((latex ) >& 1 ) .." too
128         cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
129         return os.path.basename (cmd)
130
131 def error_log (name):
132         name = re.sub('[^a-z]','x', name)
133         return tempfile.mktemp ('%s.errorlog' % name)
134
135 def read_pipe (cmd, mode = 'r'):
136         
137         
138         redirect = ''
139         error_log_file = ''
140         if be_verbose:
141                 progress (_ ("Opening pipe `%s\'") % cmd)
142         else:
143                 error_log_file = error_log (command_name (cmd))
144                 redirect = ' 2>%s' % error_log_file
145                 
146         pipe = os.popen (cmd + redirect, mode)
147         output = pipe.read ()
148         status = pipe.close ()
149         # successful pipe close returns 'None'
150         if not status:
151                 status = 0
152         signal = 0x0f & status
153         exit_status = status >> 8
154
155         if status:
156                 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
157                 
158                 if not be_verbose:
159                         contents = open (error_log_file).read ()
160                         if contents:
161                                 error (_ ("The error log is as follows:"))
162                                 sys.stderr.write (contents)
163
164                 # Ugh. code dup
165                 if error_log_file:
166                         os.unlink (error_log_file)
167
168                 exit (1)
169                 
170         if be_verbose:
171                 progress ('\n')
172
173         if error_log_file:
174                 os.unlink (error_log_file)
175                 
176         return output
177
178 def get_global_option (old, new):
179         try:
180                 return __main__.__dict__[old]
181         except KeyError:
182                 return __main__.global_options.__dict__[new]
183
184 def system (cmd, ignore_error = 0, progress_p = 0):
185         
186         '''System CMD.  If IGNORE_ERROR, do not complain when CMD
187 returns non zero.  If PROGRESS_P, always show progress.
188
189 RETURN VALUE
190
191 Exit status of CMD '''
192
193         name = command_name (cmd)
194         error_log_file = ''
195
196         ## UGH
197         be_verbose = get_global_option('verbose_p', 'verbose')
198         pseudo_filter = get_global_option ('pseudo_filter_p', 'pseudo_filter')
199         
200         if be_verbose:
201                 progress_p = 1
202                 progress (_ ("Invoking `%s\'") % cmd)
203         else:
204                 progress ( _("Running %s...") % name)
205
206         redirect = ''
207         if not progress_p:
208                 error_log_file = error_log (name)
209                 redirect = ' 1>/dev/null 2>' + error_log_file
210         elif pseudo_filter:
211                 redirect = ' 1>/dev/null'
212
213         status = os.system (cmd + redirect)
214         signal = 0x0f & status
215         exit_status = status >> 8
216         
217         if status:
218                 
219                 exit_type =  'status %d' % exit_status
220                 if signal:
221                         exit_type = 'signal %d' % signal 
222                 
223                 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
224                 if ignore_error:
225                         if be_verbose:
226                                 warning (msg + ' ' + _ ("(ignored)"))
227                 else:
228                         error (msg)
229                         if not progress_p and error_log_file:
230                                 error (_ ("The error log is as follows:"))
231                                 sys.stderr.write (open (error_log_file).read ())
232                         if error_log_file:
233                                 os.unlink (error_log_file)
234                         exit (1)
235
236         if error_log_file:
237                 os.unlink (error_log_file)
238         progress ('\n')
239         return status
240
241 def cleanup_temp ():
242         be_verbose = get_global_option('verbose_p', 'verbose')
243         if not __main__.keep_temp_dir_p:
244                 if be_verbose:
245                         progress (_ ("Cleaning %s...") % __main__.temp_dir)
246                 shutil.rmtree (__main__.temp_dir)
247                 if be_verbose:
248                         progress ('\n')
249
250
251 def strip_extension (f, ext):
252         (p, e) = os.path.splitext (f)
253         if e == ext:
254                 e = ''
255         return p + e
256
257
258 def cp_to_dir (pattern, dir):
259         "Copy files matching re PATTERN from cwd to DIR"
260         
261         # Duh.  Python style portable: cp *.EXT OUTDIR
262         # system ('cp *.%s %s' % (ext, outdir), 1)
263
264         files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
265         map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
266
267
268 def search_exe_path (name):
269         p = os.environ['PATH']
270         exe_paths = string.split (p, ':')
271         for e in exe_paths:
272                 full = os.path.join (e, name)
273                 if os.path.exists (full):
274                         return full
275         return None
276
277
278 def mkdir_p (dir, mode=0777):
279         if not os.path.isdir (dir):
280                 makedirs (dir, mode)
281
282 def print_environment ():
283         for (k,v) in os.environ.items ():
284                 sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
285
286
287 def ps_page_count (ps_name):
288         header = open (ps_name).read (1024)
289         m = re.search ('\n%%Pages: ([0-9]+)', header)
290         if m:
291                 return string.atoi (m.group (1))
292         return 0
293
294 def make_ps_images (ps_name, resolution = 90, papersize = "a4",
295                     rename_page1_p = 0):
296         base = os.path.basename (re.sub (r'\.e?ps', '', ps_name))
297         header = open (ps_name).read (1024)
298
299         png1 = base + '.png'
300         pngn = base + '-page%d.png'
301         output_file = pngn
302         multi_page = re.search ('\n%%Pages: ', header)
303
304         # png16m is because Lily produces color nowadays.
305         if not multi_page:
306
307                 # GS can produce empty 2nd page if pngn is used.
308                 output_file = png1
309                 cmd = r'''gs\
310                 -dEPSCrop\
311                 -dGraphicsAlphaBits=4\
312                 -dNOPAUSE\
313                 -dTextAlphaBits=4\
314                 -sDEVICE=png16m\
315                 -sOutputFile='%(output_file)s'\
316                 -sPAPERSIZE=%(papersize)s\
317                 -q\
318                 -r%(resolution)d\
319                 '%(ps_name)s'\
320                 -c showpage\
321                 -c quit ''' % vars ()
322         else:
323                 cmd = r'''gs\
324                 -s\
325                 -dGraphicsAlphaBits=4\
326                 -dNOPAUSE\
327                 -dTextAlphaBits=4\
328                 -sDEVICE=png16m\
329                 -sOutputFile='%(output_file)s'\
330                 -sPAPERSIZE=%(papersize)s\
331                 -q\
332                 -r%(resolution)d\
333                 '%(ps_name)s'\
334                 -c quit''' % vars ()
335
336         remove = glob.glob (png1) + glob.glob (base + '-page*.png')
337         map (os.unlink, remove)
338
339         status = system (cmd)
340         signal = 0xf & status
341         exit_status = status >> 8
342
343         if status:
344                 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
345                 map (os.unlink, remove)
346                 error (_ ("%s exited with status: %d") % ('GS', status))
347                 exit (1)
348
349         if rename_page1_p and multi_page:
350                 os.rename (pngn % 1, png1)
351         files = glob.glob (png1) + glob.glob (re.sub ('%d', '*', pngn))
352         return files
353
354 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
355     def format_heading(self, heading):
356             if heading:
357                     return heading[0].upper() + heading[1:] + ':\n'
358             return ''
359     def format_option_strings(self, option):
360             sep = ' '
361             if option._short_opts and option._long_opts:
362                     sep = ','
363
364             metavar = ''
365             if option.takes_value():
366                     metavar = '=%s' % option.metavar or option.dest.upper()
367
368             return "%3s%s %s%s" % (" ".join (option._short_opts),
369                                    sep,
370                                    " ".join (option._long_opts),
371                                    metavar)
372
373     def format_usage(self, usage):
374         return _("Usage: %s\n") % usage
375     
376     def format_description(self, description):
377             return description
378
379 def get_option_parser (*args, **kwargs): 
380         p = optparse.OptionParser (*args, **kwargs)
381         p.formatter = NonDentedHeadingFormatter () 
382         return p