]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
Merge branch 'master' of git://git.sv.gnu.org/lilypond
[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 # ugh, Python 2.5 optparse requires Unicode strings in some argument
63 # functions, and refuse them in some other places
64 def display_encode (s):
65     return s.encode (sys.stderr.encoding or 'utf_8')
66
67 def stderr_write (s):
68     encoded_write (sys.stderr, s)
69
70 progress = stderr_write
71
72 # Modified version of the commands.mkarg(x), which always uses 
73 # double quotes (since Windows can't handle the single quotes:
74 def mkarg(x):
75     s = ' "'
76     for c in x:
77         if c in '\\$"`':
78             s = s + '\\'
79         s = s + c
80     s = s + '"'
81     return s
82
83 def command_name (cmd):
84     # Strip all stuf after command,
85     # deal with "((latex ) >& 1 ) .." too
86     cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
87     return os.path.basename (cmd)
88
89 def subprocess_system (cmd,
90                        ignore_error=False,
91                        progress_p=True,
92                        be_verbose=False,
93                        log_file=None):
94     import subprocess
95
96     show_progress= progress_p 
97     name = command_name (cmd)
98     error_log_file = ''
99
100     if be_verbose:
101         show_progress = 1
102         progress (_ ("Invoking `%s\'") % cmd)
103     else:
104         progress ( _("Running %s...") % name)
105
106
107     stdout_setting = None
108     if not show_progress:
109         stdout_setting = subprocess.PIPE
110
111     proc = subprocess.Popen (cmd,
112                              shell=True,
113                              universal_newlines=True,
114                              stdout=stdout_setting,
115                              stderr=stdout_setting)
116
117     log = ''
118
119     if show_progress:
120         retval = proc.wait()
121     else:
122         log = proc.communicate ()
123         retval = proc.returncode
124
125
126     if retval:
127         print >>sys.stderr, 'command failed:', cmd
128         if retval < 0:
129             print >>sys.stderr, "Child was terminated by signal", -retval
130         elif retval > 0:
131             print >>sys.stderr, "Child returned", retval
132
133         if ignore_error:
134             print >>sys.stderr, "Error ignored"
135         else:
136             if not show_progress:
137                 print log[0]
138                 print log[1]
139             sys.exit (1)
140
141     return abs (retval)
142
143 def ossystem_system (cmd,
144                      ignore_error=False,
145                      progress_p=True,
146                      be_verbose=False,
147                      log_file=None):
148
149
150     name = command_name (cmd)
151     if be_verbose:
152         show_progress = 1
153         progress (_ ("Invoking `%s\'") % cmd)
154     else:
155         progress ( _("Running %s...") % name)
156
157     retval = os.system (cmd)
158     if retval:
159         print >>sys.stderr, 'command failed:', cmd
160         if retval < 0:
161             print >>sys.stderr, "Child was terminated by signal", -retval
162         elif retval > 0:
163             print >>sys.stderr, "Child returned", retval
164
165         if ignore_error:
166             print >>sys.stderr, "Error ignored"
167         else:
168             sys.exit (1)
169
170     return abs (retval)
171
172
173 system = subprocess_system
174 if sys.platform == 'mingw32':
175     
176     ## subprocess x-compile doesn't work.
177     system = ossystem_system
178
179 def strip_extension (f, ext):
180     (p, e) = os.path.splitext (f)
181     if e == ext:
182         e = ''
183     return p + e
184
185
186 def search_exe_path (name):
187     p = os.environ['PATH']
188     exe_paths = string.split (p, ':')
189     for e in exe_paths:
190         full = os.path.join (e, name)
191         if os.path.exists (full):
192             return full
193     return None
194
195
196 def print_environment ():
197     for (k,v) in os.environ.items ():
198         sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
199
200 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
201     def format_heading(self, heading):
202         if heading:
203             return heading[0].upper() + heading[1:] + ':\n'
204         return ''
205     def format_option_strings(self, option):
206         sep = ' '
207         if option._short_opts and option._long_opts:
208             sep = ','
209
210         metavar = ''
211         if option.takes_value():
212             metavar = '=%s' % option.metavar or option.dest.upper()
213
214         return "%3s%s %s%s" % (" ".join (option._short_opts),
215                                sep,
216                                " ".join (option._long_opts),
217                                metavar)
218
219     def format_usage(self, usage):
220         return _("Usage: %s") % usage + '\n'
221
222     def format_description(self, description):
223         return description
224
225 def get_option_parser (*args, **kwargs): 
226     p = optparse.OptionParser (*args, **kwargs)
227     p.formatter = NonDentedHeadingFormatter () 
228     return p