]> git.donarmstrong.com Git - lilypond.git/blob - scripts/convert-ly.py
(datadir): remove LILYPONDPREFIX support.
[lilypond.git] / scripts / convert-ly.py
1 #!@TARGET_PYTHON@
2 #
3 # convert-ly.py -- Update old LilyPond input files (fix name?)
4 #
5 # source file of the GNU LilyPond music typesetter
6 #
7 # (c) 1998--2006  Han-Wen Nienhuys <hanwen@cs.uu.nl>
8 #                 Jan Nieuwenhuizen <janneke@gnu.org>
9 #
10 # converting rules are found in python/convertrules.py
11 #
12
13 import os
14 import sys
15 import string
16 import re
17
18
19 datadir = '@local_lilypond_datadir@'
20 if not os.path.isdir (datadir):
21     datadir = '@lilypond_datadir@'
22
23 sys.path.insert (0, os.path.join (datadir, 'python'))
24
25 # dynamic relocation, for GUB binaries.
26 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
27 for p in ['share', 'lib']:
28     datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
29     sys.path.insert (0, datadir)
30
31 import lilylib as ly
32 global _;_=ly._
33
34 from convertrules import *
35
36 lilypond_version_re_str = '\\\\version *\"([0-9.]+)"'
37 lilypond_version_re = re.compile (lilypond_version_re_str)
38
39
40 help_summary = _ (
41 '''Update LilyPond input to newer version.  By default, update from the
42 version taken from the \\version command, to the current LilyPond version.
43
44 Examples:
45
46   convert-ly -e old.ly
47   convert-ly --from=2.3.28 --to 2.5.21 foobar.ly
48 ''')
49
50 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
51          'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
52
53 program_name = os.path.basename (sys.argv[0])
54 program_version = '@TOPLEVEL_VERSION@'
55
56 add_version = 1
57
58 def warning (s):
59     sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
60
61 def error (s):
62     sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
63
64 def identify (port=sys.stderr):
65     port.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
66
67 def warranty ():
68     identify ()
69     sys.stdout.write ('''
70 Copyright (c) %s by
71
72   Han-Wen Nienhuys
73   Jan Nieuwenhuizen
74
75 %s
76 %s
77 '''  ( '2001--2006',
78        _('Distributed under terms of the GNU General Public License.'),
79        _('It comes with NO WARRANTY.')))
80
81
82
83 def get_option_parser ():
84     p = ly.get_option_parser (usage='convert-ly [OPTIONS] FILE',
85                   version="@TOPLEVEL_VERSION@",
86                   description=help_summary)
87
88     p.add_option ('-f', '--from', 
89               action="store",
90               metavar=_ ("VERSION"),
91               dest="from_version",
92               help=_('start from VERSION [default: \\version found in file]'),
93               default='')
94     
95     p.add_option ('-e', '--edit', help=_('edit in place'),
96               action='store_true')
97     p.add_option ('-n', '--no-version',
98               help=_ ('do not add \\version command if missing'),
99               action='store_true',
100               dest='skip_version_add',
101               default=False)
102     
103     p.add_option ("-s", '--show-rules',
104               help=_('print rules [default: --from=0, --to=@TOPLEVEL_VERSION@]'),
105               dest='show_rules',
106               action='store_true', default=False)
107     
108     p.add_option ('-t', '--to',
109               help=_('convert to VERSION [default: @TOPLEVEL_VERSION@]'),
110               metavar=_('VERSION'),
111               action='store',
112               dest="to_version",
113               default='')
114
115     p.add_option_group  ('bugs',
116                  description='''Report bugs via http://post.gmane.org/post.php'''
117                  '''?group=gmane.comp.gnu.lilypond.bugs\n''')
118     
119     return p
120
121
122
123 def str_to_tuple (s):
124     return tuple (map (int, string.split (s, '.')))
125
126 def tup_to_str (t):
127     return string.join (map (lambda x: '%s' % x, list (t)), '.')
128
129 def version_cmp (t1, t2):
130     for x in [0, 1, 2]:
131         if t1[x] - t2[x]:
132             return t1[x] - t2[x]
133     return 0
134
135 def get_conversions (from_version, to_version):
136     def is_applicable (v, f = from_version, t = to_version):
137         return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
138     return filter (is_applicable, conversions)
139
140 def latest_version ():
141     return conversions[-1][0]
142
143 def show_rules (file, from_version, to_version):
144     for x in conversions:
145         if (not from_version or x[0] > from_version) \
146            and (not to_version or x[0] <= to_version):
147             file.write  ('%s: %s\n' % (tup_to_str (x[0]), x[2]))
148
149 def do_conversion (str, from_version, to_version):
150     """Apply conversions from FROM_VERSION to TO_VERSION.  Return
151 tuple (LAST,STR), with the last succesful conversion and the resulting
152 string."""
153     conv_list = get_conversions (from_version, to_version)
154
155     if error_file:
156         error_file.write (_ ("Applying conversion: "))
157         
158     last_conversion = ()
159     try:
160         for x in conv_list:
161             error_file.write (tup_to_str (x[0]))
162             if x != conv_list[-1]:
163                 error_file.write (', ')
164             str = x[1] (str)
165             last_conversion = x[0]
166
167     except FatalConversionError:
168         error_file.write (_ ("error while converting")) 
169         error_file.write ('\n')
170         error_file.write (_ ("Aborting"))
171         error_file.write ('\n')
172
173
174
175     return (last_conversion, str)
176
177
178
179 def guess_lilypond_version (filename):
180     s = open (filename).read ()
181     m = lilypond_version_re.search (s)
182     if m:
183         return m.group (1)
184     else:
185         return ''
186
187 class FatalConversionError:
188     pass
189
190 class UnknownVersion:
191     pass
192
193 def do_one_file (infile_name):
194     sys.stderr.write (_ ("Processing `%s\'... ") % infile_name)
195     sys.stderr.write ('\n')
196
197     from_version = None
198     to_version = None
199     if global_options.from_version:
200         from_version = global_options.from_version
201     else:
202         guess = guess_lilypond_version (infile_name)
203         if not guess:
204             raise UnknownVersion ()
205         from_version = str_to_tuple (guess)
206
207     if global_options.to_version:
208         to_version = global_options.to_version
209     else:
210         to_version = latest_version ()
211
212
213     if infile_name:
214         infile = open (infile_name, 'r')
215     else:
216         infile = sys.stdin
217
218
219     (last, result) = do_conversion (infile.read (), from_version, to_version)
220     infile.close ()
221
222     if last:
223         newversion = r'\version "%s"' % tup_to_str (last)
224         if lilypond_version_re.search (result):
225             result = re.sub (lilypond_version_re_str,
226                      '\\' + newversion, result)
227         elif add_version:
228             result = newversion + '\n' + result
229             
230         error_file.write ('\n')            
231     
232         if global_options.edit:
233             try:
234                 os.remove(infile_name + '~')
235             except:
236                 pass
237             os.rename (infile_name, infile_name + '~')
238             outfile = open (infile_name, 'w')
239         else:
240             outfile = sys.stdout
241
242
243         outfile.write (result)
244
245     sys.stderr.flush ()
246
247 def do_options ():
248     opt_parser = get_option_parser()
249     (options, args) = opt_parser.parse_args ()
250
251
252     if options.from_version:
253         options.from_version = str_to_tuple (options.from_version)
254     if options.to_version:
255         options.to_version = str_to_tuple (options.to_version)
256
257     options.outfile_name = ''
258     global global_options
259     global_options = options
260
261     if not args and not options.show_rules:
262         opt_parser.print_help ()
263         sys.exit (2)
264
265     return args
266
267 def main ():
268     files = do_options ()
269
270     # should parse files[] to read \version?
271     if global_options.show_rules:
272         show_rules (sys.stdout, global_options.from_version, global_options.to_version)
273         sys.exit (0)
274
275     identify (sys.stderr)
276
277     for f in files:
278         if f == '-':
279             f = ''
280         elif not os.path.isfile (f):
281             error (_ ("can't open file: `%s'") % f)
282             if len (files) == 1:
283                 sys.exit (1)
284             continue
285         try:
286             do_one_file (f)
287         except UnknownVersion:
288             error (_ ("can't determine version for `%s'. Skipping") % f)
289
290     sys.stderr.write ('\n')
291
292 main ()