]> git.donarmstrong.com Git - lilypond.git/blob - scripts/convert-ly.py
* scripts/convert-ly.py (bindir): use optparse, argv[0] relocation.
[lilypond.git] / scripts / convert-ly.py
1 #!@PYTHON@
2 #
3 # convert-ly.py -- Update old LilyPond input files (fix name?)
4 #
5 # source file of the GNU LilyPond music typesetter
6 #
7 # (c) 1998--2006  Han-Wen Nienhuys <hanwen@cs.uu.nl>
8 #                 Jan Nieuwenhuizen <janneke@gnu.org>
9 #
10 # converting rules are found in python/convertrules.py
11 #
12
13 import os
14 import sys
15 import __main__
16 import getopt
17 import string
18 import re
19
20
21 datadir = '@local_lilypond_datadir@'
22 if not os.path.isdir (datadir):
23         datadir = '@lilypond_datadir@'
24
25 sys.path.insert (0, os.path.join (datadir, 'python'))
26
27 if os.environ.has_key ('LILYPONDPREFIX'):
28         datadir = os.environ['LILYPONDPREFIX']
29         while datadir[-1] == os.sep:
30                 datadir= datadir[:-1]
31                 
32         datadir = os.path.join (datadir, "share/lilypond/current/")
33 sys.path.insert (0, os.path.join (datadir, 'python'))
34
35 # dynamic relocation, for GUB binaries.
36 bindir = os.path.split (sys.argv[0])[0]
37 for p in ['share', 'lib']:
38         datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
39         sys.path.insert (0, os.path.join (datadir))
40
41 import lilylib as ly
42 import fontextract
43 global _;_=ly._
44
45 from convertrules import *
46
47 lilypond_version_re_str = '\\\\version *\"([0-9.]+)"'
48 lilypond_version_re = re.compile (lilypond_version_re_str)
49
50
51 help_summary = _ (
52 '''Update LilyPond input to newer version.  By default, update from the
53 version taken from the \\version command, to the current LilyPond version.
54
55 Examples:
56
57   convert-ly -e old.ly
58   convert-ly --from=2.3.28 --to 2.5.21 foobar.ly
59 ''')
60
61 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
62              'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
63
64 program_name = os.path.basename (sys.argv[0])
65 program_version = '@TOPLEVEL_VERSION@'
66
67 add_version = 1
68
69
70 def get_option_parser ():
71         p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
72                                   version="@TOPLEVEL_VERSION@",
73                                   description=help_summary)
74
75         p.add_option ('-f', '--from', 
76                       action="store",
77                       metavar=_ ("VERSION"),
78                       dest="from_version",
79                       help=_('start from VERSION [default: \\version found in file]'),
80                       default='')
81         
82         p.add_option ('-e', '--edit', help=_('edit in place'),
83                       action='store_true')
84         p.add_option ('-n', '--no-version',
85                       help=_ ('do not add \\version command if missing'),
86                       action='store_true',
87                       dest='skip_version_add',
88                       default=False)
89         
90         p.add_option ("-s", '--show-rules',
91                       help=_('print rules [default: --from=0, --to=@TOPLEVEL_VERSION@]'),
92                       action='store_true', default=False)
93         
94         p.add_option ('-t', '--to',
95                       help=_('convert to VERSION [default: @TOPLEVEL_VERSION@]'),
96                       metavar=_('VERSION'),
97                       action='store',
98                       dest="to_version",
99                       default='')
100
101         p.add_option_group  ('bugs',
102                              description='''Report bugs via http://post.gmane.org/post.php'''
103                              '''?group=gmane.comp.gnu.lilypond.bugs\n''')
104         
105         return p
106
107
108
109 def str_to_tuple (s):
110         return tuple (map (string.atoi, string.split (s, '.')))
111
112 def tup_to_str (t):
113         return string.join (map (lambda x: '%s' % x, list (t)), '.')
114
115 def version_cmp (t1, t2):
116         for x in [0, 1, 2]:
117                 if t1[x] - t2[x]:
118                         return t1[x] - t2[x]
119         return 0
120
121 def get_conversions (from_version, to_version):
122         def is_applicable (v, f = from_version, t = to_version):
123                 return version_cmp (v[0], f) > 0 and version_cmp (v[0], t) <= 0
124         return filter (is_applicable, conversions)
125
126 def latest_version ():
127         return conversions[-1][0]
128
129 def show_rules (file, from_version, to_version):
130         for x in conversions:
131                 if (not from_version or x[0] > from_version) \
132                    and (not to_version or x[0] <= to_version):
133                         file.write  ('%s: %s\n' % (tup_to_str (x[0]), x[2]))
134
135 def do_conversion (str, from_version, to_version):
136         """Apply conversions from FROM_VERSION to TO_VERSION.  Return
137 tuple (LAST,STR), with the last succesful conversion and the resulting
138 string."""
139         conv_list = get_conversions (from_version, to_version)
140
141         if error_file:
142                 error_file.write (_ ("Applying conversion: "))
143                 
144         last_conversion = ()
145         try:
146                 for x in conv_list:
147                         error_file.write (tup_to_str (x[0]))
148                         if x != conv_list[-1]:
149                                 error_file.write (', ')
150                         str = x[1] (str)
151                         last_conversion = x[0]
152
153         except FatalConversionError:
154                 error_file.write (_ ("error while converting")) 
155                 error_file.write ('\n')
156                 error_file.write (_ ("Aborting"))
157                 error_file.write ('\n')
158
159
160
161         return (last_conversion, str)
162
163
164
165 def guess_lilypond_version (filename):
166         s = open (filename).read ()
167         m = lilypond_version_re.search (s)
168         if m:
169                 return m.group (1)
170         else:
171                 return ''
172
173 class FatalConversionError:
174         pass
175
176 class UnknownVersion:
177         pass
178
179 def do_one_file (infile_name):
180         sys.stderr.write (_ ("Processing `%s\'... ") % infile_name)
181         sys.stderr.write ('\n')
182         outfile_name = ''
183         if global_options.edit:
184                 outfile_name = infile_name + '.NEW'
185         elif global_options.outfile_name:
186                 outfile_name = global_options.outfile_name
187
188         if global_options.from_version:
189                 from_version = global_options.from_version
190         else:
191                 guess = guess_lilypond_version (infile_name)
192                 if not guess:
193                         raise UnknownVersion ()
194                 from_version = str_to_tuple (guess)
195
196         if global_options.to_version:
197                 to_version = global_options.to_version
198         else:
199                 to_version = latest_version ()
200
201
202         if infile_name:
203                 infile = open (infile_name, 'r')
204         else:
205                 infile = sys.stdin
206
207
208         (last, result) = do_conversion (infile.read (), from_version, to_version)
209         infile.close ()
210
211         if last:
212                 newversion = r'\version "%s"' % tup_to_str (last)
213                 if lilypond_version_re.search (result):
214                         result = re.sub (lilypond_version_re_str,
215                                          '\\' + newversion, result)
216                 elif add_version:
217                         result = newversion + '\n' + result
218                         
219                 error_file.write ('\n')                 
220         
221                 if global_options.edit:
222                         try:
223                                 os.remove(infile_name + '~')
224                         except:
225                                 pass
226                         os.rename (infile_name, infile_name + '~')
227                         outfile = open (infile_name, 'w')
228                 else:
229                         outfile = sys.stdout
230
231
232                 outfile.write (result)
233
234         sys.stderr.flush ()
235
236 def do_options ():
237         opt_parser = get_option_parser()
238         (options, args) = opt_parser.parse_args ()
239
240
241         if options.from_version:
242                 options.from_version = str_to_tuple (options.from_version)
243         if options.to_version:
244                 options.to_version = str_to_tuple (options.to_version)
245
246         options.outfile_name = ''
247         global global_options
248         global_options = options
249
250         if not args:
251                 opt_parser.print_help ()
252                 sys.exit (2)
253
254         return args
255
256 def main ():
257         files = do_options ()
258
259         # should parse files[] to read \version?
260         if global_options.show_rules:
261                 show_rules (sys.stdout, from_version, to_version)
262                 sys.exit (0)
263
264         ly.identify (sys.stderr)
265
266         for f in files:
267                 if f == '-':
268                         f = ''
269                 elif not os.path.isfile (f):
270                         ly.error (_ ("can't open file: `%s'") % f)
271                         if len (files) == 1:
272                                 sys.exit (1)
273                         continue
274                 try:
275                         do_one_file (f)
276                 except UnknownVersion:
277                         ly.error (_ ("can't determine version for `%s'. Skipping") % f)
278
279         sys.stderr.write ('\n')
280
281 main ()