]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/makelsr.py
Merge branch 'master' into lilypond/translation
[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 lilypond_bin=conv_path+'lilypond'
77
78 print 'using '+convert_ly
79
80 unsafe = []
81 unconverted = []
82 notags_files = []
83
84 # mark the section that will be printed verbatim by lilypond-book
85 end_header_re = re.compile ('(\\header {.+?doctitle = ".+?})\n', re.M | re.S)
86
87 doctitle_re = re.compile (r'(doctitle[a-zA-Z_]{0,6}\s*=\s*")((?:\\"|[^"\n])*)"')
88 texinfo_q_re = re.compile (r'@q{(.*?)}')
89 texinfo_qq_re = re.compile (r'@qq{(.*?)}')
90 def doctitle_sub (title_match):
91     # Comma forbidden in Texinfo node name
92     title = title_match.group (2).replace (',', '')
93     title = texinfo_q_re.sub (r"`\1'", title)
94     title = texinfo_qq_re.sub (r'\"\1\"', title)
95     return title_match.group (1) + title + '"'
96
97 def mark_verbatim_section (ly_code):
98     return end_header_re.sub ('\\1 % begin verbatim\n\n', ly_code, 1)
99
100 # '% LSR' comments are to be stripped
101 lsr_comment_re = re.compile (r'\s*%+\s*LSR.*')
102 begin_header_re = re.compile (r'\\header\s*{', re.M)
103 ly_new_version_re = re.compile (r'\\version\s*"(.+?)"')
104 strip_white_spaces_re = re.compile (r'[ \t]+(?=\n)')
105
106 # add tags to ly files from LSR
107 def add_tags (ly_code, tags):
108     return begin_header_re.sub ('\\g<0>\n  lsrtags = "' + tags + '"\n',
109                                 ly_code, 1)
110
111 # for snippets from input/new, add message for earliest working version
112 def add_version (ly_code):
113     return '''%% Note: this file works from version ''' + \
114         ly_new_version_re.search (ly_code).group (1) + '\n'
115
116 s = 'Translation of GIT [Cc]ommittish'
117 texidoc_chunk_re = re.compile (r'^(?:%+\s*' + s + \
118     r'.+)?\s*(?:texidoc|doctitle)([a-zA-Z]{2,4})\s+=(?:.|\n)*?(?=%+\s*' + \
119     s + r'|\n\} % begin verbatim|\n  (?:doctitle|texidoc|lsrtags) |$(?!.|\n))', re.M)
120
121 def update_translated_texidoc (m, snippet_path, visited_languages):
122     base = os.path.splitext (os.path.basename (snippet_path))[0]
123     language_code = m.group (1)
124     visited_languages.append (language_code)
125     texidoc_path = os.path.join ('Documentation', language_code,
126                                  'texidocs', base + '.texidoc')
127     if os.path.isfile (texidoc_path):
128         return open (texidoc_path).read ()
129     else:
130         return m.group (0)
131
132 def escape_backslashes_in_header(snippet):
133     # ASSUME: the \header exists.
134     header_char_number_start = snippet.find('\header {')
135     header_char_number_end = snippet.find('} % begin verbatim')
136
137     header = snippet[header_char_number_start:header_char_number_end]
138     # two levels of escaping happening here -- 4\ means 1\
139     # and the 10\ means two \ backslashes (that's 8\ ), and
140     # one backreference to group 1 (that's two 2\ ).
141     new_header = re.sub("@code\{\\\\([a-zA-Z])", "@code{\\\\\\\\\\1", header)
142     escaped_snippet = (snippet[:header_char_number_start] +
143         new_header + snippet[header_char_number_end:])
144     return escaped_snippet
145
146 def copy_ly (srcdir, name, tags):
147     global unsafe
148     global unconverted
149     dest = os.path.join (DEST, name)
150     tags = ', '.join (tags)
151     s = open (os.path.join (srcdir, name)).read ()
152
153     for path in TEXIDOCS:
154         texidoc_translation_path = \
155             os.path.join (path, os.path.splitext (name)[0] + '.texidoc')
156         if os.path.exists (texidoc_translation_path):
157             texidoc_translation = open (texidoc_translation_path).read ()
158             # Since we want to insert the translations verbatim using a 
159             # regexp, \\ is understood as ONE escaped backslash. So we have
160             # to escape those backslashes once more...
161             texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
162             s = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, s, 1)
163
164     s = doctitle_re.sub (doctitle_sub, s)
165     if in_dir and in_dir in srcdir:
166         s = LY_HEADER_LSR + add_tags (s, tags)
167     else:
168         s = LY_HEADER_NEW + add_version (s) + s
169
170     s = mark_verbatim_section (s)
171     s = lsr_comment_re.sub ('', s)
172     s = strip_white_spaces_re.sub ('', s)
173     s = escape_backslashes_in_header (s)
174     open (dest, 'w').write (s)
175
176     e = os.system (convert_ly+(" -d -e '%s'" % dest))
177     if e:
178         unconverted.append (dest)
179     if os.path.exists (dest + '~'):
180         os.remove (dest + '~')
181     # no need to check snippets from input/new
182     if in_dir and in_dir in srcdir:
183         e = os.system ("%s -dno-print-pages -dsafe -o /tmp/lsrtest '%s'" %(lilypond_bin, dest))
184         if e:
185             unsafe.append (dest)
186
187 def read_source_with_dirs (src):
188     s = {}
189     l = {}
190     for tag in TAGS:
191         srcdir = os.path.join (src, tag)
192         l[tag] = set (map (os.path.basename,
193                            glob.glob (os.path.join (srcdir, '*.ly'))))
194         for f in l[tag]:
195             if f in s:
196                 s[f][1].append (tag)
197             else:
198                 s[f] = (srcdir, [tag])
199     return s, l
200
201
202 tags_re = re.compile ('lsrtags\\s*=\\s*"(.+?)"')
203
204 def read_source (src):
205     s = {}
206     l = dict ([(tag, set()) for tag in TAGS])
207     for f in glob.glob (os.path.join (src, '*.ly')):
208         basename = os.path.basename (f)
209         m = tags_re.search (open (f, 'r').read ())
210         if m:
211             file_tags = [tag.strip() for tag in m.group (1). split(',')]
212             s[basename] = (src, file_tags)
213             [l[tag].add (basename) for tag in file_tags if tag in TAGS]
214         else:
215             notags_files.append (f)
216     return s, l
217
218
219 def dump_file_list (file, file_list, update=False):
220     if update:
221         old_list = set (open (file, 'r').read ().splitlines ())
222         old_list.update (file_list)
223         new_list = list (old_list)
224     else:
225         new_list = file_list
226     f = open (file, 'w')
227     f.write ('\n'.join (sorted (new_list)) + '\n')
228
229 def update_ly_in_place (snippet_path):
230     visited_languages = []
231     contents = open (snippet_path).read ()
232     contents = texidoc_chunk_re.sub \
233         (lambda m: update_translated_texidoc (m,
234                                               snippet_path,
235                                               visited_languages),
236          contents)
237     need_line_break_workaround = False
238     for language_code in langdefs.LANGDICT:
239         if not language_code in visited_languages:
240             base = os.path.splitext (os.path.basename (snippet_path))[0]
241             texidoc_path = os.path.join ('Documentation', language_code,
242                          'texidocs', base + '.texidoc')
243             if os.path.isfile (texidoc_path):
244                 texidoc_translation = open (texidoc_path).read ()
245                 texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
246                 contents = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, contents, 1)
247         else:
248             need_line_break_workaround = True
249     contents = doctitle_re.sub (doctitle_sub, contents)
250     contents = escape_backslashes_in_header (contents)
251
252     # workaround for a bug in the regex's that I'm not smart
253     # enough to figure out.  -gp
254     if need_line_break_workaround:
255         first_translated = contents.find('%% Translation of')
256         keep = contents[:first_translated+5]
257         contents = keep + contents[first_translated+5:].replace('%% Translation of', '\n%% Translation of')
258
259     open (snippet_path, 'w').write (contents)
260
261 if in_dir:
262     ## clean out existing lys and generated files
263     map (os.remove, glob.glob (os.path.join (DEST, '*.ly')) +
264          glob.glob (os.path.join (DEST, '*.snippet-list')))
265
266     # read LSR source where tags are defined by subdirs
267     snippets, tag_lists = read_source_with_dirs (in_dir)
268
269     # read input/new where tags are directly defined
270     s, l = read_source (NEW_LYS)
271     snippets.update (s)
272     for t in TAGS:
273         tag_lists[t].update (l[t])
274 else:
275     snippets, tag_lists = read_source (NEW_LYS)
276     ## update texidocs of snippets that don't come from NEW_LYS
277     for snippet_path in glob.glob (os.path.join (DEST, '*.ly')):
278         if not os.path.basename (snippet_path) in snippets:
279             update_ly_in_place (snippet_path)
280
281 for (name, (srcdir, tags)) in snippets.items ():
282     copy_ly (srcdir, name, tags)
283 for (tag, file_set) in tag_lists.items ():
284     dump_file_list (os.path.join (DEST, tag + '.snippet-list'),
285                     file_set, update=not(in_dir))
286 if unconverted:
287     sys.stderr.write ('These files could not be converted successfully by convert-ly:\n')
288     sys.stderr.write ('\n'.join (unconverted) + '\n\n')
289 if notags_files:
290     sys.stderr.write ('No tags could be found in these files:\n')
291     sys.stderr.write ('\n'.join (notags_files) + '\n\n')
292 if unsafe:
293     dump_file_list ('lsr-unsafe.txt', unsafe)
294     sys.stderr.write ('''
295
296 Unsafe files printed in lsr-unsafe.txt: CHECK MANUALLY!
297   git add %s/*.ly
298   xargs git diff HEAD < lsr-unsafe.txt
299
300 ''' % DEST)