]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
* make/lilypond-vars.make (PYTHONPATH): Add python's outdir to
[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--2002  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 shutil
16 import sys
17 import tempfile
18
19 ################################################################
20 # Users of python modules should include this snippet
21 # and customize variables below.
22
23 # We'll suffer this path init stuff as long as we don't install our
24 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
25 # it as we do with teTeX on Red Hat Linux: set some environment var
26 # (PYTHONPATH) in profile)
27
28 # If set, LILYPONDPREFIX must take prevalence
29 # if datadir is not set, we're doing a build and LILYPONDPREFIX
30 import getopt, os, sys
31 datadir = '@local_lilypond_datadir@'
32 if not os.path.isdir (datadir):
33         datadir = '@lilypond_datadir@'
34 if os.environ.has_key ('LILYPONDPREFIX') :
35         datadir = os.environ['LILYPONDPREFIX']
36         while datadir[-1] == os.sep:
37                 datadir= datadir[:-1]
38
39 sys.path.insert (0, os.path.join (datadir, 'python'))
40
41 # Customize these
42 if __name__ == '__main__':
43         import lilylib as ly
44         global _;_=ly._
45
46         # lilylib globals
47         program_name = 'unset'
48         original_dir = os.getcwd ()
49         temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
50         keep_temp_dir_p = 0
51         verbose_p = 0
52
53         help_summary = _ ("lilylib module")
54
55         option_definitions = [
56                 ('', 'h', 'help', _ ("this help")),
57                 ]
58
59         from lilylib import *
60 ################################################################
61
62 # Handle bug in Python 1.6-2.1
63 #
64 # there are recursion limits for some patterns in Python 1.6 til 2.1. 
65 # fix this by importing pre instead. Fix by Mats.
66
67 # todo: should check Python version first.
68 try:
69         import pre
70         re = pre
71         del pre
72 except ImportError:
73         import re
74
75 # Attempt to fix problems with limited stack size set by Python!
76 # Sets unlimited stack size. Note that the resource module only
77 # is available on UNIX.
78 try:
79        import resource
80        resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
81 except:
82        pass
83
84 try:
85         import gettext
86         gettext.bindtextdomain ('lilypond', localedir)
87         gettext.textdomain ('lilypond')
88         global _
89         _ = gettext.gettext
90 except:
91         def _ (s):
92                 return s
93 underscore = _
94
95 program_version = '1.6.6'
96 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
97         program_version = '1.5.54'
98
99 def identify (port):
100         port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, program_version))
101
102 # hmm
103 def warranty ():
104         identify (sys.stdout)
105         sys.stdout.write ('\n')
106         sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998--2002'))
107         sys.stdout.write ('\n')
108         sys.stdout.write ('  Han-Wen Nienhuys')
109         sys.stdout.write ('  Jan Nieuwenhuizen')
110         sys.stdout.write ('\n\n')
111         sys.stdout.write ('\n')
112         sys.stdout.write (_ ("Distributed under terms of the GNU General Public License.  It comes with NO WARRANTY."))
113         sys.stdout.write ('\n')
114
115 def progress (s):
116         sys.stderr.write (s)
117
118 def warning (s):
119         sys.stderr.write (__main__.program_name + ":" + _ ("warning: ") + s + '\n')
120
121 def error (s):
122         sys.stderr.write (__main__.program_name + ":" + _ ("error: ") + s + '\n')
123         
124 def exit (i):
125         if __main__.verbose_p:
126                 raise _ ('Exiting (%d)...') % i
127         else:
128                 sys.exit (1)
129                 
130 def getopt_args (opts):
131         '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
132         short = ''
133         long = []
134         for o in opts:
135                 if o[1]:
136                         short = short + o[1]
137                         if o[0]:
138                                 short = short + ':'
139                 if o[2]:
140                         l = o[2]
141                         if o[0]:
142                                 l = l + '='
143                         long.append (l)
144         return (short, long)
145
146 def option_help_str (o):
147         '''Transform one option description (4-tuple ) into neatly formatted string'''
148         sh = '  '       
149         if o[1]:
150                 sh = '-%s' % o[1]
151
152         sep = ' '
153         if o[1] and o[2]:
154                 sep = ','
155                 
156         long = ''
157         if o[2]:
158                 long= '--%s' % o[2]
159
160         arg = ''
161         if o[0]:
162                 if o[2]:
163                         arg = '='
164                 arg = arg + o[0]
165         return '  ' + sh + sep + long + arg
166
167
168 def options_help_str (opts):
169         '''Convert a list of options into a neatly formatted string'''
170         w = 0
171         strs =[]
172         helps = []
173
174         for o in opts:
175                 s = option_help_str (o)
176                 strs.append ((s, o[3]))
177                 if len (s) > w:
178                         w = len (s)
179
180         str = ''
181         for s in strs:
182                 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
183         return str
184
185 def help ():
186         ls = [(_ ("Usage: %s [OPTION]... FILE") % __main__.program_name),
187               ('\n\n'),
188               (__main__.help_summary),
189               ('\n\n'),
190               (_ ("Options:")),
191               ('\n'),
192               (options_help_str (__main__.option_definitions)),
193               ('\n\n'),
194               (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
195               ('\n')]
196         map (sys.stdout.write, ls)
197         
198 def setup_temp ():
199         
200         ''' Create a temporary directory, and return its name. '''
201         
202         if not __main__.keep_temp_dir_p:
203                 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
204         try:
205                 os.mkdir (__main__.temp_dir, 0777)
206         except OSError:
207                 pass
208
209         return __main__.temp_dir
210
211 def command_name (cmd):
212         return re.match ('^[ \t]*([^ \t]*)', cmd).group (1)
213
214 def error_log (name):
215         return os.path.join (__main__.temp_dir, '%s.errorlog' % name)
216
217 def read_pipe (cmd, mode = 'r'):
218         redirect = ''
219         if __main__.verbose_p:
220                 progress (_ ("Opening pipe `%s\'") % cmd)
221                 redirect = ' 2>%s' % error_log (command_name (cmd))
222         pipe = os.popen (cmd + redirect, mode)
223         output = pipe.read ()
224         status = pipe.close ()
225         # successful pipe close returns 'None'
226         if not status:
227                 status = 0
228         signal = 0x0f & status
229         exit_status = status >> 8
230
231         if status:
232                 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
233                 if not __main__.verbose_p:
234                         error (_ ("The error log is as follows:"))
235                         sys.stderr.write (open (error_log (command_name (cmd)).read ()))
236                 exit (status)
237         if __main__.verbose_p:
238                 progress ('\n')
239         return output
240
241 def system (cmd, ignore_error = 0):
242         
243         ''' Run CMD.  If IGNORE_ERROR is set, do not complain when CMD
244 returns non zero.
245
246 RETURN VALUE
247
248 Exit status of CMD '''
249
250         name = command_name (cmd)
251
252         redirect = ''
253         if __main__.verbose_p:
254                 progress (_ ("Invoking `%s\'") % cmd)
255                 if __main__.pseudo_filter_p:
256                         redirect = ' 1> /dev/null'
257         else:
258                 progress ( _("Running %s...") % name)
259                 redirect = ' 1> /dev/null 2>%s' % error_log (name)
260
261         status = os.system (cmd + redirect)
262         signal = 0x0f & status
263         exit_status = status >> 8
264         
265         if status:
266                 msg = _ ("`%s\' failed (%d)") % (name, status / exit_status)
267                 if ignore_error:
268                         if __main__.verbose_p:
269                                 warning (msg + ' ' + _ ("(ignored)"))
270                 else:
271                         error (msg)
272                         if not __main__.verbose_p:
273                                 error (_ ("The error log is as follows:"))
274                                 sys.stderr.write (open (error_log (name)).read ())
275                         exit (status)
276
277         progress ('\n')
278         return status
279
280 def cleanup_temp ():
281         if not __main__.keep_temp_dir_p:
282                 if __main__.verbose_p:
283                         progress (_ ("Cleaning %s...") % __main__.temp_dir)
284                 shutil.rmtree (__main__.temp_dir)
285                 if __main__.verbose_p:
286                         progress ('\n')
287
288
289 def strip_extension (f, ext):
290         (p, e) = os.path.splitext (f)
291         if e == ext:
292                 e = ''
293         return p + e
294
295
296 def cp_to_dir (pattern, dir):
297         "Copy files matching re PATTERN from cwd to DIR"
298         # Duh.  Python style portable: cp *.EXT OUTDIR
299         # system ('cp *.%s %s' % (ext, outdir), 1)
300         files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
301         map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
302
303
304 # Python < 1.5.2 compatibility
305 #
306 # On most platforms, this is equivalent to
307 #`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
308 if os.path.__dict__.has_key ('abspath'):
309         abspath = os.path.abspath
310 else:
311         def abspath (path):
312                 return os.path.normpath (os.path.join (os.getcwd (), path))
313
314 if os.__dict__.has_key ('makedirs'):
315         makedirs = os.makedirs
316 else:
317         def makedirs (dir, mode=0777):
318                 system ('mkdir -p %s' % dir)
319
320
321 def mkdir_p (dir, mode=0777):
322         if not os.path.isdir (dir):
323                 makedirs (dir, mode)