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--2011 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)
44 _ ('''Update LilyPond input to newer version. By default, update from the
45 version taken from the \\version command, to the current LilyPond version.''')
48 $ convert-ly -e old.ly
49 $ convert-ly --from=2.3.28 --to=2.5.21 foobar.ly > foobar-new.ly
52 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
53 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
55 program_name = os.path.basename (sys.argv[0])
56 program_version = '@TOPLEVEL_VERSION@'
58 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
59 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
61 error_file_write = ly.stderr_write
64 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
67 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
69 def identify (port=sys.stderr):
70 ly.encoded_write (port, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
74 ly.encoded_write (sys.stdout, '''
81 ''' % ( _ ('Copyright (c) %s by') % '2001--2011',
83 _ ('Distributed under terms of the GNU General Public License.'),
84 _ ('It comes with NO WARRANTY.')))
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)
91 p.version="@TOPLEVEL_VERSION@"
92 p.add_option("--version",
94 help=_ ("show version number and exit"))
96 p.add_option("-h", "--help",
98 help=_ ("show this help and exit"))
100 p.add_option ('-f', '--from',
102 metavar=_ ("VERSION"),
104 help=_ ("start from VERSION [default: \\version found in file]"),
107 p.add_option ('-e', '--edit', help=_ ("edit in place"),
110 p.add_option ('-n', '--no-version',
111 help=_ ("do not add \\version command if missing"),
113 dest='skip_version_add',
116 p.add_option ('-c', '--current-version',
117 help=_ ("force updating \\version number to %s") % program_version,
119 dest='force_current_version',
122 p.add_option ('-d', '--diff-version-update',
123 help=_ ("only update \\version number if file is modified"),
125 dest='diff_version_update',
128 p.add_option ("-s", '--show-rules',
129 help=_ ("show rules [default: -f 0, -t %s]") % program_version,
131 action='store_true', default=False)
133 p.add_option ('-t', '--to',
134 help=_ ("convert to VERSION [default: %s]") % program_version,
135 metavar=_ ('VERSION'),
139 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
142 p.add_option_group ('',
144 _ ("Report bugs via %s")
145 % 'http://post.gmane.org/post.php'
146 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
152 def str_to_tuple (s):
153 return tuple ([int(n) for n in s.split ('.')])
156 return '.'.join (['%s' % x for x in t])
158 def version_cmp (t1, t2):
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)
169 def latest_version ():
170 return convertrules.conversions[-1][0]
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]))
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
182 conv_list = get_conversions (from_version, to_version)
184 error_file_write (_ ("Applying conversion: "))
189 last_conversion = to_version
191 error_file_write (tup_to_str (x[0]))
192 if x != conv_list[-1]:
193 error_file_write (', ')
195 last_conversion = x[0]
197 except convertrules.FatalConversionError:
198 error_file_write ('\n'
199 + _ ("Error while converting")
201 + _ ("Stopping at last successful rule")
204 return (last_conversion, str)
208 def guess_lilypond_version (input):
209 m = lilypond_version_re.search (input)
215 class FatalConversionError (Exception):
218 class UnknownVersion (Exception):
221 class InvalidVersion (Exception):
222 def __init__ (self, version):
223 self.version = version
225 def do_one_file (infile_name):
226 ly.stderr_write (_ ("Processing `%s\'... ") % infile_name)
227 sys.stderr.write ('\n')
230 infile = open (infile_name, 'r')
231 input = infile.read ()
234 input = sys.stdin.read ()
238 if global_options.from_version:
239 from_version = global_options.from_version
241 guess = guess_lilypond_version (input)
243 raise UnknownVersion ()
244 from_version = str_to_tuple (guess)
246 if global_options.to_version:
247 to_version = global_options.to_version
249 to_version = latest_version ()
251 if len (from_version) != 3:
252 raise InvalidVersion (".".join ([str(n) for n in from_version]))
255 (last, result) = do_conversion (input, from_version, to_version)
258 if global_options.force_current_version and last == to_version:
259 last = str_to_tuple (program_version)
261 if global_options.diff_version_update:
263 # check the y in x.y.z (minor version number)
264 previous_stable = (last[0], 2*(last[1]/2), 0)
265 if ((last[0:2] != from_version[0:2]) and
266 (previous_stable > from_version)):
267 # previous stable version
268 last = previous_stable
270 # make no (actual) change to the version number
273 newversion = r'\version "%s"' % tup_to_str (last)
274 if lilypond_version_re.search (result):
275 result = re.sub (lilypond_version_re_str,
276 '\\' + newversion, result)
277 elif not global_options.skip_version_add:
278 result = newversion + '\n' + result
280 error_file_write ('\n')
282 if global_options.edit:
284 os.remove(infile_name + '~')
287 os.rename (infile_name, infile_name + '~')
288 outfile = open (infile_name, 'w')
293 outfile.write (result)
298 opt_parser = get_option_parser()
299 (options, args) = opt_parser.parse_args ()
305 if options.from_version:
306 options.from_version = str_to_tuple (options.from_version)
307 if options.to_version:
308 options.to_version = str_to_tuple (options.to_version)
310 options.outfile_name = ''
311 global global_options
312 global_options = options
314 if not args and not options.show_rules:
315 opt_parser.print_help ()
321 files = do_options ()
323 # should parse files[] to read \version?
324 if global_options.show_rules:
325 show_rules (sys.stdout, global_options.from_version, global_options.to_version)
328 identify (sys.stderr)
333 elif not os.path.isfile (f):
334 error (_ ("%s: Unable to open file") % f)
340 except UnknownVersion:
341 error (_ ("%s: Unable to determine version. Skipping") % f)
342 except InvalidVersion:
343 # Compat code for 2.x and 3.0 syntax ("except .. as v" doesn't
344 # work in python 2.4!):
345 t, v, b = sys.exc_info ()
346 error (_ ("%s: Invalid version string `%s' \n"
347 "Valid version strings consist of three numbers, "
348 "separated by dots, e.g. `2.8.12'") % (f, v.version) )
350 sys.stderr.write ('\n')