Nitpick: ly:spanner-bound grob name slur -> spanner.
[lilypond.git] / scripts / convert-ly.py
blobcffd859ff72ef74900f01579fb3efdbc6bc6c66a
1 #!@TARGET_PYTHON@
3 # convert-ly.py -- Update old LilyPond input files (fix name?)
5 # source file of the GNU LilyPond music typesetter
7 # (c) 1998--2009 Han-Wen Nienhuys <hanwen@xs4all.nl>
8 # Jan Nieuwenhuizen <janneke@gnu.org>
10 # converting rules are found in python/convertrules.py
13 import os
14 import sys
15 import re
17 """
18 @relocate-preamble@
19 """
21 import lilylib as ly
22 global _;_=ly._
24 ly.require_python_version ()
26 import convertrules
28 lilypond_version_re_str = '\\\\version *\"([0-9.]+)"'
29 lilypond_version_re = re.compile (lilypond_version_re_str)
32 help_summary = (
33 _ ('''Update LilyPond input to newer version. By default, update from the
34 version taken from the \\version command, to the current LilyPond version.''')
35 + _ ("Examples:")
36 + '''
37 $ convert-ly -e old.ly
38 $ convert-ly --from=2.3.28 --to=2.5.21 foobar.ly > foobar-new.ly
39 ''')
41 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
42 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
44 program_name = os.path.basename (sys.argv[0])
45 program_version = '@TOPLEVEL_VERSION@'
47 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
48 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
50 error_file_write = ly.stderr_write
52 def warning (s):
53 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
55 def error (s):
56 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
58 def identify (port=sys.stderr):
59 ly.encoded_write (port, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
61 def warranty ():
62 identify ()
63 ly.encoded_write (sys.stdout, '''
70 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
71 ' '.join (authors),
72 _ ('Distributed under terms of the GNU General Public License.'),
73 _ ('It comes with NO WARRANTY.')))
75 def get_option_parser ():
76 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'convert-ly',
77 description=help_summary,
78 add_help_option=False)
80 p.version="@TOPLEVEL_VERSION@"
81 p.add_option("--version",
82 action="version",
83 help=_ ("show version number and exit"))
85 p.add_option("-h", "--help",
86 action="help",
87 help=_ ("show this help and exit"))
89 p.add_option ('-f', '--from',
90 action="store",
91 metavar=_ ("VERSION"),
92 dest="from_version",
93 help=_ ("start from VERSION [default: \\version found in file]"),
94 default='')
96 p.add_option ('-e', '--edit', help=_ ("edit in place"),
97 action='store_true')
99 p.add_option ('-n', '--no-version',
100 help=_ ("do not add \\version command if missing"),
101 action='store_true',
102 dest='skip_version_add',
103 default=False)
105 p.add_option ('-c', '--current-version',
106 help=_ ("force updating \\version number to %s") % program_version,
107 action='store_true',
108 dest='force_current_version',
109 default=False)
111 p.add_option ("-s", '--show-rules',
112 help=_ ("show rules [default: -f 0, -t %s]") % program_version,
113 dest='show_rules',
114 action='store_true', default=False)
116 p.add_option ('-t', '--to',
117 help=_ ("convert to VERSION [default: %s]") % program_version,
118 metavar=_ ('VERSION'),
119 action='store',
120 dest="to_version",
121 default='')
122 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
123 action='store_true',
125 p.add_option_group ('',
126 description=(
127 _ ("Report bugs via %s")
128 % 'http://post.gmane.org/post.php'
129 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
131 return p
135 def str_to_tuple (s):
136 return tuple ([int(n) for n in s.split ('.')])
138 def tup_to_str (t):
139 return '.'.join (['%s' % x for x in t])
141 def version_cmp (t1, t2):
142 for x in [0, 1, 2]:
143 if t1[x] - t2[x]:
144 return t1[x] - t2[x]
145 return 0
147 def get_conversions (from_version, to_version):
148 def is_applicable (v, f = from_version, t = to_version):
149 return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
150 return filter (is_applicable, convertrules.conversions)
152 def latest_version ():
153 return convertrules.conversions[-1][0]
155 def show_rules (file, from_version, to_version):
156 for x in convertrules.conversions:
157 if (not from_version or x[0] > from_version) \
158 and (not to_version or x[0] <= to_version):
159 ly.encoded_write (file, '%s: %s\n' % (tup_to_str (x[0]), x[2]))
161 def do_conversion (str, from_version, to_version):
162 """Apply conversions from FROM_VERSION to TO_VERSION. Return
163 tuple (LAST,STR), with the last succesful conversion and the resulting
164 string."""
165 conv_list = get_conversions (from_version, to_version)
167 error_file_write (_ ("Applying conversion: "))
169 last_conversion = ()
170 try:
171 for x in conv_list:
172 error_file_write (tup_to_str (x[0]))
173 if x != conv_list[-1]:
174 error_file_write (', ')
175 str = x[1] (str)
176 last_conversion = x[0]
178 except convertrules.FatalConversionError:
179 error_file_write ('\n'
180 + _ ("Error while converting")
181 + '\n'
182 + _ ("Stopping at last successful rule")
183 + '\n')
185 return (last_conversion, str)
189 def guess_lilypond_version (input):
190 m = lilypond_version_re.search (input)
191 if m:
192 return m.group (1)
193 else:
194 return ''
196 class FatalConversionError:
197 pass
199 class UnknownVersion:
200 pass
202 def do_one_file (infile_name):
203 ly.stderr_write (_ ("Processing `%s\'... ") % infile_name)
204 sys.stderr.write ('\n')
206 if infile_name:
207 infile = open (infile_name, 'r')
208 input = infile.read ()
209 infile.close ()
210 else:
211 input = sys.stdin.read ()
213 from_version = None
214 to_version = None
215 if global_options.from_version:
216 from_version = global_options.from_version
217 else:
218 guess = guess_lilypond_version (input)
219 if not guess:
220 raise UnknownVersion ()
221 from_version = str_to_tuple (guess)
223 if global_options.to_version:
224 to_version = global_options.to_version
225 else:
226 to_version = latest_version ()
229 (last, result) = do_conversion (input, from_version, to_version)
231 if last:
232 if global_options.force_current_version and last == to_version:
233 last = str_to_tuple (program_version)
235 newversion = r'\version "%s"' % tup_to_str (last)
236 if lilypond_version_re.search (result):
237 result = re.sub (lilypond_version_re_str,
238 '\\' + newversion, result)
239 elif not global_options.skip_version_add:
240 result = newversion + '\n' + result
242 error_file_write ('\n')
244 if global_options.edit:
245 try:
246 os.remove(infile_name + '~')
247 except:
248 pass
249 os.rename (infile_name, infile_name + '~')
250 outfile = open (infile_name, 'w')
251 else:
252 outfile = sys.stdout
255 outfile.write (result)
257 sys.stderr.flush ()
259 def do_options ():
260 opt_parser = get_option_parser()
261 (options, args) = opt_parser.parse_args ()
263 if options.warranty:
264 warranty ()
265 sys.exit (0)
267 if options.from_version:
268 options.from_version = str_to_tuple (options.from_version)
269 if options.to_version:
270 options.to_version = str_to_tuple (options.to_version)
272 options.outfile_name = ''
273 global global_options
274 global_options = options
276 if not args and not options.show_rules:
277 opt_parser.print_help ()
278 sys.exit (2)
280 return args
282 def main ():
283 files = do_options ()
285 # should parse files[] to read \version?
286 if global_options.show_rules:
287 show_rules (sys.stdout, global_options.from_version, global_options.to_version)
288 sys.exit (0)
290 identify (sys.stderr)
292 for f in files:
293 if f == '-':
294 f = ''
295 elif not os.path.isfile (f):
296 error (_ ("cannot open file: `%s'") % f)
297 if len (files) == 1:
298 sys.exit (1)
299 continue
300 try:
301 do_one_file (f)
302 except UnknownVersion:
303 error (_ ("cannot determine version for `%s'. Skipping") % f)
305 sys.stderr.write ('\n')
307 main ()