3 # convert-ly.py -- Update old LilyPond input files (fix name?)
4 # converting rules are found in python/convertrules.py
6 # This file is part of LilyPond, the GNU music typesetter.
8 # Copyright (C) 1998--2012 Han-Wen Nienhuys <hanwen@xs4all.nl>
9 # Jan Nieuwenhuizen <janneke@gnu.org>
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.
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.
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/>.
35 ly.require_python_version ()
39 lilypond_version_re_str = '\\\\version *\"([0-9.]+)"'
40 lilypond_version_re = re.compile (lilypond_version_re_str)
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)
46 _ ('''Update LilyPond input to newer version. By default, update from the
47 version taken from the \\version command, to the current LilyPond version.''')
49 + _ ("If FILE is `-', read from standard input.")
53 $ convert-ly -e old.ly
54 $ convert-ly --from=2.3.28 --to=2.5.21 foobar.ly > foobar-new.ly
57 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
58 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
60 program_name = os.path.basename (sys.argv[0])
61 program_version = '@TOPLEVEL_VERSION@'
63 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
64 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
67 ly.progress ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
71 ly.encoded_write (sys.stdout, '''
78 ''' % ( _ ('Copyright (c) %s by') % '2001--2012',
80 _ ('Distributed under terms of the GNU General Public License.'),
81 _ ('It comes with NO WARRANTY.')))
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)
88 p.version="@TOPLEVEL_VERSION@"
89 p.add_option("--version",
91 help=_ ("show version number and exit"))
93 p.add_option("-h", "--help",
95 help=_ ("show this help and exit"))
97 p.add_option ('-f', '--from',
99 metavar=_ ("VERSION"),
101 help=_ ("start from VERSION [default: \\version found in file]"),
104 p.add_option ('-e', '--edit', help=_ ("edit in place"),
107 p.add_option ("-l", "--loglevel",
108 help=_ ("Print log messages according to LOGLEVEL "
109 "(NONE, ERROR, WARNING, PROGRESS (default), DEBUG)"),
110 metavar=_ ("LOGLEVEL"),
112 callback=ly.handle_loglevel_option,
115 p.add_option ('-n', '--no-version',
116 help=_ ("do not add \\version command if missing"),
118 dest='skip_version_add',
121 p.add_option ('-c', '--current-version',
122 help=_ ("force updating \\version number to %s") % program_version,
124 dest='force_current_version',
127 p.add_option ('-d', '--diff-version-update',
128 help=_ ("only update \\version number if file is modified"),
130 dest='diff_version_update',
133 p.add_option ("-s", '--show-rules',
134 help=_ ("show rules [default: -f 0, -t %s]") % program_version,
136 action='store_true', default=False)
138 p.add_option ('-t', '--to',
139 help=_ ("convert to VERSION [default: %s]") % program_version,
140 metavar=_ ('VERSION'),
144 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
147 p.add_option_group ('',
149 _ ("Report bugs via %s")
150 % 'http://post.gmane.org/post.php'
151 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
157 def str_to_tuple (s):
158 return tuple ([int(n) for n in s.split ('.')])
161 return '.'.join (['%s' % x for x in t])
163 def version_cmp (t1, t2):
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)
174 def latest_version ():
175 return convertrules.conversions[-1][0]
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]))
183 def do_conversion (str, from_version, to_version):
184 """Apply conversions from FROM_VERSION to TO_VERSION. Return
185 tuple (LAST,STR), with the last successful conversion and the resulting
187 conv_list = get_conversions (from_version, to_version)
189 ly.progress (_ ("Applying conversion: "), newline = False)
191 last_conversion = None
195 if x != conv_list[-1]:
196 ly.progress (tup_to_str (x[0]), newline = False)
197 ly.progress (', ', newline = False)
199 ly.progress (tup_to_str (x[0]))
201 last_conversion = x[0]
203 except convertrules.FatalConversionError:
204 ly.error (_ ("Error while converting")
206 + _ ("Stopping at last successful rule"))
209 return (last_conversion, str, errors)
213 def guess_lilypond_version (input):
214 m = lilypond_version_strict_re.search (input)
217 m = lilypond_version_re.search (input)
219 raise InvalidVersion (m.group (1))
223 class FatalConversionError (Exception):
226 class UnknownVersion (Exception):
229 class InvalidVersion (Exception):
230 def __init__ (self, version):
231 self.version = version
233 def do_one_file (infile_name):
234 ly.progress (_ (u"Processing `%s\'... ") % infile_name, True)
237 infile = open (infile_name, 'r')
238 input = infile.read ()
241 input = sys.stdin.read ()
245 if global_options.from_version:
246 from_version = global_options.from_version
248 guess = guess_lilypond_version (input)
250 raise UnknownVersion ()
251 from_version = str_to_tuple (guess)
253 if global_options.to_version:
254 to_version = global_options.to_version
256 to_version = latest_version ()
258 if len (from_version) != 3:
259 raise InvalidVersion (".".join ([str(n) for n in from_version]))
262 (last, result, errors) = do_conversion (input, from_version, to_version)
264 if global_options.force_current_version and \
265 (last is None or last == to_version):
266 last = str_to_tuple (program_version)
268 if global_options.diff_version_update:
270 # check the y in x.y.z (minor version number)
271 previous_stable = (last[0], 2*(last[1]/2), 0)
272 if ((last[0:2] != from_version[0:2]) and
273 (previous_stable > from_version)):
274 # previous stable version
275 last = previous_stable
277 # make no (actual) change to the version number
280 newversion = r'\version "%s"' % tup_to_str (last)
281 if lilypond_version_re.search (result):
282 result = re.sub (lilypond_version_re_str,
283 '\\' + newversion, result)
284 elif not global_options.skip_version_add:
285 result = newversion + '\n' + result
289 if global_options.edit:
291 os.remove (infile_name + '~')
294 os.rename (infile_name, infile_name + '~')
295 outfile = open (infile_name, 'w')
299 outfile.write (result)
306 opt_parser = get_option_parser()
307 (options, args) = opt_parser.parse_args ()
313 if options.from_version:
314 options.from_version = str_to_tuple (options.from_version)
315 if options.to_version:
316 options.to_version = str_to_tuple (options.to_version)
318 options.outfile_name = ''
319 global global_options
320 global_options = options
322 if not args and not options.show_rules:
323 opt_parser.print_help ()
329 files = do_options ()
331 # should parse files[] to read \version?
332 if global_options.show_rules:
333 show_rules (sys.stdout, global_options.from_version, global_options.to_version)
340 f = f.decode (sys.stdin.encoding or "utf-8")
343 elif not os.path.isfile (f):
344 ly.error (_ (u"%s: Unable to open file") % f)
348 errors += do_one_file (f)
349 except UnknownVersion:
350 ly.error (_ (u"%s: Unable to determine version. Skipping") % f)
352 except InvalidVersion:
353 # Compat code for 2.x and 3.0 syntax ("except .. as v" doesn't
354 # work in python 2.4!):
355 t, v, b = sys.exc_info ()
356 ly.error (_ (u"%s: Invalid version string `%s' \n"
357 "Valid version strings consist of three numbers, "
358 "separated by dots, e.g. `2.8.12'") % (f, v.version) )
362 ly.warning (ly.ungettext ("There was %d error.",
363 "There were %d errors.", errors) % errors)