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