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