]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
877b98e360b1a67cd0390627385e524d9c87a9da
[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--2006 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 string
15 import sys
16 import optparse
17
18 ################################################################
19 # Users of python modules should include this snippet
20 # and customize variables below.
21
22 # We'll suffer this path init stuff as long as we don't install our
23 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
24 # it as we do with teTeX on Red Hat Linux: set some environment var
25 # (PYTHONPATH) in profile)
26
27 # If set, LILYPONDPREFIX must take prevalence
28 # if datadir is not set, we're doing a build and LILYPONDPREFIX
29
30 datadir = '@local_lilypond_datadir@'
31 if not os.path.isdir (datadir):
32     datadir = '@lilypond_datadir@'
33 if os.environ.has_key ('LILYPONDPREFIX') :
34     datadir = os.environ['LILYPONDPREFIX']
35     while datadir[-1] == os.sep:
36         datadir= datadir[:-1]
37
38 sys.path.insert (0, os.path.join (datadir, 'python'))
39
40
41
42
43 localedir = '@localedir@'
44 try:
45     import gettext
46     gettext.bindtextdomain ('lilypond', localedir)
47     gettext.textdomain ('lilypond')
48     _ = gettext.gettext
49 except:
50     def _ (s):
51         return s
52 underscore = _
53 progress = sys.stderr.write 
54
55 # Modified version of the commands.mkarg(x), which always uses 
56 # double quotes (since Windows can't handle the single quotes:
57 def mkarg(x):
58     s = ' "'
59     for c in x:
60         if c in '\\$"`':
61             s = s + '\\'
62         s = s + c
63     s = s + '"'
64     return s
65
66 def command_name (cmd):
67     # Strip all stuf after command,
68     # deal with "((latex ) >& 1 ) .." too
69     cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
70     return os.path.basename (cmd)
71
72 def subprocess_system (cmd,
73                        ignore_error=False,
74                        progress_p=True,
75                        be_verbose=False,
76                        log_file=None):
77     import subprocess
78
79     show_progress= progress_p 
80     name = command_name (cmd)
81     error_log_file = ''
82
83     if be_verbose:
84         show_progress = 1
85         progress (_ ("Invoking `%s\'") % cmd)
86     else:
87         progress ( _("Running %s...") % name)
88
89
90     stdout_setting = None
91     if not show_progress:
92         stdout_setting = subprocess.PIPE
93
94     proc = subprocess.Popen (cmd,
95                              shell=True,
96                              universal_newlines=True,
97                              stdout=stdout_setting,
98                              stderr=stdout_setting)
99
100     log = ''
101
102     if show_progress:
103         retval = proc.wait()
104     else:
105         log = proc.communicate ()
106         retval = proc.returncode
107
108
109     if retval:
110         print >>sys.stderr, 'command failed:', cmd
111         if retval < 0:
112             print >>sys.stderr, "Child was terminated by signal", -retval
113         elif retval > 0:
114             print >>sys.stderr, "Child returned", retval
115
116         if ignore_error:
117             print >>sys.stderr, "Error ignored"
118         else:
119             if not show_progress:
120                 print log[0]
121                 print log[1]
122             sys.exit (1)
123
124     return abs (retval)
125
126 def ossystem_system (cmd,
127                      ignore_error=False,
128                      progress_p=True,
129                      be_verbose=False,
130                      log_file=None):
131
132
133     name = command_name (cmd)
134     if be_verbose:
135         show_progress = 1
136         progress (_ ("Invoking `%s\'") % cmd)
137     else:
138         progress ( _("Running %s...") % name)
139
140     retval = os.system (cmd)
141     if retval:
142         print >>sys.stderr, 'command failed:', cmd
143         if retval < 0:
144             print >>sys.stderr, "Child was terminated by signal", -retval
145         elif retval > 0:
146             print >>sys.stderr, "Child returned", retval
147
148         if ignore_error:
149             print >>sys.stderr, "Error ignored"
150         else:
151             sys.exit (1)
152
153     return abs (retval)
154
155
156 system = subprocess_system
157 if sys.platform == 'mingw32':
158     
159     ## subprocess x-compile doesn't work.
160     system = ossystem_system
161
162 def strip_extension (f, ext):
163     (p, e) = os.path.splitext (f)
164     if e == ext:
165         e = ''
166     return p + e
167
168
169 def search_exe_path (name):
170     p = os.environ['PATH']
171     exe_paths = string.split (p, ':')
172     for e in exe_paths:
173         full = os.path.join (e, name)
174         if os.path.exists (full):
175             return full
176     return None
177
178
179 def print_environment ():
180     for (k,v) in os.environ.items ():
181         sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
182
183 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
184     def format_heading(self, heading):
185         if heading:
186             return heading[0].upper() + heading[1:] + ':\n'
187         return ''
188     def format_option_strings(self, option):
189         sep = ' '
190         if option._short_opts and option._long_opts:
191             sep = ','
192
193         metavar = ''
194         if option.takes_value():
195             metavar = '=%s' % option.metavar or option.dest.upper()
196
197         return "%3s%s %s%s" % (" ".join (option._short_opts),
198                                sep,
199                                " ".join (option._long_opts),
200                                metavar)
201
202     def format_usage(self, usage):
203         return _("Usage: %s\n") % usage
204
205     def format_description(self, description):
206         return description
207
208 def get_option_parser (*args, **kwargs): 
209     p = optparse.OptionParser (*args, **kwargs)
210     p.formatter = NonDentedHeadingFormatter () 
211     return p