]> git.donarmstrong.com Git - lilypond.git/blob - scripts/convert-ly.py
Merge remote-tracking branch 'origin/translation' into master
[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--2012  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 lilypond_version_strict_re_str = '\\\\version *\"([0-9]+[.][0-9]+[.][0-9]+)"'
43 lilypond_version_strict_re = re.compile (lilypond_version_strict_re_str)
44
45 help_summary = (
46 _ ('''Update LilyPond input to newer version.  By default, update from the
47 version taken from the \\version command, to the current LilyPond version.''')
48 + _ ("Examples:")
49 + '''
50   $ convert-ly -e old.ly
51   $ convert-ly --from=2.3.28 --to=2.5.21 foobar.ly > foobar-new.ly
52 ''')
53
54 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
55              'Han-Wen Nienhuys <hanwen@xs4all.nl>')
56
57 program_name = os.path.basename (sys.argv[0])
58 program_version = '@TOPLEVEL_VERSION@'
59
60 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
61            'Han-Wen Nienhuys <hanwen@xs4all.nl>')
62
63 def identify ():
64     ly.progress ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
65
66 def warranty ():
67     identify ()
68     ly.encoded_write (sys.stdout, '''
69 %s
70
71 %s
72
73 %s
74 %s
75 ''' % ( _ ('Copyright (c) %s by') % '2001--2012',
76         ' '.join (authors),
77         _ ('Distributed under terms of the GNU General Public License.'),
78         _ ('It comes with NO WARRANTY.')))
79
80 def get_option_parser ():
81     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'convert-ly',
82                   description=help_summary,
83                   add_help_option=False)
84
85     p.version="@TOPLEVEL_VERSION@"
86     p.add_option("--version",
87                  action="version",
88                  help=_ ("show version number and exit"))
89
90     p.add_option("-h", "--help",
91                  action="help",
92                  help=_ ("show this help and exit"))
93
94     p.add_option ('-f', '--from', 
95               action="store",
96               metavar=_ ("VERSION"),
97               dest="from_version",
98               help=_ ("start from VERSION [default: \\version found in file]"),
99               default='')
100     
101     p.add_option ('-e', '--edit', help=_ ("edit in place"),
102               action='store_true')
103
104     p.add_option ("-l", "--loglevel",
105                   help=_ ("Print log messages according to LOGLEVEL "
106                           "(NONE, ERROR, WARNING, PROGRESS (default), DEBUG)"),
107                   metavar=_ ("LOGLEVEL"),
108                   action='callback',
109                   callback=ly.handle_loglevel_option,
110                   type='string')
111
112     p.add_option ('-n', '--no-version',
113               help=_ ("do not add \\version command if missing"),
114               action='store_true',
115               dest='skip_version_add',
116               default=False)
117
118     p.add_option ('-c', '--current-version',
119               help=_ ("force updating \\version number to %s") % program_version,
120               action='store_true',
121               dest='force_current_version',
122               default=False)
123
124     p.add_option ('-d', '--diff-version-update',
125               help=_ ("only update \\version number if file is modified"),
126               action='store_true',
127               dest='diff_version_update',
128               default=False)
129     
130     p.add_option ("-s", '--show-rules',
131               help=_ ("show rules [default: -f 0, -t %s]") % program_version,
132               dest='show_rules',
133               action='store_true', default=False)
134     
135     p.add_option ('-t', '--to',
136               help=_ ("convert to VERSION [default: %s]") % program_version,
137               metavar=_ ('VERSION'),
138               action='store',
139               dest="to_version",
140               default='')
141     p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
142            action='store_true',
143            ),
144     p.add_option_group ('',
145                         description=(
146             _ ("Report bugs via %s")
147             % 'http://post.gmane.org/post.php'
148             '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
149     
150     return p
151
152
153
154 def str_to_tuple (s):
155     return tuple ([int(n) for n in s.split ('.')])
156
157 def tup_to_str (t):
158     return '.'.join (['%s' % x for x in t])
159
160 def version_cmp (t1, t2):
161     for x in [0, 1, 2]:
162         if t1[x] - t2[x]:
163             return t1[x] - t2[x]
164     return 0
165
166 def get_conversions (from_version, to_version):
167     def is_applicable (v, f = from_version, t = to_version):
168         return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
169     return filter (is_applicable, convertrules.conversions)
170
171 def latest_version ():
172     return convertrules.conversions[-1][0]
173
174 def show_rules (file, from_version, to_version):
175     for x in convertrules.conversions:
176         if (not from_version or x[0] > from_version) \
177            and (not to_version or x[0] <= to_version):
178             ly.encoded_write  (file, '%s: %s\n' % (tup_to_str (x[0]), x[2]))
179
180 def do_conversion (str, from_version, to_version):
181     """Apply conversions from FROM_VERSION to TO_VERSION.  Return
182 tuple (LAST,STR), with the last successful conversion and the resulting
183 string."""
184     conv_list = get_conversions (from_version, to_version)
185
186     ly.progress (_ ("Applying conversion: "), newline = False)
187
188     last_conversion = None
189     errors = 0
190     try:
191         for x in conv_list:
192             if x != conv_list[-1]:
193                 ly.progress (tup_to_str (x[0]), newline = False)
194                 ly.progress (', ', newline = False)
195             else:
196                 ly.progress (tup_to_str (x[0]))
197             str = x[1] (str)
198             last_conversion = x[0]
199
200     except convertrules.FatalConversionError:
201         ly.error (_ ("Error while converting")
202                   + '\n'
203                   + _ ("Stopping at last successful rule"))
204         errors += 1
205
206     return (last_conversion, str, errors)
207
208
209
210 def guess_lilypond_version (input):
211     m = lilypond_version_strict_re.search (input)
212     if m:
213         return m.group (1)
214     m = lilypond_version_re.search (input)
215     if m:
216         raise InvalidVersion (m.group (1))
217     else:
218         return ''
219
220 class FatalConversionError (Exception):
221     pass
222
223 class UnknownVersion (Exception):
224     pass
225
226 class InvalidVersion (Exception):
227     def __init__ (self, version):
228       self.version = version
229
230 def do_one_file (infile_name):
231     ly.progress (_ (u"Processing `%s\'... ") % infile_name, True)
232
233     if infile_name:
234         infile = open (infile_name, 'r')
235         input = infile.read ()
236         infile.close ()
237     else:
238         input = sys.stdin.read ()
239
240     from_version = None
241     to_version = None
242     if global_options.from_version:
243         from_version = global_options.from_version
244     else:
245         guess = guess_lilypond_version (input)
246         if not guess:
247             raise UnknownVersion ()
248         from_version = str_to_tuple (guess)
249
250     if global_options.to_version:
251         to_version = global_options.to_version
252     else:
253         to_version = latest_version ()
254
255     if len (from_version) != 3:
256         raise InvalidVersion (".".join ([str(n) for n in from_version]))
257
258
259     (last, result, errors) = do_conversion (input, from_version, to_version)
260
261     if global_options.force_current_version and \
262             (last is None or last == to_version):
263         last = str_to_tuple (program_version)
264     if last:
265         if global_options.diff_version_update:
266             if result == input:
267                 # check the y in x.y.z  (minor version number)
268                 previous_stable = (last[0], 2*(last[1]/2), 0)
269                 if ((last[0:2] != from_version[0:2]) and
270                     (previous_stable > from_version)):
271                     # previous stable version
272                     last = previous_stable
273                 else:
274                     # make no (actual) change to the version number
275                     last = from_version
276
277         newversion = r'\version "%s"' % tup_to_str (last)
278         if lilypond_version_re.search (result):
279             result = re.sub (lilypond_version_re_str,
280                      '\\' + newversion, result)
281         elif not global_options.skip_version_add:
282             result = newversion + '\n' + result
283
284     ly.progress ('\n')
285
286     if global_options.edit:
287         try:
288             os.remove (infile_name + '~')
289         except:
290             pass
291         os.rename (infile_name, infile_name + '~')
292         outfile = open (infile_name, 'w')
293     else:
294         outfile = sys.stdout
295
296     outfile.write (result)
297     
298     sys.stderr.flush ()
299
300     return errors
301
302 def do_options ():
303     opt_parser = get_option_parser()
304     (options, args) = opt_parser.parse_args ()
305
306     if options.warranty:
307         warranty ()
308         sys.exit (0)
309
310     if options.from_version:
311         options.from_version = str_to_tuple (options.from_version)
312     if options.to_version:
313         options.to_version = str_to_tuple (options.to_version)
314
315     options.outfile_name = ''
316     global global_options
317     global_options = options
318
319     if not args and not options.show_rules:
320         opt_parser.print_help ()
321         sys.exit (2)
322
323     return args
324
325 def main ():
326     files = do_options ()
327
328     # should parse files[] to read \version?
329     if global_options.show_rules:
330         show_rules (sys.stdout, global_options.from_version, global_options.to_version)
331         sys.exit (0)
332
333     identify ()
334
335     errors = 0
336     for f in files:
337         if f == '-':
338             continue
339         f = f.decode (sys.stdin.encoding or "utf-8")
340         if not os.path.isfile (f):
341             ly.error (_ (u"%s: Unable to open file") % f)
342             errors += 1
343             continue
344         try:
345             errors += do_one_file (f)
346         except UnknownVersion:
347             ly.error (_ (u"%s: Unable to determine version.  Skipping") % f)
348             errors += 1
349         except InvalidVersion:
350             # Compat code for 2.x and 3.0 syntax ("except .. as v" doesn't 
351             # work in python 2.4!):
352             t, v, b = sys.exc_info ()
353             ly.error (_ (u"%s: Invalid version string `%s' \n"
354                          "Valid version strings consist of three numbers, "
355                          "separated by dots, e.g. `2.8.12'") % (f, v.version) )
356             errors += 1
357
358     if errors:
359         ly.warning (ly.ungettext ("There was %d error.",
360             "There were %d errors.", errors) % errors)
361         sys.exit (1)
362
363
364 main ()