]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
Merge commit 'ce4b499'
[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--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8
9 import __main__
10 import glob
11 import os
12 import re
13 import shutil
14 import string
15 import sys
16 import optparse
17
18 ################################################################
19 # Users of python modules should include this snippet
20 # and customize variables below.
21
22 # We'll suffer this path init stuff as long as we don't install our
23 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
24 # it as we do with teTeX on Red Hat Linux: set some environment var
25 # (PYTHONPATH) in profile)
26
27 # If set, LILYPOND_DATADIR must take prevalence
28 # if datadir is not set, we're doing a build and LILYPOND_DATADIR
29
30 datadir = '@local_lilypond_datadir@'
31 if not os.path.isdir (datadir):
32     datadir = '@lilypond_datadir@'
33 if os.environ.has_key ('LILYPOND_DATADIR') :
34     datadir = os.environ['LILYPOND_DATADIR']
35     while datadir[-1] == os.sep:
36         datadir= datadir[:-1]
37
38 sys.path.insert (0, os.path.join (datadir, 'python'))
39
40
41 # Python 2.5 only accepts strings with proper Python internal encoding
42 # (i.e. ASCII or Unicode) when writing to stdout/stderr, so we must
43 # use ugettext iso gettext, and encode the string when writing to
44 # stdout/stderr
45
46 localedir = '@localedir@'
47 try:
48     import gettext
49     t = gettext.translation ('lilypond', localedir)
50     _ = t.ugettext
51 except:
52     def _ (s):
53         return s
54 underscore = _
55
56 # Urg, Python 2.4 does not define stderr/stdout encoding
57 # Maybe guess encoding from LANG/LC_ALL/LC_CTYPE?
58
59 def encoded_write(f, s):
60     f.write (s.encode (f.encoding or 'utf_8'))
61
62 def stderr_write (s):
63     encoded_write (sys.stderr, s)
64
65 progress = stderr_write
66
67 # Modified version of the commands.mkarg(x), which always uses 
68 # double quotes (since Windows can't handle the single quotes:
69 def mkarg(x):
70     s = ' "'
71     for c in x:
72         if c in '\\$"`':
73             s = s + '\\'
74         s = s + c
75     s = s + '"'
76     return s
77
78 def command_name (cmd):
79     # Strip all stuf after command,
80     # deal with "((latex ) >& 1 ) .." too
81     cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
82     return os.path.basename (cmd)
83
84 def subprocess_system (cmd,
85                        ignore_error=False,
86                        progress_p=True,
87                        be_verbose=False,
88                        log_file=None):
89     import subprocess
90
91     show_progress= progress_p 
92     name = command_name (cmd)
93     error_log_file = ''
94
95     if be_verbose:
96         show_progress = 1
97         progress (_ ("Invoking `%s\'") % cmd)
98     else:
99         progress ( _("Running %s...") % name)
100
101
102     stdout_setting = None
103     if not show_progress:
104         stdout_setting = subprocess.PIPE
105
106     proc = subprocess.Popen (cmd,
107                              shell=True,
108                              universal_newlines=True,
109                              stdout=stdout_setting,
110                              stderr=stdout_setting)
111
112     log = ''
113
114     if show_progress:
115         retval = proc.wait()
116     else:
117         log = proc.communicate ()
118         retval = proc.returncode
119
120
121     if retval:
122         print >>sys.stderr, 'command failed:', cmd
123         if retval < 0:
124             print >>sys.stderr, "Child was terminated by signal", -retval
125         elif retval > 0:
126             print >>sys.stderr, "Child returned", retval
127
128         if ignore_error:
129             print >>sys.stderr, "Error ignored"
130         else:
131             if not show_progress:
132                 print log[0]
133                 print log[1]
134             sys.exit (1)
135
136     return abs (retval)
137
138 def ossystem_system (cmd,
139                      ignore_error=False,
140                      progress_p=True,
141                      be_verbose=False,
142                      log_file=None):
143
144
145     name = command_name (cmd)
146     if be_verbose:
147         show_progress = 1
148         progress (_ ("Invoking `%s\'") % cmd)
149     else:
150         progress ( _("Running %s...") % name)
151
152     retval = os.system (cmd)
153     if retval:
154         print >>sys.stderr, 'command failed:', cmd
155         if retval < 0:
156             print >>sys.stderr, "Child was terminated by signal", -retval
157         elif retval > 0:
158             print >>sys.stderr, "Child returned", retval
159
160         if ignore_error:
161             print >>sys.stderr, "Error ignored"
162         else:
163             sys.exit (1)
164
165     return abs (retval)
166
167
168 system = subprocess_system
169 if sys.platform == 'mingw32':
170     
171     ## subprocess x-compile doesn't work.
172     system = ossystem_system
173
174 def strip_extension (f, ext):
175     (p, e) = os.path.splitext (f)
176     if e == ext:
177         e = ''
178     return p + e
179
180
181 def search_exe_path (name):
182     p = os.environ['PATH']
183     exe_paths = string.split (p, ':')
184     for e in exe_paths:
185         full = os.path.join (e, name)
186         if os.path.exists (full):
187             return full
188     return None
189
190
191 def print_environment ():
192     for (k,v) in os.environ.items ():
193         sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
194
195 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
196     def format_heading(self, heading):
197         if heading:
198             return heading[0].upper() + heading[1:] + ':\n'
199         return ''
200     def format_option_strings(self, option):
201         sep = ' '
202         if option._short_opts and option._long_opts:
203             sep = ','
204
205         metavar = ''
206         if option.takes_value():
207             metavar = '=%s' % option.metavar or option.dest.upper()
208
209         return "%3s%s %s%s" % (" ".join (option._short_opts),
210                                sep,
211                                " ".join (option._long_opts),
212                                metavar)
213
214     def format_usage(self, usage):
215         return _("Usage: %s") % usage + '\n'
216
217     def format_description(self, description):
218         return description
219
220 def get_option_parser (*args, **kwargs): 
221     p = optparse.OptionParser (*args, **kwargs)
222     p.formatter = NonDentedHeadingFormatter () 
223     return p