]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/makelsr.py
adf8681638f72781bbb915979403ff47ad613668
[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
8 sys.path.append ('python')
9 import langdefs
10
11 DEST = os.path.join ('Documentation', 'snippets')
12 NEW_LYS = os.path.join ('Documentation', 'snippets', 'new')
13 TEXIDOCS = [os.path.join ('Documentation', language_code, 'texidocs')
14             for language_code in langdefs.LANGDICT]
15
16 USAGE = '''  Usage: makelsr.py [LSR_SNIPPETS_DIR]
17 This script must be run from top of the source tree;
18 it updates snippets %(DEST)s with snippets
19 from %(NEW_LYS)s or LSR_SNIPPETS_DIR.
20 If a snippet is present in both directories, the one
21 from %(NEW_LYS)s is preferred.
22 ''' % vars ()
23
24 LY_HEADER_LSR = '''%% DO NOT EDIT this file manually; it is automatically
25 %% generated from LSR http://lsr.dsi.unimi.it
26 %% Make any changes in LSR itself, or in Documentation/snippets/new/ ,
27 %% and then run scripts/auxiliar/makelsr.py
28 %%
29 %% This file is in the public domain.
30 '''
31
32 LY_HEADER_NEW = '''%% DO NOT EDIT this file manually; it is automatically
33 %% generated from %s
34 %% Make any changes in Documentation/snippets/new/
35 %% and then run scripts/auxiliar/makelsr.py
36 %%
37 %% This file is in the public domain.
38 ''' % NEW_LYS
39
40 TAGS = []
41 # NR 1
42 TAGS.extend (['pitches', 'rhythms', 'expressive-marks',
43 'repeats', 'simultaneous-notes', 'staff-notation',
44 'editorial-annotations', 'text'])
45 # NR 2
46 TAGS.extend (['vocal-music', 'chords', 'keyboards',
47 'percussion', 'fretted-strings', 'unfretted-strings',
48 'ancient-notation', 'winds', 'world-music'
49 ])
50
51 # other
52 TAGS.extend (['contexts-and-engravers', 'tweaks-and-overrides',
53 'paper-and-layout', 'breaks', 'spacing', 'midi', 'titles', 'template'])
54
55 def exit_with_usage (n=0):
56     sys.stderr.write (USAGE)
57     sys.exit (n)
58
59 if len (sys.argv) >= 2:
60     in_dir = sys.argv[1]
61     if len (sys.argv) >= 3:
62         exit_with_usage (2)
63     if not (os.path.isdir (DEST) and os.path.isdir (NEW_LYS)):
64         exit_with_usage (3)
65 else:
66     in_dir = ''
67
68 # which convert-ly to use
69 if os.path.isfile("out/bin/convert-ly"):
70     conv_path='out/bin/'
71 elif os.path.isfile("build/out/bin/convert-ly"):
72     conv_path='build/out/bin/'
73 else:
74     conv_path=''
75 convert_ly=conv_path+'convert-ly'
76 print 'using '+convert_ly
77
78 unsafe = []
79 unconverted = []
80 notags_files = []
81
82 # mark the section that will be printed verbatim by lilypond-book
83 end_header_re = re.compile ('(\\header {.+?doctitle = ".+?})\n', re.M | re.S)
84
85 doctitle_re = re.compile (r'(doctitle[a-zA-Z_]{0,6}\s*=\s*")((?:\\"|[^"\n])*)"')
86 texinfo_q_re = re.compile (r'@q{(.*?)}')
87 texinfo_qq_re = re.compile (r'@qq{(.*?)}')
88 def doctitle_sub (title_match):
89     # Comma forbidden in Texinfo node name
90     title = title_match.group (2).replace (',', '')
91     title = texinfo_q_re.sub (r"`\1'", title)
92     title = texinfo_qq_re.sub (r'\"\1\"', title)
93     return title_match.group (1) + title + '"'
94
95 def mark_verbatim_section (ly_code):
96     return end_header_re.sub ('\\1 % begin verbatim\n\n', ly_code, 1)
97
98 # '% LSR' comments are to be stripped
99 lsr_comment_re = re.compile (r'\s*%+\s*LSR.*')
100 begin_header_re = re.compile (r'\\header\s*{', re.M)
101 ly_new_version_re = re.compile (r'\\version\s*"(.+?)"')
102 strip_white_spaces_re = re.compile (r'[ \t]+(?=\n)')
103
104 # add tags to ly files from LSR
105 def add_tags (ly_code, tags):
106     return begin_header_re.sub ('\\g<0>\n  lsrtags = "' + tags + '"\n',
107                                 ly_code, 1)
108
109 # for snippets from input/new, add message for earliest working version
110 def add_version (ly_code):
111     return '''%% Note: this file works from version ''' + \
112         ly_new_version_re.search (ly_code).group (1) + '\n'
113
114 s = 'Translation of GIT [Cc]ommittish'
115 texidoc_chunk_re = re.compile (r'^(?:%+\s*' + s + \
116     r'.+)?\s*(?:texidoc|doctitle)([a-zA-Z]{2,4})\s+=(?:.|\n)*?(?=%+\s*' + \
117     s + r'|\n\} % begin verbatim|\n  (?:doctitle|texidoc|lsrtags) |$(?!.|\n))', re.M)
118
119 def update_translated_texidoc (m, snippet_path, visited_languages):
120     base = os.path.splitext (os.path.basename (snippet_path))[0]
121     language_code = m.group (1)
122     visited_languages.append (language_code)
123     texidoc_path = os.path.join ('Documentation', language_code,
124                                  'texidocs', base + '.texidoc')
125     if os.path.isfile (texidoc_path):
126         return open (texidoc_path).read ()
127     else:
128         return m.group (0)
129
130 def escape_backslashes_in_header(snippet):
131     # ASSUME: the \header exists.
132     header_char_number_start = snippet.find('\header {')
133     header_char_number_end = snippet.find('} % begin verbatim')
134
135     header = snippet[header_char_number_start:header_char_number_end]
136     # two levels of escaping happening here -- 4\ means 1\
137     # and the 10\ means two \ backslashes (that's 8\ ), and
138     # one backreference to group 1 (that's two 2\ ).
139     new_header = re.sub("@code\{\\\\([a-zA-Z])", "@code{\\\\\\\\\\1", header)
140     escaped_snippet = (snippet[:header_char_number_start] +
141         new_header + snippet[header_char_number_end:])
142     return escaped_snippet
143
144 def copy_ly (srcdir, name, tags):
145     global unsafe
146     global unconverted
147     dest = os.path.join (DEST, name)
148     tags = ', '.join (tags)
149     s = open (os.path.join (srcdir, name)).read ()
150
151     for path in TEXIDOCS:
152         texidoc_translation_path = \
153             os.path.join (path, os.path.splitext (name)[0] + '.texidoc')
154         if os.path.exists (texidoc_translation_path):
155             texidoc_translation = open (texidoc_translation_path).read ()
156             # Since we want to insert the translations verbatim using a 
157             # regexp, \\ is understood as ONE escaped backslash. So we have
158             # to escape those backslashes once more...
159             texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
160             s = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, s, 1)
161
162     s = doctitle_re.sub (doctitle_sub, s)
163     if in_dir and in_dir in srcdir:
164         s = LY_HEADER_LSR + add_tags (s, tags)
165     else:
166         s = LY_HEADER_NEW + add_version (s) + s
167
168     s = mark_verbatim_section (s)
169     s = lsr_comment_re.sub ('', s)
170     s = strip_white_spaces_re.sub ('', s)
171     s = escape_backslashes_in_header (s)
172     open (dest, 'w').write (s)
173
174     e = os.system (convert_ly+(" -d -e '%s'" % dest))
175     if e:
176         unconverted.append (dest)
177     if os.path.exists (dest + '~'):
178         os.remove (dest + '~')
179     # no need to check snippets from input/new
180     if in_dir and in_dir in srcdir:
181         # -V seems to make unsafe snippets fail nicer/sooner
182         e = os.system ("lilypond -V -dno-print-pages -dsafe -o /tmp/lsrtest '%s'" % dest)
183         if e:
184             unsafe.append (dest)
185
186 def read_source_with_dirs (src):
187     s = {}
188     l = {}
189     for tag in TAGS:
190         srcdir = os.path.join (src, tag)
191         l[tag] = set (map (os.path.basename,
192                            glob.glob (os.path.join (srcdir, '*.ly'))))
193         for f in l[tag]:
194             if f in s:
195                 s[f][1].append (tag)
196             else:
197                 s[f] = (srcdir, [tag])
198     return s, l
199
200
201 tags_re = re.compile ('lsrtags\\s*=\\s*"(.+?)"')
202
203 def read_source (src):
204     s = {}
205     l = dict ([(tag, set()) for tag in TAGS])
206     for f in glob.glob (os.path.join (src, '*.ly')):
207         basename = os.path.basename (f)
208         m = tags_re.search (open (f, 'r').read ())
209         if m:
210             file_tags = [tag.strip() for tag in m.group (1). split(',')]
211             s[basename] = (src, file_tags)
212             [l[tag].add (basename) for tag in file_tags if tag in TAGS]
213         else:
214             notags_files.append (f)
215     return s, l
216
217
218 def dump_file_list (file, file_list, update=False):
219     if update:
220         old_list = set (open (file, 'r').read ().splitlines ())
221         old_list.update (file_list)
222         new_list = list (old_list)
223     else:
224         new_list = file_list
225     f = open (file, 'w')
226     f.write ('\n'.join (sorted (new_list)) + '\n')
227
228 def update_ly_in_place (snippet_path):
229     visited_languages = []
230     contents = open (snippet_path).read ()
231     contents = texidoc_chunk_re.sub \
232         (lambda m: update_translated_texidoc (m,
233                                               snippet_path,
234                                               visited_languages),
235          contents)
236     need_line_break_workaround = False
237     for language_code in langdefs.LANGDICT:
238         if not language_code in visited_languages:
239             base = os.path.splitext (os.path.basename (snippet_path))[0]
240             texidoc_path = os.path.join ('Documentation', language_code,
241                          'texidocs', base + '.texidoc')
242             if os.path.isfile (texidoc_path):
243                 texidoc_translation = open (texidoc_path).read ()
244                 texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
245                 contents = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, contents, 1)
246         else:
247             need_line_break_workaround = True
248     contents = doctitle_re.sub (doctitle_sub, contents)
249     contents = escape_backslashes_in_header (contents)
250
251     # workaround for a bug in the regex's that I'm not smart
252     # enough to figure out.  -gp
253     if need_line_break_workaround:
254         first_translated = contents.find('%% Translation of')
255         keep = contents[:first_translated+5]
256         contents = keep + contents[first_translated+5:].replace('%% Translation of', '\n%% Translation of')
257
258     open (snippet_path, 'w').write (contents)
259
260 if in_dir:
261     ## clean out existing lys and generated files
262     map (os.remove, glob.glob (os.path.join (DEST, '*.ly')) +
263          glob.glob (os.path.join (DEST, '*.snippet-list')))
264
265     # read LSR source where tags are defined by subdirs
266     snippets, tag_lists = read_source_with_dirs (in_dir)
267
268     # read input/new where tags are directly defined
269     s, l = read_source (NEW_LYS)
270     snippets.update (s)
271     for t in TAGS:
272         tag_lists[t].update (l[t])
273 else:
274     snippets, tag_lists = read_source (NEW_LYS)
275     ## update texidocs of snippets that don't come from NEW_LYS
276     for snippet_path in glob.glob (os.path.join (DEST, '*.ly')):
277         if not os.path.basename (snippet_path) in snippets:
278             update_ly_in_place (snippet_path)
279
280 for (name, (srcdir, tags)) in snippets.items ():
281     copy_ly (srcdir, name, tags)
282 for (tag, file_set) in tag_lists.items ():
283     dump_file_list (os.path.join (DEST, tag + '.snippet-list'),
284                     file_set, update=not(in_dir))
285 if unconverted:
286     sys.stderr.write ('These files could not be converted successfully by convert-ly:\n')
287     sys.stderr.write ('\n'.join (unconverted) + '\n\n')
288 if notags_files:
289     sys.stderr.write ('No tags could be found in these files:\n')
290     sys.stderr.write ('\n'.join (notags_files) + '\n\n')
291 if unsafe:
292     dump_file_list ('lsr-unsafe.txt', unsafe)
293     sys.stderr.write ('''
294
295 Unsafe files printed in lsr-unsafe.txt: CHECK MANUALLY!
296   git add %s/*.ly
297   xargs git diff HEAD < lsr-unsafe.txt
298
299 ''' % DEST)