]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
Doc-fr: update for 2.16.1 (second part)
[lilypond.git] / python / lilylib.py
1 # This file is part of LilyPond, the GNU music typesetter.
2 #
3 # Copyright (C) 1998--2012 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
82 # Logging framework: We have the following output functions:
83 #    error
84 #    warning
85 #    progress
86 #    debug
87
88 loglevels = {"NONE":0, "ERROR":1, "WARN":2, "BASIC":3, "PROGRESS":4, "INFO":5, "DEBUG":6}
89
90 loglevel = loglevels["PROGRESS"]
91
92 def set_loglevel (l):
93     global loglevel
94     newlevel = loglevels.get (l, -1)
95     if newlevel > 0:
96         debug_output (_ ("Setting loglevel to %s") % l)
97         loglevel = newlevel
98     else:
99         error (_ ("Unknown or invalid loglevel '%s'") % l)
100
101
102 def handle_loglevel_option (option, opt_str, value, parser, *args):
103     if value:
104         set_loglevel (value);
105     elif args:
106         set_loglevel (args[0]);
107
108 def is_loglevel (l):
109     global loglevel
110     return loglevel >= loglevels[l];
111
112 def is_verbose ():
113     return is_loglevel ("DEBUG")
114
115 def stderr_write (s):
116     encoded_write (sys.stderr, s)
117
118 def print_logmessage (level, s, fullmessage = True, newline = True):
119     if (is_loglevel (level)):
120         if fullmessage:
121             stderr_write (program_name + ": " + s + '\n')
122         elif newline:
123             stderr_write (s + '\n')
124         else:
125             stderr_write (s)
126
127 def error (s):
128     print_logmessage ("ERROR", _ ("error: %s") % s);
129
130 def warning (s):
131     print_logmessage ("WARN", _ ("warning: %s") % s);
132
133 def basic_progress (s):
134     print_logmessage ("BASIC", s);
135
136 def progress (s, fullmessage = False, newline = True):
137     print_logmessage ("PROGRESS", s, fullmessage, newline);
138
139 def debug_output (s, fullmessage = False, newline = True):
140     print_logmessage ("DEBUG", s, fullmessage, newline);
141
142
143
144 def require_python_version ():
145     if sys.hexversion < 0x02040000:
146         error ("Python 2.4 or newer is required to run this program.\n\
147 Please upgrade Python from http://python.org/download/, and if you use MacOS X,\n\
148 please read 'Setup for MacOS X' in Application Usage.")
149         os.system ("open http://python.org/download/")
150         sys.exit (2)
151
152 # A modified version of the commands.mkarg(x) that always uses
153 # double quotes (since Windows can't handle the single quotes)
154 # and escapes the characters \, $, ", and ` for unix shells.
155 def mkarg(x):
156     if os.name == 'nt':
157         return ' "%s"' % x
158     s = ' "'
159     for c in x:
160         if c in '\\$"`':
161             s = s + '\\'
162         s = s + c
163     s = s + '"'
164     return s
165
166 def command_name (cmd):
167     # Strip all stuf after command,
168     # deal with "((latex ) >& 1 ) .." too
169     cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
170     return os.path.basename (cmd)
171
172 def subprocess_system (cmd,
173                        ignore_error=False,
174                        progress_p=True,
175                        be_verbose=False,
176                        redirect_output=False,
177                        log_file=None):
178     import subprocess
179
180     show_progress= progress_p
181     name = command_name (cmd)
182     error_log_file = ''
183
184     if redirect_output:
185         progress (_ ("Processing %s.ly") % log_file)
186     else:
187         if be_verbose:
188             show_progress = 1
189             progress (_ ("Invoking `%s\'") % cmd)
190         else:
191             progress ( _("Running %s...") % name)
192
193     stdout_setting = None
194     stderr_setting = None
195     if not show_progress:
196         stdout_setting = subprocess.PIPE
197
198     if redirect_output:
199         stderr_filename = log_file + '.log'
200         stderr_setting = open(stderr_filename, 'w')
201
202     proc = subprocess.Popen (cmd,
203                              shell=True,
204                              universal_newlines=True,
205                              stdout=stdout_setting,
206                              stderr=stderr_setting)
207
208     log = ''
209
210     if redirect_output:
211         while proc.poll()==None:
212             time.sleep(0.01)
213         retval = proc.returncode
214         stderr_setting.close()
215     else:
216         if show_progress:
217             retval = proc.wait()
218         else:
219             log = proc.communicate ()
220             retval = proc.returncode
221
222     if retval:
223         print >>sys.stderr, 'command failed:', cmd
224         if retval < 0:
225             print >>sys.stderr, "Child was terminated by signal", -retval
226         elif retval > 0:
227             print >>sys.stderr, "Child returned", retval
228
229         if ignore_error:
230             print >>sys.stderr, "Error ignored by lilylib"
231         else:
232             if not show_progress:
233                 print log[0]
234                 print log[1]
235             sys.exit (1)
236
237     return abs (retval)
238
239 def ossystem_system (cmd,
240                      ignore_error=False,
241                      progress_p=True,
242                      be_verbose=False,
243                      redirect_output=False,
244                      log_file=None):
245
246
247     name = command_name (cmd)
248     if be_verbose:
249         show_progress = 1
250         progress (_ ("Invoking `%s\'") % cmd)
251     else:
252         progress ( _("Running %s...") % name)
253
254     retval = os.system (cmd)
255     if retval:
256         print >>sys.stderr, 'command failed:', cmd
257         if retval < 0:
258             print >>sys.stderr, "Child was terminated by signal", -retval
259         elif retval > 0:
260             print >>sys.stderr, "Child returned", retval
261
262         if ignore_error:
263             print >>sys.stderr, "Error ignored"
264         else:
265             sys.exit (1)
266
267     return abs (retval)
268
269
270 system = subprocess_system
271 if sys.platform == 'mingw32':
272
273     ## subprocess x-compile doesn't work.
274     system = ossystem_system
275
276 def strip_extension (f, ext):
277     (p, e) = os.path.splitext (f)
278     if e == ext:
279         e = ''
280     return p + e
281
282
283 def search_exe_path (name):
284     p = os.environ['PATH']
285     exe_paths = p.split (':')
286     for e in exe_paths:
287         full = os.path.join (e, name)
288         if os.path.exists (full):
289             return full
290     return None
291
292
293 def print_environment ():
294     for (k,v) in os.environ.items ():
295         sys.stderr.write ("%s=\"%s\"\n" % (k, v))
296
297 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
298     def format_heading(self, heading):
299         if heading:
300             return heading[0].upper() + heading[1:] + ':\n'
301         return ''
302     def format_option_strings(self, option):
303         sep = ' '
304         if option._short_opts and option._long_opts:
305             sep = ','
306
307         metavar = ''
308         if option.takes_value():
309             metavar = '=%s' % option.metavar or option.dest.upper()
310
311         return "%3s%s %s%s" % (" ".join (option._short_opts),
312                                sep,
313                                " ".join (option._long_opts),
314                                metavar)
315
316     # Only use one level of indentation (even for groups and nested groups),
317     # since we don't indent the headeings, either
318     def indent(self):
319         self.current_indent = self.indent_increment
320         self.level += 1
321     def dedent(self):
322         self.level -= 1
323         if self.level <= 0:
324             self.current_indent = ''
325             self.level = 0;
326
327     def format_usage(self, usage):
328         return _("Usage: %s") % usage + '\n'
329
330     def format_description(self, description):
331         return description
332
333 def get_option_parser (*args, **kwargs):
334     p = optparse.OptionParser (*args, **kwargs)
335     p.formatter = NonDentedHeadingFormatter ()
336     p.formatter.set_parser (p)
337     return p