1 # This file is part of LilyPond, the GNU music typesetter.
3 # Copyright (C) 1998--2012 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)
43 ungettext = t.ungettext
47 def ungettext (s, p, n):
53 # Urg, Python 2.4 does not define stderr/stdout encoding
54 # Maybe guess encoding from LANG/LC_ALL/LC_CTYPE?
57 sys.setdefaultencoding ('utf-8')
59 sys.stdout = codecs.getwriter ('utf8') (sys.stdout)
60 sys.stderr = codecs.getwriter ('utf8') (sys.stderr)
62 def encoded_write(f, s):
63 f.write (s.encode (f.encoding or 'utf-8', 'replace'))
65 # ugh, Python 2.5 optparse requires Unicode strings in some argument
66 # functions, and refuse them in some other places
67 def display_encode (s):
68 return s.encode (sys.stderr.encoding or 'utf-8', 'replace')
71 program_version = '@TOPLEVEL_VERSION@'
72 program_name = os.path.basename (sys.argv[0])
75 # Check if program_version contains @ characters. This will be the case if
76 # the .py file is called directly while building the lilypond documentation.
77 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
78 # makefiles and use its value.
79 at_re = re.compile (r'@')
80 if at_re.match (program_version):
81 if os.environ.has_key('LILYPOND_VERSION'):
82 program_version = os.environ['LILYPOND_VERSION']
84 program_version = "unknown"
87 # Logging framework: We have the following output functions:
93 loglevels = {"NONE":0, "ERROR":1, "WARN":2, "BASIC":3, "PROGRESS":4, "INFO":5, "DEBUG":6}
95 loglevel = loglevels["PROGRESS"]
99 newlevel = loglevels.get (l, -1)
101 debug_output (_ ("Setting loglevel to %s") % l)
104 error (_ ("Unknown or invalid loglevel '%s'") % l)
107 def handle_loglevel_option (option, opt_str, value, parser, *args):
109 set_loglevel (value);
111 set_loglevel (args[0]);
115 return loglevel >= loglevels[l];
118 return is_loglevel ("DEBUG")
120 def stderr_write (s):
121 encoded_write (sys.stderr, s)
123 def print_logmessage (level, s, fullmessage = True, newline = True):
124 if (is_loglevel (level)):
126 stderr_write (program_name + ": " + s + '\n')
128 stderr_write (s + '\n')
133 print_logmessage ("ERROR", _ ("error: %s") % s);
136 print_logmessage ("WARN", _ ("warning: %s") % s);
138 def basic_progress (s):
139 print_logmessage ("BASIC", s);
141 def progress (s, fullmessage = False, newline = True):
142 print_logmessage ("PROGRESS", s, fullmessage, newline);
144 def debug_output (s, fullmessage = False, newline = True):
145 print_logmessage ("DEBUG", s, fullmessage, newline);
149 def require_python_version ():
150 if sys.hexversion < 0x02040000:
151 error ("Python 2.4 or newer is required to run this program.\n\
152 Please upgrade Python from http://python.org/download/, and if you use MacOS X,\n\
153 please read 'Setup for MacOS X' in Application Usage.")
154 os.system ("open http://python.org/download/")
157 # A modified version of the commands.mkarg(x) that always uses
158 # double quotes (since Windows can't handle the single quotes)
159 # and escapes the characters \, $, ", and ` for unix shells.
171 def command_name (cmd):
172 # Strip all stuf after command,
173 # deal with "((latex ) >& 1 ) .." too
174 cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
175 return os.path.basename (cmd)
177 def subprocess_system (cmd,
181 redirect_output=False,
185 show_progress= progress_p
186 name = command_name (cmd)
190 progress (_ ("Processing %s.ly") % log_file)
194 progress (_ ("Invoking `%s\'") % cmd)
196 progress ( _("Running %s...") % name)
198 stdout_setting = None
199 stderr_setting = None
200 if not show_progress:
201 stdout_setting = subprocess.PIPE
204 stderr_filename = log_file + '.log'
205 stderr_setting = open(stderr_filename, 'w')
207 proc = subprocess.Popen (cmd,
209 universal_newlines=True,
210 stdout=stdout_setting,
211 stderr=stderr_setting)
216 while proc.poll()==None:
218 retval = proc.returncode
219 stderr_setting.close()
224 log = proc.communicate ()
225 retval = proc.returncode
228 print >>sys.stderr, 'command failed:', cmd
230 print >>sys.stderr, "Child was terminated by signal", -retval
232 print >>sys.stderr, "Child returned", retval
235 print >>sys.stderr, "Error ignored by lilylib"
237 if not show_progress:
244 def ossystem_system (cmd,
248 redirect_output=False,
252 name = command_name (cmd)
255 progress (_ ("Invoking `%s\'") % cmd)
257 progress ( _("Running %s...") % name)
259 retval = os.system (cmd)
261 print >>sys.stderr, 'command failed:', cmd
263 print >>sys.stderr, "Child was terminated by signal", -retval
265 print >>sys.stderr, "Child returned", retval
268 print >>sys.stderr, "Error ignored"
275 system = subprocess_system
276 if sys.platform == 'mingw32':
278 ## subprocess x-compile doesn't work.
279 system = ossystem_system
281 def strip_extension (f, ext):
282 (p, e) = os.path.splitext (f)
288 def search_exe_path (name):
289 p = os.environ['PATH']
290 exe_paths = p.split (':')
292 full = os.path.join (e, name)
293 if os.path.exists (full):
298 def print_environment ():
299 for (k,v) in os.environ.items ():
300 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
302 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
303 def format_heading(self, heading):
305 return heading[0].upper() + heading[1:] + ':\n'
307 def format_option_strings(self, option):
309 if option._short_opts and option._long_opts:
313 if option.takes_value():
314 metavar = '=%s' % option.metavar or option.dest.upper()
316 return "%3s%s %s%s" % (" ".join (option._short_opts),
318 " ".join (option._long_opts),
321 # Only use one level of indentation (even for groups and nested groups),
322 # since we don't indent the headeings, either
324 self.current_indent = self.indent_increment
329 self.current_indent = ''
332 def format_usage(self, usage):
333 return _("Usage: %s") % usage + '\n'
335 def format_description(self, description):
338 class NonEmptyOptionParser (optparse.OptionParser):
339 "A subclass of OptionParser that gobbles empty string arguments."
341 def parse_args (self, args=None, values=None):
342 options, args = optparse.OptionParser.parse_args (self, args, values)
343 return options, filter (None, args)
345 def get_option_parser (*args, **kwargs):
346 p = NonEmptyOptionParser (*args, **kwargs)
347 p.formatter = NonDentedHeadingFormatter ()
348 p.formatter.set_parser (p)