1 # This file is part of LilyPond, the GNU music typesetter.
3 # Copyright (C) 1998--2011 Han-Wen Nienhuys <hanwen@xs4all.nl>
4 # Jan Nieuwenhuizen <janneke@gnu.org>
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.
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.
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/>.
28 ################################################################
29 # Users of python modules should include this snippet
30 # and customize variables below.
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
38 localedir = '@localedir@'
41 t = gettext.translation ('lilypond', localedir)
48 # Urg, Python 2.4 does not define stderr/stdout encoding
49 # Maybe guess encoding from LANG/LC_ALL/LC_CTYPE?
52 sys.setdefaultencoding ('utf-8')
54 sys.stdout = codecs.getwriter ('utf8') (sys.stdout)
55 sys.stderr = codecs.getwriter ('utf8') (sys.stderr)
57 def encoded_write(f, s):
58 f.write (s.encode (f.encoding or 'utf-8', 'replace'))
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')
66 program_version = '@TOPLEVEL_VERSION@'
67 program_name = os.path.basename (sys.argv[0])
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']
79 program_version = "unknown"
82 # Logging framework: We have the following output functions:
88 loglevels = {"NONE":0, "ERROR":1, "WARN":2, "BASIC":3, "PROGRESS":4, "INFO":5, "DEBUG":6}
90 loglevel = loglevels["PROGRESS"]
94 newlevel = loglevels.get (l, -1)
96 debug_output (_ ("Setting loglevel to %s") % l)
99 error (_ ("Unknown or invalid loglevel '%s'") % l)
102 def handle_loglevel_option (option, opt_str, value, parser, *args):
104 set_loglevel (value);
106 set_loglevel (args[0]);
110 return loglevel >= loglevels[l];
113 return is_loglevel ("DEBUG")
115 def stderr_write (s):
116 encoded_write (sys.stderr, s)
118 def print_logmessage (level, s, fullmessage = True):
119 if (is_loglevel (level)):
121 stderr_write (program_name + ": " + s + '\n')
126 print_logmessage ("ERROR", _ ("error: %s") % s);
129 print_logmessage ("WARN", _ ("warning: %s") % s);
131 def basic_progress (s):
132 print_logmessage ("BASIC", s);
134 def progress (s, fullmessage = False):
135 print_logmessage ("PROGRESS", s, fullmessage);
137 def debug_output (s, fullmessage = False):
138 print_logmessage ("DEBUG", s, fullmessage);
142 def require_python_version ():
143 if sys.hexversion < 0x02040000:
144 error ("Python 2.4 or newer is required to run this program.\n\
145 Please upgrade Python from http://python.org/download/, and if you use MacOS X,\n\
146 please read 'Setup for MacOS X' in Application Usage.")
147 os.system ("open http://python.org/download/")
150 # Modified version of the commands.mkarg(x), which always uses
151 # double quotes (since Windows can't handle the single quotes:
161 def command_name (cmd):
162 # Strip all stuf after command,
163 # deal with "((latex ) >& 1 ) .." too
164 cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
165 return os.path.basename (cmd)
167 def subprocess_system (cmd,
171 redirect_output=False,
175 show_progress= progress_p
176 name = command_name (cmd)
180 progress (_ ("Processing %s.ly") % log_file)
184 progress (_ ("Invoking `%s\'") % cmd)
186 progress ( _("Running %s...") % name)
188 stdout_setting = None
189 stderr_setting = None
190 if not show_progress:
191 stdout_setting = subprocess.PIPE
194 stdout_filename = ' '.join([log_file, '.log'])
195 stderr_filename = ' '.join([log_file, '.err.log'])
196 stdout_setting = open(stdout_filename, 'w')
197 stderr_setting = open(stderr_filename, 'w')
199 proc = subprocess.Popen (cmd,
201 universal_newlines=True,
202 stdout=stdout_setting,
203 stderr=stderr_setting)
208 while proc.poll()==None:
210 retval = proc.returncode
211 stdout_setting.close()
212 stderr_setting.close()
217 log = proc.communicate ()
218 retval = proc.returncode
221 print >>sys.stderr, 'command failed:', cmd
223 print >>sys.stderr, "Child was terminated by signal", -retval
225 print >>sys.stderr, "Child returned", retval
228 print >>sys.stderr, "Error ignored"
230 if not show_progress:
237 def ossystem_system (cmd,
241 redirect_output=False,
245 name = command_name (cmd)
248 progress (_ ("Invoking `%s\'") % cmd)
250 progress ( _("Running %s...") % name)
252 retval = os.system (cmd)
254 print >>sys.stderr, 'command failed:', cmd
256 print >>sys.stderr, "Child was terminated by signal", -retval
258 print >>sys.stderr, "Child returned", retval
261 print >>sys.stderr, "Error ignored"
268 system = subprocess_system
269 if sys.platform == 'mingw32':
271 ## subprocess x-compile doesn't work.
272 system = ossystem_system
274 def strip_extension (f, ext):
275 (p, e) = os.path.splitext (f)
281 def search_exe_path (name):
282 p = os.environ['PATH']
283 exe_paths = p.split (':')
285 full = os.path.join (e, name)
286 if os.path.exists (full):
291 def print_environment ():
292 for (k,v) in os.environ.items ():
293 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
295 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
296 def format_heading(self, heading):
298 return heading[0].upper() + heading[1:] + ':\n'
300 def format_option_strings(self, option):
302 if option._short_opts and option._long_opts:
306 if option.takes_value():
307 metavar = '=%s' % option.metavar or option.dest.upper()
309 return "%3s%s %s%s" % (" ".join (option._short_opts),
311 " ".join (option._long_opts),
314 # Only use one level of indentation (even for groups and nested groups),
315 # since we don't indent the headeings, either
317 self.current_indent = self.indent_increment
322 self.current_indent = ''
325 def format_usage(self, usage):
326 return _("Usage: %s") % usage + '\n'
328 def format_description(self, description):
331 def get_option_parser (*args, **kwargs):
332 p = optparse.OptionParser (*args, **kwargs)
333 p.formatter = NonDentedHeadingFormatter ()
334 p.formatter.set_parser (p)