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