]> 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 # This file is part of LilyPond, the GNU music typesetter.
2 #
3 # Copyright (C) 1998--2010 Han-Wen Nienhuys <hanwen@xs4all.nl>
4 #                Jan Nieuwenhuizen <janneke@gnu.org>
5 #
6 # LilyPond is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # LilyPond is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18
19 import __main__
20 import glob
21 import os
22 import re
23 import shutil
24 import sys
25 import optparse
26 import locale
27
28 ################################################################
29 # Users of python modules should include this snippet
30 # and customize variables below.
31
32
33 # Python 2.5 only accepts strings with proper Python internal encoding
34 # (i.e. ASCII or Unicode) when writing to stdout/stderr, so we must
35 # use ugettext iso gettext, and encode the string when writing to
36 # stdout/stderr
37
38 localedir = '@localedir@'
39 try:
40     import gettext
41     t = gettext.translation ('lilypond', localedir)
42     _ = t.ugettext
43 except:
44     def _ (s):
45         return s
46 underscore = _
47
48 # Urg, Python 2.4 does not define stderr/stdout encoding
49 # Maybe guess encoding from LANG/LC_ALL/LC_CTYPE?
50
51 def encoded_write(f, s):
52     f.write (s
53       .decode (sys.stderr.encoding or locale.getdefaultlocale()[1])
54       .encode (f.encoding or 'utf_8'))
55
56 # ugh, Python 2.5 optparse requires Unicode strings in some argument
57 # functions, and refuse them in some other places
58 def display_encode (s):
59     return s.encode (sys.stderr.encoding or 'utf_8')
60
61 def stderr_write (s):
62     encoded_write (sys.stderr, s)
63
64 progress = stderr_write
65
66 def require_python_version ():
67     if sys.hexversion < 0x02040000:
68         stderr_write ("Python 2.4 or newer is required to run this program.\n\
69 Please upgrade Python from http://python.org/download/, and if you use MacOS X,\n\
70 please read 'Setup for MacOS X' in Application Usage.")
71         os.system ("open http://python.org/download/")
72         sys.exit (2)
73
74 # Modified version of the commands.mkarg(x), which always uses
75 # double quotes (since Windows can't handle the single quotes:
76 def mkarg(x):
77     s = ' "'
78     for c in x:
79         if c in '\\$"`':
80             s = s + '\\'
81         s = s + c
82     s = s + '"'
83     return s
84
85 def command_name (cmd):
86     # Strip all stuf after command,
87     # deal with "((latex ) >& 1 ) .." too
88     cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
89     return os.path.basename (cmd)
90
91 def subprocess_system (cmd,
92                        ignore_error=False,
93                        progress_p=True,
94                        be_verbose=False,
95                        log_file=None):
96     import subprocess
97
98     show_progress= progress_p
99     name = command_name (cmd)
100     error_log_file = ''
101
102     if be_verbose:
103         show_progress = 1
104         progress (_ ("Invoking `%s\'") % cmd)
105     else:
106         progress ( _("Running %s...") % name)
107
108
109     stdout_setting = None
110     if not show_progress:
111         stdout_setting = subprocess.PIPE
112
113     proc = subprocess.Popen (cmd,
114                              shell=True,
115                              universal_newlines=True,
116                              stdout=stdout_setting,
117                              stderr=stdout_setting)
118
119     log = ''
120
121     if show_progress:
122         retval = proc.wait()
123     else:
124         log = proc.communicate ()
125         retval = proc.returncode
126
127
128     if retval:
129         print >>sys.stderr, 'command failed:', cmd
130         if retval < 0:
131             print >>sys.stderr, "Child was terminated by signal", -retval
132         elif retval > 0:
133             print >>sys.stderr, "Child returned", retval
134
135         if ignore_error:
136             print >>sys.stderr, "Error ignored"
137         else:
138             if not show_progress:
139                 print log[0]
140                 print log[1]
141             sys.exit (1)
142
143     return abs (retval)
144
145 def ossystem_system (cmd,
146                      ignore_error=False,
147                      progress_p=True,
148                      be_verbose=False,
149                      log_file=None):
150
151
152     name = command_name (cmd)
153     if be_verbose:
154         show_progress = 1
155         progress (_ ("Invoking `%s\'") % cmd)
156     else:
157         progress ( _("Running %s...") % name)
158
159     retval = os.system (cmd)
160     if retval:
161         print >>sys.stderr, 'command failed:', cmd
162         if retval < 0:
163             print >>sys.stderr, "Child was terminated by signal", -retval
164         elif retval > 0:
165             print >>sys.stderr, "Child returned", retval
166
167         if ignore_error:
168             print >>sys.stderr, "Error ignored"
169         else:
170             sys.exit (1)
171
172     return abs (retval)
173
174
175 system = subprocess_system
176 if sys.platform == 'mingw32':
177
178     ## subprocess x-compile doesn't work.
179     system = ossystem_system
180
181 def strip_extension (f, ext):
182     (p, e) = os.path.splitext (f)
183     if e == ext:
184         e = ''
185     return p + e
186
187
188 def search_exe_path (name):
189     p = os.environ['PATH']
190     exe_paths = p.split (':')
191     for e in exe_paths:
192         full = os.path.join (e, name)
193         if os.path.exists (full):
194             return full
195     return None
196
197
198 def print_environment ():
199     for (k,v) in os.environ.items ():
200         sys.stderr.write ("%s=\"%s\"\n" % (k, v))
201
202 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
203     def format_heading(self, heading):
204         if heading:
205             return heading[0].upper() + heading[1:] + ':\n'
206         return ''
207     def format_option_strings(self, option):
208         sep = ' '
209         if option._short_opts and option._long_opts:
210             sep = ','
211
212         metavar = ''
213         if option.takes_value():
214             metavar = '=%s' % option.metavar or option.dest.upper()
215
216         return "%3s%s %s%s" % (" ".join (option._short_opts),
217                                sep,
218                                " ".join (option._long_opts),
219                                metavar)
220
221     def format_usage(self, usage):
222         return _("Usage: %s") % usage + '\n'
223
224     def format_description(self, description):
225         return description
226
227 def get_option_parser (*args, **kwargs):
228     p = optparse.OptionParser (*args, **kwargs)
229     p.formatter = NonDentedHeadingFormatter ()
230     return p