]> git.donarmstrong.com Git - lilypond.git/blob - scripts/convert-ly.py
Merge branch 'lilypond/translation' of ssh://git.sv.gnu.org/srv/git/lilypond into...
[lilypond.git] / scripts / convert-ly.py
1 #!@TARGET_PYTHON@
2
3 # convert-ly.py -- Update old LilyPond input files (fix name?)
4 # converting rules are found in python/convertrules.py
5
6 # This file is part of LilyPond, the GNU music typesetter.
7 #
8 # Copyright (C) 1998--2010  Han-Wen Nienhuys <hanwen@xs4all.nl>
9 #                 Jan Nieuwenhuizen <janneke@gnu.org>
10 #
11 # LilyPond is free software: you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation, either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # LilyPond is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
23
24 import os
25 import sys
26 import re
27
28 """
29 @relocate-preamble@
30 """
31
32 import lilylib as ly
33 global _;_=ly._
34
35 ly.require_python_version ()
36
37 import convertrules
38
39 lilypond_version_re_str = '\\\\version *\"([0-9.]+)"'
40 lilypond_version_re = re.compile (lilypond_version_re_str)
41
42
43 help_summary = (
44 _ ('''Update LilyPond input to newer version.  By default, update from the
45 version taken from the \\version command, to the current LilyPond version.''')
46 + _ ("Examples:")
47 + '''
48   $ convert-ly -e old.ly
49   $ convert-ly --from=2.3.28 --to=2.5.21 foobar.ly > foobar-new.ly
50 ''')
51
52 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
53              'Han-Wen Nienhuys <hanwen@xs4all.nl>')
54
55 program_name = os.path.basename (sys.argv[0])
56 program_version = '@TOPLEVEL_VERSION@'
57
58 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
59            'Han-Wen Nienhuys <hanwen@xs4all.nl>')
60
61 error_file_write = ly.stderr_write
62
63 def warning (s):
64     ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
65
66 def error (s):
67     ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
68
69 def identify (port=sys.stderr):
70     ly.encoded_write (port, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
71
72 def warranty ():
73     identify ()
74     ly.encoded_write (sys.stdout, '''
75 %s
76
77 %s
78
79 %s
80 %s
81 ''' % ( _ ('Copyright (c) %s by') % '2001--2010',
82         ' '.join (authors),
83         _ ('Distributed under terms of the GNU General Public License.'),
84         _ ('It comes with NO WARRANTY.')))
85
86 def get_option_parser ():
87     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'convert-ly',
88                   description=help_summary,
89                   add_help_option=False)
90
91     p.version="@TOPLEVEL_VERSION@"
92     p.add_option("--version",
93                  action="version",
94                  help=_ ("show version number and exit"))
95
96     p.add_option("-h", "--help",
97                  action="help",
98                  help=_ ("show this help and exit"))
99
100     p.add_option ('-f', '--from', 
101               action="store",
102               metavar=_ ("VERSION"),
103               dest="from_version",
104               help=_ ("start from VERSION [default: \\version found in file]"),
105               default='')
106     
107     p.add_option ('-e', '--edit', help=_ ("edit in place"),
108               action='store_true')
109
110     p.add_option ('-n', '--no-version',
111               help=_ ("do not add \\version command if missing"),
112               action='store_true',
113               dest='skip_version_add',
114               default=False)
115
116     p.add_option ('-c', '--current-version',
117               help=_ ("force updating \\version number to %s") % program_version,
118               action='store_true',
119               dest='force_current_version',
120               default=False)
121
122     p.add_option ('-d', '--diff-version-update',
123               help=_ ("only update \\version number if file is modified"),
124               action='store_true',
125               dest='diff_version_update',
126               default=False)
127     
128     p.add_option ("-s", '--show-rules',
129               help=_ ("show rules [default: -f 0, -t %s]") % program_version,
130               dest='show_rules',
131               action='store_true', default=False)
132     
133     p.add_option ('-t', '--to',
134               help=_ ("convert to VERSION [default: %s]") % program_version,
135               metavar=_ ('VERSION'),
136               action='store',
137               dest="to_version",
138               default='')
139     p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
140            action='store_true',
141            ),
142     p.add_option_group ('',
143                         description=(
144             _ ("Report bugs via %s")
145             % 'http://post.gmane.org/post.php'
146             '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
147     
148     return p
149
150
151
152 def str_to_tuple (s):
153     return tuple ([int(n) for n in s.split ('.')])
154
155 def tup_to_str (t):
156     return '.'.join (['%s' % x for x in t])
157
158 def version_cmp (t1, t2):
159     for x in [0, 1, 2]:
160         if t1[x] - t2[x]:
161             return t1[x] - t2[x]
162     return 0
163
164 def get_conversions (from_version, to_version):
165     def is_applicable (v, f = from_version, t = to_version):
166         return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
167     return filter (is_applicable, convertrules.conversions)
168
169 def latest_version ():
170     return convertrules.conversions[-1][0]
171
172 def show_rules (file, from_version, to_version):
173     for x in convertrules.conversions:
174         if (not from_version or x[0] > from_version) \
175            and (not to_version or x[0] <= to_version):
176             ly.encoded_write  (file, '%s: %s\n' % (tup_to_str (x[0]), x[2]))
177
178 def do_conversion (str, from_version, to_version):
179     """Apply conversions from FROM_VERSION to TO_VERSION.  Return
180 tuple (LAST,STR), with the last successful conversion and the resulting
181 string."""
182     conv_list = get_conversions (from_version, to_version)
183
184     error_file_write (_ ("Applying conversion: "))
185         
186     last_conversion = ()
187     try:
188         for x in conv_list:
189             error_file_write (tup_to_str (x[0]))
190             if x != conv_list[-1]:
191                 error_file_write (', ')
192             str = x[1] (str)
193             last_conversion = x[0]
194
195     except convertrules.FatalConversionError:
196         error_file_write ('\n'
197                           + _ ("Error while converting")
198                           + '\n'
199                           + _ ("Stopping at last successful rule")
200                           + '\n')
201
202     return (last_conversion, str)
203
204
205
206 def guess_lilypond_version (input):
207     m = lilypond_version_re.search (input)
208     if m:
209         return m.group (1)
210     else:
211         return ''
212
213 class FatalConversionError (Exception):
214     pass
215
216 class UnknownVersion (Exception):
217     pass
218
219 class InvalidVersion (Exception):
220     def __init__ (self, version):
221       self.version = version
222
223 def do_one_file (infile_name):
224     ly.stderr_write (_ ("Processing `%s\'... ") % infile_name)
225     sys.stderr.write ('\n')
226
227     if infile_name:
228         infile = open (infile_name, 'r')
229         input = infile.read ()
230         infile.close ()
231     else:
232         input = sys.stdin.read ()
233
234     from_version = None
235     to_version = None
236     if global_options.from_version:
237         from_version = global_options.from_version
238     else:
239         guess = guess_lilypond_version (input)
240         if not guess:
241             raise UnknownVersion ()
242         from_version = str_to_tuple (guess)
243
244     if global_options.to_version:
245         to_version = global_options.to_version
246     else:
247         to_version = latest_version ()
248
249     if len (from_version) != 3:
250         raise InvalidVersion (".".join ([str(n) for n in from_version]))
251
252
253     (last, result) = do_conversion (input, from_version, to_version)
254
255     if last:
256         if global_options.force_current_version and last == to_version:
257             last = str_to_tuple (program_version)
258
259         if global_options.diff_version_update:
260             if result == input:
261                 # check the y in x.y.z  (minor version number)
262                 previous_stable = (last[0], 2*(last[1]/2), 0)
263                 if ((last[0:2] != from_version[0:2]) and
264                     (previous_stable > from_version)):
265                     # previous stable version
266                     last = previous_stable
267                 else:
268                     # make no (actual) change to the version number
269                     last = from_version
270
271         newversion = r'\version "%s"' % tup_to_str (last)
272         if lilypond_version_re.search (result):
273             result = re.sub (lilypond_version_re_str,
274                      '\\' + newversion, result)
275         elif not global_options.skip_version_add:
276             result = newversion + '\n' + result
277             
278         error_file_write ('\n')            
279     
280         if global_options.edit:
281             try:
282                 os.remove(infile_name + '~')
283             except:
284                 pass
285             os.rename (infile_name, infile_name + '~')
286             outfile = open (infile_name, 'w')
287         else:
288             outfile = sys.stdout
289
290
291         outfile.write (result)
292
293     sys.stderr.flush ()
294
295 def do_options ():
296     opt_parser = get_option_parser()
297     (options, args) = opt_parser.parse_args ()
298
299     if options.warranty:
300         warranty ()
301         sys.exit (0)
302
303     if options.from_version:
304         options.from_version = str_to_tuple (options.from_version)
305     if options.to_version:
306         options.to_version = str_to_tuple (options.to_version)
307
308     options.outfile_name = ''
309     global global_options
310     global_options = options
311
312     if not args and not options.show_rules:
313         opt_parser.print_help ()
314         sys.exit (2)
315
316     return args
317
318 def main ():
319     files = do_options ()
320
321     # should parse files[] to read \version?
322     if global_options.show_rules:
323         show_rules (sys.stdout, global_options.from_version, global_options.to_version)
324         sys.exit (0)
325
326     identify (sys.stderr)
327
328     for f in files:
329         if f == '-':
330             f = ''
331         elif not os.path.isfile (f):
332             error (_ ("%s: Unable to open file") % f)
333             if len (files) == 1:
334                 sys.exit (1)
335             continue
336         try:
337             do_one_file (f)
338         except UnknownVersion:
339             error (_ ("%s: Unable to determine version.  Skipping") % f)
340         except InvalidVersion:
341             # Compat code for 2.x and 3.0 syntax ("except .. as v" doesn't 
342             # work in python 2.4!):
343             t, v, b = sys.exc_info ()
344             error (_ ("%s: Invalid version string `%s' \n"
345                       "Valid version strings consist of three numbers, "
346                       "separated by dots, e.g. `2.8.12'") % (f, v.version) )
347
348     sys.stderr.write ('\n')
349
350 main ()