]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
Python lilylib: remove path insertion of @lilypond_datadir@/python
[lilypond.git] / python / lilylib.py
1 ###############################################################
2 # lilylib.py -- options and stuff
3
4 # source file of the GNU LilyPond music typesetter
5 #
6 # (c) 1998--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8
9 import __main__
10 import glob
11 import os
12 import re
13 import shutil
14 import sys
15 import optparse
16
17 ################################################################
18 # Users of python modules should include this snippet
19 # and customize variables below.
20
21 # We'll suffer this path init stuff as long as we don't install our
22 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
23 # it as we do with teTeX on Red Hat Linux: set some environment var
24 # (PYTHONPATH) in profile)
25
26 # If set, LILYPOND_DATADIR must take prevalence
27 # if datadir is not set, we're doing a build and LILYPOND_DATADIR
28
29 datadir = '@local_lilypond_datadir@'
30 if not os.path.isdir (datadir):
31     datadir = '@lilypond_datadir@'
32 if os.environ.has_key ('LILYPOND_DATADIR') :
33     datadir = os.environ['LILYPOND_DATADIR']
34     while datadir[-1] == os.sep:
35         datadir= datadir[:-1]
36
37 # Python 2.5 only accepts strings with proper Python internal encoding
38 # (i.e. ASCII or Unicode) when writing to stdout/stderr, so we must
39 # use ugettext iso gettext, and encode the string when writing to
40 # stdout/stderr
41
42 localedir = '@localedir@'
43 try:
44     import gettext
45     t = gettext.translation ('lilypond', localedir)
46     _ = t.ugettext
47 except:
48     def _ (s):
49         return s
50 underscore = _
51
52 # Urg, Python 2.4 does not define stderr/stdout encoding
53 # Maybe guess encoding from LANG/LC_ALL/LC_CTYPE?
54
55 def encoded_write(f, s):
56     f.write (s.encode (f.encoding or 'utf_8'))
57
58 # ugh, Python 2.5 optparse requires Unicode strings in some argument
59 # functions, and refuse them in some other places
60 def display_encode (s):
61     return s.encode (sys.stderr.encoding or 'utf_8')
62
63 def stderr_write (s):
64     encoded_write (sys.stderr, s)
65
66 progress = stderr_write
67
68 def require_python_version ():
69     if sys.hexversion < 0x02040000:
70         stderr_write ("Python 2.4 or newer is required to run this program.\n\
71 Please upgrade Python from http://python.org/download/, and if you use MacOS X,\n\
72 please read 'Setup for MacOS X' in Application Usage.")
73         os.system ("open http://python.org/download/")
74         sys.exit (2)
75
76 # Modified version of the commands.mkarg(x), which always uses 
77 # double quotes (since Windows can't handle the single quotes:
78 def mkarg(x):
79     s = ' "'
80     for c in x:
81         if c in '\\$"`':
82             s = s + '\\'
83         s = s + c
84     s = s + '"'
85     return s
86
87 def command_name (cmd):
88     # Strip all stuf after command,
89     # deal with "((latex ) >& 1 ) .." too
90     cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
91     return os.path.basename (cmd)
92
93 def subprocess_system (cmd,
94                        ignore_error=False,
95                        progress_p=True,
96                        be_verbose=False,
97                        log_file=None):
98     import subprocess
99
100     show_progress= progress_p 
101     name = command_name (cmd)
102     error_log_file = ''
103
104     if be_verbose:
105         show_progress = 1
106         progress (_ ("Invoking `%s\'") % cmd)
107     else:
108         progress ( _("Running %s...") % name)
109
110
111     stdout_setting = None
112     if not show_progress:
113         stdout_setting = subprocess.PIPE
114
115     proc = subprocess.Popen (cmd,
116                              shell=True,
117                              universal_newlines=True,
118                              stdout=stdout_setting,
119                              stderr=stdout_setting)
120
121     log = ''
122
123     if show_progress:
124         retval = proc.wait()
125     else:
126         log = proc.communicate ()
127         retval = proc.returncode
128
129
130     if retval:
131         print >>sys.stderr, 'command failed:', cmd
132         if retval < 0:
133             print >>sys.stderr, "Child was terminated by signal", -retval
134         elif retval > 0:
135             print >>sys.stderr, "Child returned", retval
136
137         if ignore_error:
138             print >>sys.stderr, "Error ignored"
139         else:
140             if not show_progress:
141                 print log[0]
142                 print log[1]
143             sys.exit (1)
144
145     return abs (retval)
146
147 def ossystem_system (cmd,
148                      ignore_error=False,
149                      progress_p=True,
150                      be_verbose=False,
151                      log_file=None):
152
153
154     name = command_name (cmd)
155     if be_verbose:
156         show_progress = 1
157         progress (_ ("Invoking `%s\'") % cmd)
158     else:
159         progress ( _("Running %s...") % name)
160
161     retval = os.system (cmd)
162     if retval:
163         print >>sys.stderr, 'command failed:', cmd
164         if retval < 0:
165             print >>sys.stderr, "Child was terminated by signal", -retval
166         elif retval > 0:
167             print >>sys.stderr, "Child returned", retval
168
169         if ignore_error:
170             print >>sys.stderr, "Error ignored"
171         else:
172             sys.exit (1)
173
174     return abs (retval)
175
176
177 system = subprocess_system
178 if sys.platform == 'mingw32':
179     
180     ## subprocess x-compile doesn't work.
181     system = ossystem_system
182
183 def strip_extension (f, ext):
184     (p, e) = os.path.splitext (f)
185     if e == ext:
186         e = ''
187     return p + e
188
189
190 def search_exe_path (name):
191     p = os.environ['PATH']
192     exe_paths = p.split (':')
193     for e in exe_paths:
194         full = os.path.join (e, name)
195         if os.path.exists (full):
196             return full
197     return None
198
199
200 def print_environment ():
201     for (k,v) in os.environ.items ():
202         sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
203
204 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
205     def format_heading(self, heading):
206         if heading:
207             return heading[0].upper() + heading[1:] + ':\n'
208         return ''
209     def format_option_strings(self, option):
210         sep = ' '
211         if option._short_opts and option._long_opts:
212             sep = ','
213
214         metavar = ''
215         if option.takes_value():
216             metavar = '=%s' % option.metavar or option.dest.upper()
217
218         return "%3s%s %s%s" % (" ".join (option._short_opts),
219                                sep,
220                                " ".join (option._long_opts),
221                                metavar)
222
223     def format_usage(self, usage):
224         return _("Usage: %s") % usage + '\n'
225
226     def format_description(self, description):
227         return description
228
229 def get_option_parser (*args, **kwargs): 
230     p = optparse.OptionParser (*args, **kwargs)
231     p.formatter = NonDentedHeadingFormatter () 
232     return p