]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
Web-ja: update introduction
[lilypond.git] / python / lilylib.py
1 # This file is part of LilyPond, the GNU music typesetter.
2 #
3 # Copyright (C) 1998--2015 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     ungettext = t.ungettext
44 except:
45     def _ (s):
46         return s
47     def ungettext (s, p, n):
48         if n == 1:
49             return s
50         return p
51 underscore = _
52
53 # Urg, Python 2.4 does not define stderr/stdout encoding
54 # Maybe guess encoding from LANG/LC_ALL/LC_CTYPE?
55
56 reload (sys)
57 sys.setdefaultencoding ('utf-8')
58 import codecs
59 sys.stdout = codecs.getwriter ('utf8') (sys.stdout)
60 sys.stderr = codecs.getwriter ('utf8') (sys.stderr)
61
62 def encoded_write(f, s):
63     f.write (s.encode (f.encoding or 'utf-8', 'replace'))
64
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')
69
70 # Lilylib globals.
71 program_version = '@TOPLEVEL_VERSION@'
72 program_name = os.path.basename (sys.argv[0])
73
74
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']
83     else:
84         program_version = "unknown"
85
86
87 # Logging framework: We have the following output functions:
88 #    error
89 #    warning
90 #    progress
91 #    debug
92
93 loglevels = {"NONE":0, "ERROR":1, "WARN":2, "BASIC":3, "PROGRESS":4, "INFO":5, "DEBUG":6}
94
95 loglevel = loglevels["PROGRESS"]
96
97 def set_loglevel (l):
98     global loglevel
99     newlevel = loglevels.get (l, -1)
100     if newlevel > 0:
101         debug_output (_ ("Setting loglevel to %s") % l)
102         loglevel = newlevel
103     else:
104         error (_ ("Unknown or invalid loglevel '%s'") % l)
105
106
107 def handle_loglevel_option (option, opt_str, value, parser, *args):
108     if value:
109         set_loglevel (value);
110     elif args:
111         set_loglevel (args[0]);
112
113 def is_loglevel (l):
114     global loglevel
115     return loglevel >= loglevels[l];
116
117 def is_verbose ():
118     return is_loglevel ("DEBUG")
119
120 def stderr_write (s):
121     encoded_write (sys.stderr, s)
122
123 def print_logmessage (level, s, fullmessage = True, newline = True):
124     if (is_loglevel (level)):
125         if fullmessage:
126             stderr_write (program_name + ": " + s + '\n')
127         elif newline:
128             stderr_write (s + '\n')
129         else:
130             stderr_write (s)
131
132 def error (s):
133     print_logmessage ("ERROR", _ ("error: %s") % s);
134
135 def warning (s):
136     print_logmessage ("WARN", _ ("warning: %s") % s);
137
138 def basic_progress (s):
139     print_logmessage ("BASIC", s);
140
141 def progress (s, fullmessage = False, newline = True):
142     print_logmessage ("PROGRESS", s, fullmessage, newline);
143
144 def debug_output (s, fullmessage = False, newline = True):
145     print_logmessage ("DEBUG", s, fullmessage, newline);
146
147
148
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/")
155         sys.exit (2)
156
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.
160 def mkarg(x):
161     if os.name == 'nt':
162         return ' "%s"' % x
163     s = ' "'
164     for c in x:
165         if c in '\\$"`':
166             s = s + '\\'
167         s = s + c
168     s = s + '"'
169     return s
170
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)
176
177 def subprocess_system (cmd,
178                        ignore_error=False,
179                        progress_p=True,
180                        be_verbose=False,
181                        redirect_output=False,
182                        log_file=None):
183     import subprocess
184
185     show_progress= progress_p
186     name = command_name (cmd)
187     error_log_file = ''
188
189     if redirect_output:
190         progress (_ ("Processing %s.ly") % log_file)
191     else:
192         if be_verbose:
193             show_progress = 1
194             progress (_ ("Invoking `%s\'") % cmd)
195         else:
196             progress ( _("Running %s...") % name)
197
198     stdout_setting = None
199     stderr_setting = None
200     if not show_progress:
201         stdout_setting = subprocess.PIPE
202
203     if redirect_output:
204         stderr_filename = log_file + '.log'
205         stderr_setting = open(stderr_filename, 'w')
206
207     proc = subprocess.Popen (cmd,
208                              shell=True,
209                              universal_newlines=True,
210                              stdout=stdout_setting,
211                              stderr=stderr_setting)
212
213     log = ''
214
215     if redirect_output:
216         while proc.poll()==None:
217             time.sleep(0.01)
218         retval = proc.returncode
219         stderr_setting.close()
220     else:
221         if show_progress:
222             retval = proc.wait()
223         else:
224             log = proc.communicate ()
225             retval = proc.returncode
226
227     if retval:
228         print >>sys.stderr, 'command failed:', cmd
229         if retval < 0:
230             print >>sys.stderr, "Child was terminated by signal", -retval
231         elif retval > 0:
232             print >>sys.stderr, "Child returned", retval
233
234         if ignore_error:
235             print >>sys.stderr, "Error ignored by lilylib"
236         else:
237             if not show_progress:
238                 print log[0]
239                 print log[1]
240             sys.exit (1)
241
242     return abs (retval)
243
244 def ossystem_system (cmd,
245                      ignore_error=False,
246                      progress_p=True,
247                      be_verbose=False,
248                      redirect_output=False,
249                      log_file=None):
250
251
252     name = command_name (cmd)
253     if be_verbose:
254         show_progress = 1
255         progress (_ ("Invoking `%s\'") % cmd)
256     else:
257         progress ( _("Running %s...") % name)
258
259     retval = os.system (cmd)
260     if retval:
261         print >>sys.stderr, 'command failed:', cmd
262         if retval < 0:
263             print >>sys.stderr, "Child was terminated by signal", -retval
264         elif retval > 0:
265             print >>sys.stderr, "Child returned", retval
266
267         if ignore_error:
268             print >>sys.stderr, "Error ignored"
269         else:
270             sys.exit (1)
271
272     return abs (retval)
273
274
275 system = subprocess_system
276 if sys.platform == 'mingw32':
277
278     ## subprocess x-compile doesn't work.
279     system = ossystem_system
280
281 def strip_extension (f, ext):
282     (p, e) = os.path.splitext (f)
283     if e == ext:
284         e = ''
285     return p + e
286
287
288 def search_exe_path (name):
289     p = os.environ['PATH']
290     exe_paths = p.split (':')
291     for e in exe_paths:
292         full = os.path.join (e, name)
293         if os.path.exists (full):
294             return full
295     return None
296
297
298 def print_environment ():
299     for (k,v) in os.environ.items ():
300         sys.stderr.write ("%s=\"%s\"\n" % (k, v))
301
302 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
303     def format_heading(self, heading):
304         if heading:
305             return heading[0].upper() + heading[1:] + ':\n'
306         return ''
307     def format_option_strings(self, option):
308         sep = ' '
309         if option._short_opts and option._long_opts:
310             sep = ','
311
312         metavar = ''
313         if option.takes_value():
314             metavar = '=%s' % option.metavar or option.dest.upper()
315
316         return "%3s%s %s%s" % (" ".join (option._short_opts),
317                                sep,
318                                " ".join (option._long_opts),
319                                metavar)
320
321     # Only use one level of indentation (even for groups and nested groups),
322     # since we don't indent the headeings, either
323     def indent(self):
324         self.current_indent = self.indent_increment
325         self.level += 1
326     def dedent(self):
327         self.level -= 1
328         if self.level <= 0:
329             self.current_indent = ''
330             self.level = 0;
331
332     def format_usage(self, usage):
333         return _("Usage: %s") % usage + '\n'
334
335     def format_description(self, description):
336         return description
337
338 class NonEmptyOptionParser (optparse.OptionParser):
339     "A subclass of OptionParser that gobbles empty string arguments."
340
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)
344
345 def get_option_parser (*args, **kwargs):
346     p = NonEmptyOptionParser (*args, **kwargs)
347     p.formatter = NonDentedHeadingFormatter ()
348     p.formatter.set_parser (p)
349     return p