Fix typo in convert-ly.
[lilypond.git] / scripts / convert-ly.py
blobea9804184f5001ce5bb7590cb357e77a55039a43
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--2007 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 error_file_write = ly.stderr_write
49 def warning (s):
50 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
52 def error (s):
53 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
55 def identify (port=sys.stderr):
56 ly.encoded_write (port, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
58 def warranty ():
59 identify ()
60 ly.encoded_write (sys.stdout, '''
61 Copyright (c) %s by
63 Han-Wen Nienhuys
64 Jan Nieuwenhuizen
68 ''' ( '2001--2006',
69 _ ("Distributed under terms of the GNU General Public License."),
70 _ ('It comes with NO WARRANTY.')))
73 def get_option_parser ():
74 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'convert-ly',
75 description=help_summary,
76 add_help_option=False)
78 p.version="@TOPLEVEL_VERSION@"
79 p.add_option("--version",
80 action="version",
81 help=_ ("show version number and exit"))
83 p.add_option("-h", "--help",
84 action="help",
85 help=_ ("show this help and exit"))
87 p.add_option ('-f', '--from',
88 action="store",
89 metavar=_ ("VERSION"),
90 dest="from_version",
91 help=_ ("start from VERSION [default: \\version found in file]"),
92 default='')
94 p.add_option ('-e', '--edit', help=_ ("edit in place"),
95 action='store_true')
97 p.add_option ('-n', '--no-version',
98 help=_ ("do not add \\version command if missing"),
99 action='store_true',
100 dest='skip_version_add',
101 default=False)
103 p.add_option ('-c', '--current-version',
104 help=_ ("force updating \\version number to %s") % program_version,
105 action='store_true',
106 dest='force_current_version',
107 default=False)
109 p.add_option ("-s", '--show-rules',
110 help=_ ("show rules [default: -f 0, -t %s]") % program_version,
111 dest='show_rules',
112 action='store_true', default=False)
114 p.add_option ('-t', '--to',
115 help=_ ("convert to VERSION [default: %s]") % program_version,
116 metavar=_ ('VERSION'),
117 action='store',
118 dest="to_version",
119 default='')
121 p.add_option_group ('',
122 description=(_ ("Report bugs via")
123 + ''' http://post.gmane.org/post.php'''
124 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
126 return p
130 def str_to_tuple (s):
131 return tuple ([int(n) for n in s.split ('.')])
133 def tup_to_str (t):
134 return '.'.join (['%s' % x for x in t])
136 def version_cmp (t1, t2):
137 for x in [0, 1, 2]:
138 if t1[x] - t2[x]:
139 return t1[x] - t2[x]
140 return 0
142 def get_conversions (from_version, to_version):
143 def is_applicable (v, f = from_version, t = to_version):
144 return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
145 return filter (is_applicable, convertrules.conversions)
147 def latest_version ():
148 return convertrules.conversions[-1][0]
150 def show_rules (file, from_version, to_version):
151 for x in convertrules.conversions:
152 if (not from_version or x[0] > from_version) \
153 and (not to_version or x[0] <= to_version):
154 ly.encoded_write (file, '%s: %s\n' % (tup_to_str (x[0]), x[2]))
156 def do_conversion (str, from_version, to_version):
157 """Apply conversions from FROM_VERSION to TO_VERSION. Return
158 tuple (LAST,STR), with the last succesful conversion and the resulting
159 string."""
160 conv_list = get_conversions (from_version, to_version)
162 error_file_write (_ ("Applying conversion: "))
164 last_conversion = ()
165 try:
166 for x in conv_list:
167 error_file_write (tup_to_str (x[0]))
168 if x != conv_list[-1]:
169 error_file_write (', ')
170 str = x[1] (str)
171 last_conversion = x[0]
173 except convertrules.FatalConversionError:
174 error_file_write ('\n'
175 + _ ("Error while converting")
176 + '\n'
177 + _ ("Stopping at last successful rule")
178 + '\n')
180 return (last_conversion, str)
184 def guess_lilypond_version (input):
185 m = lilypond_version_re.search (input)
186 if m:
187 return m.group (1)
188 else:
189 return ''
191 class FatalConversionError:
192 pass
194 class UnknownVersion:
195 pass
197 def do_one_file (infile_name):
198 ly.stderr_write (_ ("Processing `%s\'... ") % infile_name)
199 sys.stderr.write ('\n')
201 if infile_name:
202 infile = open (infile_name, 'r')
203 input = infile.read ()
204 infile.close ()
205 else:
206 input = sys.stdin.read ()
208 from_version = None
209 to_version = None
210 if global_options.from_version:
211 from_version = global_options.from_version
212 else:
213 guess = guess_lilypond_version (input)
214 if not guess:
215 raise UnknownVersion ()
216 from_version = str_to_tuple (guess)
218 if global_options.to_version:
219 to_version = global_options.to_version
220 else:
221 to_version = latest_version ()
224 (last, result) = do_conversion (input, from_version, to_version)
226 if last:
227 if global_options.force_current_version and last == to_version:
228 last = str_to_tuple (program_version)
230 newversion = r'\version "%s"' % tup_to_str (last)
231 if lilypond_version_re.search (result):
232 result = re.sub (lilypond_version_re_str,
233 '\\' + newversion, result)
234 elif not global_options.skip_version_add:
235 result = newversion + '\n' + result
237 error_file_write ('\n')
239 if global_options.edit:
240 try:
241 os.remove(infile_name + '~')
242 except:
243 pass
244 os.rename (infile_name, infile_name + '~')
245 outfile = open (infile_name, 'w')
246 else:
247 outfile = sys.stdout
250 outfile.write (result)
252 sys.stderr.flush ()
254 def do_options ():
255 opt_parser = get_option_parser()
256 (options, args) = opt_parser.parse_args ()
259 if options.from_version:
260 options.from_version = str_to_tuple (options.from_version)
261 if options.to_version:
262 options.to_version = str_to_tuple (options.to_version)
264 options.outfile_name = ''
265 global global_options
266 global_options = options
268 if not args and not options.show_rules:
269 opt_parser.print_help ()
270 sys.exit (2)
272 return args
274 def main ():
275 files = do_options ()
277 # should parse files[] to read \version?
278 if global_options.show_rules:
279 show_rules (sys.stdout, global_options.from_version, global_options.to_version)
280 sys.exit (0)
282 identify (sys.stderr)
284 for f in files:
285 if f == '-':
286 f = ''
287 elif not os.path.isfile (f):
288 error (_ ("cannot open file: `%s'") % f)
289 if len (files) == 1:
290 sys.exit (1)
291 continue
292 try:
293 do_one_file (f)
294 except UnknownVersion:
295 error (_ ("cannot determine version for `%s'. Skipping") % f)
297 sys.stderr.write ('\n')
299 main ()