]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
Replace Tab with 8 Spaces for .py files
[lilypond.git] / python / lilylib.py
1 # This file is part of LilyPond, the GNU music typesetter.
2 #
3 # Copyright (C) 1998--2011 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 time
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 reload (sys)
52 sys.setdefaultencoding ('utf-8')
53 import codecs
54 sys.stdout = codecs.getwriter ('utf8') (sys.stdout)
55 sys.stderr = codecs.getwriter ('utf8') (sys.stderr)
56
57 def encoded_write(f, s):
58     f.write (s.encode (f.encoding or 'utf-8', 'replace'))
59
60 # ugh, Python 2.5 optparse requires Unicode strings in some argument
61 # functions, and refuse them in some other places
62 def display_encode (s):
63     return s.encode (sys.stderr.encoding or 'utf-8', 'replace')
64
65 # Lilylib globals.
66 program_version = '@TOPLEVEL_VERSION@'
67 program_name = os.path.basename (sys.argv[0])
68
69
70 # Check if program_version contains @ characters. This will be the case if
71 # the .py file is called directly while building the lilypond documentation.
72 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
73 # makefiles and use its value.
74 at_re = re.compile (r'@')
75 if at_re.match (program_version):
76     if os.environ.has_key('LILYPOND_VERSION'):
77         program_version = os.environ['LILYPOND_VERSION']
78     else:
79         program_version = "unknown"
80
81 def stderr_write (s):
82     encoded_write (sys.stderr, s)
83
84 def warning (s):
85     stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
86
87 def error (s):
88     stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
89
90 progress = stderr_write
91
92
93 def require_python_version ():
94     if sys.hexversion < 0x02040000:
95         stderr_write ("Python 2.4 or newer is required to run this program.\n\
96 Please upgrade Python from http://python.org/download/, and if you use MacOS X,\n\
97 please read 'Setup for MacOS X' in Application Usage.")
98         os.system ("open http://python.org/download/")
99         sys.exit (2)
100
101 # Modified version of the commands.mkarg(x), which always uses
102 # double quotes (since Windows can't handle the single quotes:
103 def mkarg(x):
104     s = ' "'
105     for c in x:
106         if c in '\\$"`':
107             s = s + '\\'
108         s = s + c
109     s = s + '"'
110     return s
111
112 def command_name (cmd):
113     # Strip all stuf after command,
114     # deal with "((latex ) >& 1 ) .." too
115     cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
116     return os.path.basename (cmd)
117
118 def subprocess_system (cmd,
119                        ignore_error=False,
120                        progress_p=True,
121                        be_verbose=False,
122                        redirect_output=False,
123                        log_file=None):
124     import subprocess
125
126     show_progress= progress_p
127     name = command_name (cmd)
128     error_log_file = ''
129
130     if redirect_output:
131         progress (_ ("Processing %s.ly") % log_file)
132     else:
133         if be_verbose:
134             show_progress = 1
135             progress (_ ("Invoking `%s\'") % cmd)
136         else:
137             progress ( _("Running %s...") % name)
138
139     stdout_setting = None
140     stderr_setting = None
141     if not show_progress:
142         stdout_setting = subprocess.PIPE
143
144     if redirect_output:
145         stdout_filename = ''.join([log_file, '.log'])
146         stderr_filename = ''.join([log_file, '.err.log'])
147         stdout_setting = open(stdout_filename, 'w')
148         stderr_setting = open(stderr_filename, 'w')
149
150     proc = subprocess.Popen (cmd,
151                              shell=True,
152                              universal_newlines=True,
153                              stdout=stdout_setting,
154                              stderr=stdout_setting)
155
156     log = ''
157
158     if redirect_output:
159         while proc.poll()==None:
160             time.sleep(1)
161         retval = proc.returncode
162         stdout_setting.close()
163         stderr_setting.close()
164     else:
165         if show_progress:
166             retval = proc.wait()
167         else:
168             log = proc.communicate ()
169             retval = proc.returncode
170
171
172     if retval:
173         print >>sys.stderr, 'command failed:', cmd
174         if retval < 0:
175             print >>sys.stderr, "Child was terminated by signal", -retval
176         elif retval > 0:
177             print >>sys.stderr, "Child returned", retval
178
179         if ignore_error:
180             print >>sys.stderr, "Error ignored"
181         else:
182             if not show_progress:
183                 print log[0]
184                 print log[1]
185             sys.exit (1)
186
187     return abs (retval)
188
189 def ossystem_system (cmd,
190                      ignore_error=False,
191                      progress_p=True,
192                      be_verbose=False,
193                      log_file=None):
194
195
196     name = command_name (cmd)
197     if be_verbose:
198         show_progress = 1
199         progress (_ ("Invoking `%s\'") % cmd)
200     else:
201         progress ( _("Running %s...") % name)
202
203     retval = os.system (cmd)
204     if retval:
205         print >>sys.stderr, 'command failed:', cmd
206         if retval < 0:
207             print >>sys.stderr, "Child was terminated by signal", -retval
208         elif retval > 0:
209             print >>sys.stderr, "Child returned", retval
210
211         if ignore_error:
212             print >>sys.stderr, "Error ignored"
213         else:
214             sys.exit (1)
215
216     return abs (retval)
217
218
219 system = subprocess_system
220 if sys.platform == 'mingw32':
221
222     ## subprocess x-compile doesn't work.
223     system = ossystem_system
224
225 def strip_extension (f, ext):
226     (p, e) = os.path.splitext (f)
227     if e == ext:
228         e = ''
229     return p + e
230
231
232 def search_exe_path (name):
233     p = os.environ['PATH']
234     exe_paths = p.split (':')
235     for e in exe_paths:
236         full = os.path.join (e, name)
237         if os.path.exists (full):
238             return full
239     return None
240
241
242 def print_environment ():
243     for (k,v) in os.environ.items ():
244         sys.stderr.write ("%s=\"%s\"\n" % (k, v))
245
246 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
247     def format_heading(self, heading):
248         if heading:
249             return heading[0].upper() + heading[1:] + ':\n'
250         return ''
251     def format_option_strings(self, option):
252         sep = ' '
253         if option._short_opts and option._long_opts:
254             sep = ','
255
256         metavar = ''
257         if option.takes_value():
258             metavar = '=%s' % option.metavar or option.dest.upper()
259
260         return "%3s%s %s%s" % (" ".join (option._short_opts),
261                                sep,
262                                " ".join (option._long_opts),
263                                metavar)
264
265     # Only use one level of indentation (even for groups and nested groups),
266     # since we don't indent the headeings, either
267     def indent(self):
268         self.current_indent = self.indent_increment
269         self.level += 1
270     def dedent(self):
271         self.level -= 1
272         if self.level <= 0:
273             self.current_indent = ''
274             self.level = 0;
275
276     def format_usage(self, usage):
277         return _("Usage: %s") % usage + '\n'
278
279     def format_description(self, description):
280         return description
281
282 def get_option_parser (*args, **kwargs):
283     p = optparse.OptionParser (*args, **kwargs)
284     p.formatter = NonDentedHeadingFormatter ()
285     p.formatter.set_parser (p)
286     return p