]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/makelsr.py
Get texidoc translations out of snippets source files
[lilypond.git] / scripts / auxiliar / makelsr.py
1 #!/usr/bin/env python
2
3 import sys
4 import os
5 import glob
6 import re
7 import optparse
8 import tempfile
9
10 lilypond_flags = "-dno-print-pages -dsafe"
11
12 lys_from_lsr = os.path.join ('Documentation', 'snippets')
13 new_lys = os.path.join ('Documentation', 'snippets', 'new')
14 ly_output = os.path.join (tempfile.gettempdir (), 'lsrtest')
15
16 # which convert-ly and lilypond to use
17 P = os.path.join (os.environ.get ("LILYPOND_BUILD_DIR", ""),
18                   "out/bin/convert-ly")
19 if os.path.isfile (P):
20     conv_path = os.path.dirname (P)
21 elif os.path.isfile ("build/out/bin/convert-ly"):
22     conv_path = "build/out/bin/"
23 else:
24     conv_path=''
25 convert_ly = os.path.join (conv_path, 'convert-ly')
26 lilypond_bin = os.path.join (conv_path, 'lilypond')
27
28
29
30 LY_HEADER_LSR = '''%% DO NOT EDIT this file manually; it is automatically
31 %% generated from LSR http://lsr.dsi.unimi.it
32 %% Make any changes in LSR itself, or in Documentation/snippets/new/ ,
33 %% and then run scripts/auxiliar/makelsr.py
34 %%
35 %% This file is in the public domain.
36 '''
37
38 LY_HEADER_NEW = '''%% DO NOT EDIT this file manually; it is automatically
39 %% generated from %s
40 %% Make any changes in Documentation/snippets/new/
41 %% and then run scripts/auxiliar/makelsr.py
42 %%
43 %% This file is in the public domain.
44 ''' % new_lys
45
46 options_parser = optparse.OptionParser (
47     description = "makelsr - update snippets directory from LSR",
48     usage = '''%%prog [options] [LSR_SNIPPETS_DIR]
49 Unless -s option is specified, this script must be run from top of the
50 source tree. If LSR_SNIPPETS_DIR is not specified, it defaults to
51 current directory.
52
53 Remove snippets in TOP_SOURCE_DIR/%(lys_from_lsr)s and put in snippets
54 from LSR_SNIPPETS_DIR run through convert-ly or from
55 TOP_SOURCE_DIR/%(new_lys)s; if a snippet is present in both
56 directories, the one from TOP_SOURCE_DIR/%(new_lys)s is preferred.
57 All written snippets are copied in LY_OUTPUT
58 with appending translations from .texidoc files and are tested with
59 lilypond with flags %(lilypond_flags)s
60
61 ''' % vars ())
62
63 options_parser.add_option ('-s', '--top-source',
64                            dest="top_source_dir",
65                            action="store",
66                            metavar="TOP_SOURCE_DIR",
67                            default=".",
68                            help="set LilyPond top source directory")
69
70 options_parser.add_option ('-o', '--ly-output',
71                            dest="ly_output",
72                            action="store",
73                            metavar="LY_OUTPUT",
74                            default=ly_output,
75                            help="set LilyPond output files temporary directory")
76
77 options_parser.add_option ('-p', '--path',
78                            dest="bin_path",
79                            action="store",
80                            metavar="LY_PATH",
81                            default=conv_path,
82                            help="directory where looking for LilyPond binaries")
83
84 options_parser.add_option ('-c', '--convert-ly',
85                            dest="convert_ly",
86                            action="store",
87                            metavar="CONVERT-LY",
88                            default="LY_PATH/convert-ly",
89                            help="convert-ly binary to use")
90
91 options_parser.add_option ('-l', '--lilypond-binary',
92                            dest="lilypond_bin",
93                            action="store",
94                            metavar="LILYPOND_BIN",
95                            default="LY_PATH/lilypond",
96                            help="lilypond binary to use")
97
98 (options, args) = options_parser.parse_args ()
99
100 if not os.path.isdir (options.top_source_dir):
101     sys.stderr.write ("Error: top source: %s: not a directory\n" % options.top_source_dir)
102     sys.exit (4)
103
104 lys_from_lsr = os.path.normpath (os.path.join (options.top_source_dir, lys_from_lsr))
105 new_lys = os.path.normpath (os.path.join (options.top_source_dir, new_lys))
106 sys.path.append (os.path.normpath (os.path.join (options.top_source_dir, 'python')))
107 import langdefs
108 texidoc_dirs = [
109     os.path.normpath (os.path.join (options.top_source_dir, 'Documentation', language_code, 'texidocs'))
110     for language_code in langdefs.LANGDICT]
111
112 if not os.path.isdir (lys_from_lsr):
113     sys.stderr.write ("Error: snippets path: %s: not a directory\n" % lys_from_lsr)
114     sys.exit (3)
115 if not os.path.isdir (new_lys):
116     sys.stderr.write ("Error: new snippets path: %s: not a directory\n" % lys_from_lsr)
117     sys.exit (3)
118
119 ly_output_ok = False
120 if os.path.isdir (options.ly_output):
121     ly_output = options.ly_output
122     ly_output_ok = True
123 elif os.path.exists (options.ly_output):
124     try:
125         os.unlink (options.ly_output)
126     except Exception as e:
127         sys.stderr.write ("Warning: could not delete file before creating directory: %s\n" % e)
128     else:
129         try:
130             os.makedirs (options.ly_output)
131         except Exception as e:
132             sys.stderr.write ("Warning: could not create directory: %s\n" % e)
133         else:
134             ly_output = options.ly_output
135             ly_output_ok = True
136 else:
137     try:
138         os.makedirs (options.ly_output)
139     except Exception as e:
140         sys.stderr.write ("Warning: could not create directory: %s\n" % e)
141     else:
142         ly_output = options.ly_output
143         ly_output_ok = True
144 if not ly_output_ok:
145     ly_output = tempfile.gettempdir ()
146     sys.stderr.write ("Warning: could not use or create directory %s, using default %s\n" % (options.ly_output, ly_output))
147
148 def exit_with_usage (n=0):
149     options_parser.print_help (sys.stderr)
150     sys.exit (n)
151
152 if len (args):
153     in_dir = args[0]
154     if not (os.path.isdir (in_dir)):
155         sys.stderr.write ("Error: %s: not a directory\n" % in_dir)
156         sys.exit (4)
157     if len (args) > 1:
158         exit_with_usage (2)
159 else:
160     in_dir = '.'
161
162 if options.convert_ly == "LY_PATH/convert-ly":
163     convert_ly = os.path.join (options.bin_path, "convert-ly")
164 else:
165     convert_ly = options.convert_ly
166 if not os.path.exists (convert_ly):
167     sys.stderr.write ("Warning: %s: no such file\n" % convert_ly)
168     convert_ly = "convert-ly"
169 if options.lilypond_bin == "LY_PATH/lilypond":
170     lilypond_bin = os.path.join (options.bin_path, "lilypond")
171 else:
172     lilypond_bin = options.lilypond_bin
173 if not os.path.exists (lilypond_bin):
174     sys.stderr.write ("Warning: %s: no such file\n" % lilypond_bin)
175     lilypond_bin = "lilypond"
176 sys.stderr.write ("Using %s, %s\n" % (convert_ly, lilypond_bin))
177
178 tags = os.listdir (in_dir)
179
180 unsafe = []
181 unconverted = []
182 notags_files = []
183
184 # mark the section that will be printed verbatim by lilypond-book
185 end_header_re = re.compile ('(\\header {.+?doctitle = ".+?})\n', re.M | re.S)
186
187 doctitle_re = re.compile (r'(doctitle[a-zA-Z_]{0,6}\s*=\s*")((?:\\"|[^"\n])*)"')
188 texinfo_q_re = re.compile (r'@q{(.*?)}')
189 texinfo_qq_re = re.compile (r'@qq{(.*?)}')
190 def doctitle_sub (title_match):
191     # Comma forbidden in Texinfo node name
192     title = title_match.group (2).replace (',', '')
193     title = texinfo_q_re.sub (r"`\1'", title)
194     title = texinfo_qq_re.sub (r'\"\1\"', title)
195     return title_match.group (1) + title + '"'
196
197 def mark_verbatim_section (ly_code):
198     return end_header_re.sub ('\\1 % begin verbatim\n\n', ly_code, 1)
199
200 # '% LSR' comments are to be stripped
201 lsr_comment_re = re.compile (r'\s*%+\s*LSR.*')
202 begin_header_re = re.compile (r'\\header\s*{', re.M)
203 ly_new_version_re = re.compile (r'\\version\s*"(.+?)"')
204 strip_white_spaces_re = re.compile (r'[ \t]+(?=\n)')
205 final_empty_lines_re = re.compile (r'\n{2,}$')
206
207 # add tags to ly files from LSR
208 def add_tags (ly_code, tags):
209     return begin_header_re.sub ('\\g<0>\n  lsrtags = "' + tags + '"\n',
210                                 ly_code, 1)
211
212 # for snippets from input/new, add message for earliest working version
213 def add_version (ly_code):
214     return '''%% Note: this file works from version ''' + \
215         ly_new_version_re.search (ly_code).group (1) + '\n'
216
217 def escape_backslashes_in_header(snippet):
218     # ASSUME: the \header exists.
219     header_char_number_start = snippet.find('\header {')
220     header_char_number_end = snippet.find('} % begin verbatim')
221
222     header = snippet[header_char_number_start:header_char_number_end]
223     # only one level of escaping happening here
224     # thanks to raw strings
225     new_header = re.sub(r"@code\{\\([a-zA-Z])", r"@code{\\\\\1", header)
226     escaped_snippet = (snippet[:header_char_number_start] +
227         new_header + snippet[header_char_number_end:])
228     return escaped_snippet
229
230 def copy_ly (srcdir, name, tags):
231     global unsafe
232     global unconverted
233     dest = os.path.join (lys_from_lsr, name)
234     tags = ', '.join (tags)
235     file_path = os.path.join (srcdir, name)
236     sys.stderr.write ("\nmakelsr.py: reading %s\n" % file_path)
237     s = open (file_path).read ()
238
239     s = doctitle_re.sub (doctitle_sub, s)
240     if "new" in srcdir:
241         s = LY_HEADER_NEW + add_version (s) + s
242     else:
243         s = LY_HEADER_LSR + add_tags (s, tags)
244
245     s = mark_verbatim_section (s)
246     s = lsr_comment_re.sub ('', s)
247     s = strip_white_spaces_re.sub ('', s)
248     s = final_empty_lines_re.sub ('\n', s)
249     s = escape_backslashes_in_header (s)
250     sys.stderr.write ("makelsr.py: writing %s\n" % dest)
251     open (dest, 'w').write (s)
252
253     e = os.system (convert_ly+(" -d -e '%s'" % dest))
254     if e:
255         unconverted.append (dest)
256     if os.path.exists (dest + '~'):
257         os.remove (dest + '~')
258     # no need to check snippets from Documentation/snippets/new
259     if not "new" in srcdir:
260         e = os.system (
261             "%s %s -o %s '%s'" %
262             (lilypond_bin, lilypond_flags, ly_output, dest))
263         if e:
264             unsafe.append (dest)
265
266 def read_source_with_dirs (src):
267     s = {}
268     l = {}
269     for tag in tags:
270         srcdir = os.path.join (src, tag)
271         l[tag] = set (map (os.path.basename,
272                            glob.glob (os.path.join (srcdir, '*.ly'))))
273         for f in l[tag]:
274             if f in s:
275                 s[f][1].append (tag)
276             else:
277                 s[f] = (srcdir, [tag])
278     return s, l
279
280
281 tags_re = re.compile ('lsrtags\\s*=\\s*"(.+?)"')
282
283 def read_source (src):
284     s = {}
285     l = dict ([(tag, set()) for tag in tags])
286     for f in glob.glob (os.path.join (src, '*.ly')):
287         basename = os.path.basename (f)
288         m = tags_re.search (open (f, 'r').read ())
289         if m:
290             file_tags = [tag.strip() for tag in m.group (1). split(',')]
291             s[basename] = (src, file_tags)
292             [l[tag].add (basename) for tag in file_tags if tag in tags]
293         else:
294             notags_files.append (f)
295     return s, l
296
297
298 def dump_file_list (file, file_list, update=False):
299     if update:
300         old_list = set (open (file, 'r').read ().splitlines ())
301         old_list.update (file_list)
302         new_list = list (old_list)
303     else:
304         new_list = file_list
305     f = open (file, 'w')
306     f.write ('\n'.join (sorted (new_list)) + '\n')
307
308 ## clean out existing lys and generated files
309 map (os.remove, glob.glob (os.path.join (lys_from_lsr, '*.ly')) +
310      glob.glob (os.path.join (lys_from_lsr, '*.snippet-list')))
311
312 # read LSR source where tags are defined by subdirs
313 snippets, tag_lists = read_source_with_dirs (in_dir)
314
315 # read input/new where tags are directly defined
316 s, l = read_source (new_lys)
317 snippets.update (s)
318 for t in tags:
319     tag_lists[t].update (l[t])
320
321 for (name, (srcdir, tags)) in snippets.items ():
322     copy_ly (srcdir, name, tags)
323 for (tag, file_set) in tag_lists.items ():
324     dump_file_list (os.path.join (lys_from_lsr, tag + '.snippet-list'),
325                     file_set, update=not(in_dir))
326 if unconverted:
327     sys.stderr.write ('These files could not be converted successfully by convert-ly:\n')
328     sys.stderr.write ('\n'.join (unconverted) + '\n\n')
329 if notags_files:
330     sys.stderr.write ('No tags could be found in these files:\n')
331     sys.stderr.write ('\n'.join (notags_files) + '\n\n')
332 if unsafe:
333     dump_file_list ('lsr-unsafe.txt', unsafe)
334     sys.stderr.write ('''
335
336 Unsafe files printed in lsr-unsafe.txt: CHECK MANUALLY!
337   git add %(lys_from_lsr)s/*.ly
338   xargs git diff HEAD < lsr-unsafe.txt
339
340 ''' % vars ())